7dc79a4bfeec8fa46e03f7170026629b15dd2b22
[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 SimplifyVUnaryOp(SDNode *N);
255     SDValue visitSHL(SDNode *N);
256     SDValue visitSRA(SDNode *N);
257     SDValue visitSRL(SDNode *N);
258     SDValue visitRotate(SDNode *N);
259     SDValue visitCTLZ(SDNode *N);
260     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
261     SDValue visitCTTZ(SDNode *N);
262     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
263     SDValue visitCTPOP(SDNode *N);
264     SDValue visitSELECT(SDNode *N);
265     SDValue visitVSELECT(SDNode *N);
266     SDValue visitSELECT_CC(SDNode *N);
267     SDValue visitSETCC(SDNode *N);
268     SDValue visitSIGN_EXTEND(SDNode *N);
269     SDValue visitZERO_EXTEND(SDNode *N);
270     SDValue visitANY_EXTEND(SDNode *N);
271     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
272     SDValue 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
312     SDValue XformToShuffleWithZero(SDNode *N);
313     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
314
315     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
316
317     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
318     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
319     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
320     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
321                              SDValue N3, ISD::CondCode CC,
322                              bool NotExtCompare = false);
323     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
324                           SDLoc DL, bool foldBooleans = true);
325
326     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
327                            SDValue &CC) const;
328     bool isOneUseSetCC(SDValue N) const;
329
330     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
331                                          unsigned HiOp);
332     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
333     SDValue CombineExtLoad(SDNode *N);
334     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
335     SDValue BuildSDIV(SDNode *N);
336     SDValue BuildSDIVPow2(SDNode *N);
337     SDValue BuildUDIV(SDNode *N);
338     SDValue BuildReciprocalEstimate(SDValue Op);
339     SDValue BuildRsqrtEstimate(SDValue Op);
340     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
341     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
342     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
343                                bool DemandHighBits = true);
344     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
345     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
346                               SDValue InnerPos, SDValue InnerNeg,
347                               unsigned PosOpcode, unsigned NegOpcode,
348                               SDLoc DL);
349     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
350     SDValue ReduceLoadWidth(SDNode *N);
351     SDValue ReduceLoadOpStoreWidth(SDNode *N);
352     SDValue TransformFPLoadStorePair(SDNode *N);
353     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
354     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
355
356     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
357
358     /// Walk up chain skipping non-aliasing memory nodes,
359     /// looking for aliasing nodes and adding them to the Aliases vector.
360     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
361                           SmallVectorImpl<SDValue> &Aliases);
362
363     /// Return true if there is any possibility that the two addresses overlap.
364     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
365
366     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
367     /// chain (aliasing node.)
368     SDValue FindBetterChain(SDNode *N, SDValue Chain);
369
370     /// Holds a pointer to an LSBaseSDNode as well as information on where it
371     /// is located in a sequence of memory operations connected by a chain.
372     struct MemOpLink {
373       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
374       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
375       // Ptr to the mem node.
376       LSBaseSDNode *MemNode;
377       // Offset from the base ptr.
378       int64_t OffsetFromBase;
379       // What is the sequence number of this mem node.
380       // Lowest mem operand in the DAG starts at zero.
381       unsigned SequenceNum;
382     };
383
384     /// This is a helper function for MergeConsecutiveStores. When the source
385     /// elements of the consecutive stores are all constants or all extracted
386     /// vector elements, try to merge them into one larger store.
387     /// \return True if a merged store was created.
388     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
389                                          EVT MemVT, unsigned NumElem,
390                                          bool IsConstantSrc, bool UseVector);
391
392     /// Merge consecutive store operations into a wide store.
393     /// This optimization uses wide integers or vectors when possible.
394     /// \return True if some memory operations were changed.
395     bool MergeConsecutiveStores(StoreSDNode *N);
396
397     /// \brief Try to transform a truncation where C is a constant:
398     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
399     ///
400     /// \p N needs to be a truncation and its first operand an AND. Other
401     /// requirements are checked by the function (e.g. that trunc is
402     /// single-use) and if missed an empty SDValue is returned.
403     SDValue distributeTruncateThroughAnd(SDNode *N);
404
405   public:
406     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
407         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
408           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
409       auto *F = DAG.getMachineFunction().getFunction();
410       ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
411                     F->hasFnAttribute(Attribute::MinSize);
412     }
413
414     /// Runs the dag combiner on all nodes in the work list
415     void Run(CombineLevel AtLevel);
416
417     SelectionDAG &getDAG() const { return DAG; }
418
419     /// Returns a type large enough to hold any valid shift amount - before type
420     /// legalization these can be huge.
421     EVT getShiftAmountTy(EVT LHSTy) {
422       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
423       if (LHSTy.isVector())
424         return LHSTy;
425       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
426                         : TLI.getPointerTy();
427     }
428
429     /// This method returns true if we are running before type legalization or
430     /// if the specified VT is legal.
431     bool isTypeLegal(const EVT &VT) {
432       if (!LegalTypes) return true;
433       return TLI.isTypeLegal(VT);
434     }
435
436     /// Convenience wrapper around TargetLowering::getSetCCResultType
437     EVT getSetCCResultType(EVT VT) const {
438       return TLI.getSetCCResultType(*DAG.getContext(), VT);
439     }
440   };
441 }
442
443
444 namespace {
445 /// This class is a DAGUpdateListener that removes any deleted
446 /// nodes from the worklist.
447 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
448   DAGCombiner &DC;
449 public:
450   explicit WorklistRemover(DAGCombiner &dc)
451     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
452
453   void NodeDeleted(SDNode *N, SDNode *E) override {
454     DC.removeFromWorklist(N);
455   }
456 };
457 }
458
459 //===----------------------------------------------------------------------===//
460 //  TargetLowering::DAGCombinerInfo implementation
461 //===----------------------------------------------------------------------===//
462
463 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
464   ((DAGCombiner*)DC)->AddToWorklist(N);
465 }
466
467 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
468   ((DAGCombiner*)DC)->removeFromWorklist(N);
469 }
470
471 SDValue TargetLowering::DAGCombinerInfo::
472 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
473   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
474 }
475
476 SDValue TargetLowering::DAGCombinerInfo::
477 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
478   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
479 }
480
481
482 SDValue TargetLowering::DAGCombinerInfo::
483 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
484   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
485 }
486
487 void TargetLowering::DAGCombinerInfo::
488 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
489   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
490 }
491
492 //===----------------------------------------------------------------------===//
493 // Helper Functions
494 //===----------------------------------------------------------------------===//
495
496 void DAGCombiner::deleteAndRecombine(SDNode *N) {
497   removeFromWorklist(N);
498
499   // If the operands of this node are only used by the node, they will now be
500   // dead. Make sure to re-visit them and recursively delete dead nodes.
501   for (const SDValue &Op : N->ops())
502     // For an operand generating multiple values, one of the values may
503     // become dead allowing further simplification (e.g. split index
504     // arithmetic from an indexed load).
505     if (Op->hasOneUse() || Op->getNumValues() > 1)
506       AddToWorklist(Op.getNode());
507
508   DAG.DeleteNode(N);
509 }
510
511 /// Return 1 if we can compute the negated form of the specified expression for
512 /// the same cost as the expression itself, or 2 if we can compute the negated
513 /// form more cheaply than the expression itself.
514 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
515                                const TargetLowering &TLI,
516                                const TargetOptions *Options,
517                                unsigned Depth = 0) {
518   // fneg is removable even if it has multiple uses.
519   if (Op.getOpcode() == ISD::FNEG) return 2;
520
521   // Don't allow anything with multiple uses.
522   if (!Op.hasOneUse()) return 0;
523
524   // Don't recurse exponentially.
525   if (Depth > 6) return 0;
526
527   switch (Op.getOpcode()) {
528   default: return false;
529   case ISD::ConstantFP:
530     // Don't invert constant FP values after legalize.  The negated constant
531     // isn't necessarily legal.
532     return LegalOperations ? 0 : 1;
533   case ISD::FADD:
534     // FIXME: determine better conditions for this xform.
535     if (!Options->UnsafeFPMath) return 0;
536
537     // After operation legalization, it might not be legal to create new FSUBs.
538     if (LegalOperations &&
539         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
540       return 0;
541
542     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
543     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
544                                     Options, Depth + 1))
545       return V;
546     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
547     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
548                               Depth + 1);
549   case ISD::FSUB:
550     // We can't turn -(A-B) into B-A when we honor signed zeros.
551     if (!Options->UnsafeFPMath) return 0;
552
553     // fold (fneg (fsub A, B)) -> (fsub B, A)
554     return 1;
555
556   case ISD::FMUL:
557   case ISD::FDIV:
558     if (Options->HonorSignDependentRoundingFPMath()) return 0;
559
560     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
561     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
562                                     Options, Depth + 1))
563       return V;
564
565     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
566                               Depth + 1);
567
568   case ISD::FP_EXTEND:
569   case ISD::FP_ROUND:
570   case ISD::FSIN:
571     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
572                               Depth + 1);
573   }
574 }
575
576 /// If isNegatibleForFree returns true, return the newly negated expression.
577 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
578                                     bool LegalOperations, unsigned Depth = 0) {
579   const TargetOptions &Options = DAG.getTarget().Options;
580   // fneg is removable even if it has multiple uses.
581   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
582
583   // Don't allow anything with multiple uses.
584   assert(Op.hasOneUse() && "Unknown reuse!");
585
586   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
587   switch (Op.getOpcode()) {
588   default: llvm_unreachable("Unknown code");
589   case ISD::ConstantFP: {
590     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
591     V.changeSign();
592     return DAG.getConstantFP(V, Op.getValueType());
593   }
594   case ISD::FADD:
595     // FIXME: determine better conditions for this xform.
596     assert(Options.UnsafeFPMath);
597
598     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
599     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
600                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
601       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
602                          GetNegatedExpression(Op.getOperand(0), DAG,
603                                               LegalOperations, Depth+1),
604                          Op.getOperand(1));
605     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
606     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
607                        GetNegatedExpression(Op.getOperand(1), DAG,
608                                             LegalOperations, Depth+1),
609                        Op.getOperand(0));
610   case ISD::FSUB:
611     // We can't turn -(A-B) into B-A when we honor signed zeros.
612     assert(Options.UnsafeFPMath);
613
614     // fold (fneg (fsub 0, B)) -> B
615     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
616       if (N0CFP->getValueAPF().isZero())
617         return Op.getOperand(1);
618
619     // fold (fneg (fsub A, B)) -> (fsub B, A)
620     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
621                        Op.getOperand(1), Op.getOperand(0));
622
623   case ISD::FMUL:
624   case ISD::FDIV:
625     assert(!Options.HonorSignDependentRoundingFPMath());
626
627     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
628     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
629                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
630       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
631                          GetNegatedExpression(Op.getOperand(0), DAG,
632                                               LegalOperations, Depth+1),
633                          Op.getOperand(1));
634
635     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
636     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
637                        Op.getOperand(0),
638                        GetNegatedExpression(Op.getOperand(1), DAG,
639                                             LegalOperations, Depth+1));
640
641   case ISD::FP_EXTEND:
642   case ISD::FSIN:
643     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
644                        GetNegatedExpression(Op.getOperand(0), DAG,
645                                             LegalOperations, Depth+1));
646   case ISD::FP_ROUND:
647       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
648                          GetNegatedExpression(Op.getOperand(0), DAG,
649                                               LegalOperations, Depth+1),
650                          Op.getOperand(1));
651   }
652 }
653
654 // Return true if this node is a setcc, or is a select_cc
655 // that selects between the target values used for true and false, making it
656 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
657 // the appropriate nodes based on the type of node we are checking. This
658 // simplifies life a bit for the callers.
659 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
660                                     SDValue &CC) const {
661   if (N.getOpcode() == ISD::SETCC) {
662     LHS = N.getOperand(0);
663     RHS = N.getOperand(1);
664     CC  = N.getOperand(2);
665     return true;
666   }
667
668   if (N.getOpcode() != ISD::SELECT_CC ||
669       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
670       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
671     return false;
672
673   if (TLI.getBooleanContents(N.getValueType()) ==
674       TargetLowering::UndefinedBooleanContent)
675     return false;
676
677   LHS = N.getOperand(0);
678   RHS = N.getOperand(1);
679   CC  = N.getOperand(4);
680   return true;
681 }
682
683 /// Return true if this is a SetCC-equivalent operation with only one use.
684 /// If this is true, it allows the users to invert the operation for free when
685 /// it is profitable to do so.
686 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
687   SDValue N0, N1, N2;
688   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
689     return true;
690   return false;
691 }
692
693 /// Returns true if N is a BUILD_VECTOR node whose
694 /// elements are all the same constant or undefined.
695 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
696   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
697   if (!C)
698     return false;
699
700   APInt SplatUndef;
701   unsigned SplatBitSize;
702   bool HasAnyUndefs;
703   EVT EltVT = N->getValueType(0).getVectorElementType();
704   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
705                              HasAnyUndefs) &&
706           EltVT.getSizeInBits() >= SplatBitSize);
707 }
708
709 // \brief Returns the SDNode if it is a constant BuildVector or constant.
710 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
711   if (isa<ConstantSDNode>(N))
712     return N.getNode();
713   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
714   if (BV && BV->isConstant())
715     return BV;
716   return nullptr;
717 }
718
719 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
720 // int.
721 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
722   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
723     return CN;
724
725   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
726     BitVector UndefElements;
727     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
728
729     // BuildVectors can truncate their operands. Ignore that case here.
730     // FIXME: We blindly ignore splats which include undef which is overly
731     // pessimistic.
732     if (CN && UndefElements.none() &&
733         CN->getValueType(0) == N.getValueType().getScalarType())
734       return CN;
735   }
736
737   return nullptr;
738 }
739
740 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
741 // float.
742 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
743   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
744     return CN;
745
746   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
747     BitVector UndefElements;
748     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
749
750     if (CN && UndefElements.none())
751       return CN;
752   }
753
754   return nullptr;
755 }
756
757 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
758                                     SDValue N0, SDValue N1) {
759   EVT VT = N0.getValueType();
760   if (N0.getOpcode() == Opc) {
761     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
762       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
763         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
764         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R))
765           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
766         return SDValue();
767       }
768       if (N0.hasOneUse()) {
769         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
770         // use
771         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
772         if (!OpNode.getNode())
773           return SDValue();
774         AddToWorklist(OpNode.getNode());
775         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
776       }
777     }
778   }
779
780   if (N1.getOpcode() == Opc) {
781     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
782       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
783         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
784         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L))
785           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
786         return SDValue();
787       }
788       if (N1.hasOneUse()) {
789         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
790         // use
791         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
792         if (!OpNode.getNode())
793           return SDValue();
794         AddToWorklist(OpNode.getNode());
795         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
796       }
797     }
798   }
799
800   return SDValue();
801 }
802
803 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
804                                bool AddTo) {
805   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
806   ++NodesCombined;
807   DEBUG(dbgs() << "\nReplacing.1 ";
808         N->dump(&DAG);
809         dbgs() << "\nWith: ";
810         To[0].getNode()->dump(&DAG);
811         dbgs() << " and " << NumTo-1 << " other values\n");
812   for (unsigned i = 0, e = NumTo; i != e; ++i)
813     assert((!To[i].getNode() ||
814             N->getValueType(i) == To[i].getValueType()) &&
815            "Cannot combine value to value of different type!");
816
817   WorklistRemover DeadNodes(*this);
818   DAG.ReplaceAllUsesWith(N, To);
819   if (AddTo) {
820     // Push the new nodes and any users onto the worklist
821     for (unsigned i = 0, e = NumTo; i != e; ++i) {
822       if (To[i].getNode()) {
823         AddToWorklist(To[i].getNode());
824         AddUsersToWorklist(To[i].getNode());
825       }
826     }
827   }
828
829   // Finally, if the node is now dead, remove it from the graph.  The node
830   // may not be dead if the replacement process recursively simplified to
831   // something else needing this node.
832   if (N->use_empty())
833     deleteAndRecombine(N);
834   return SDValue(N, 0);
835 }
836
837 void DAGCombiner::
838 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
839   // Replace all uses.  If any nodes become isomorphic to other nodes and
840   // are deleted, make sure to remove them from our worklist.
841   WorklistRemover DeadNodes(*this);
842   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
843
844   // Push the new node and any (possibly new) users onto the worklist.
845   AddToWorklist(TLO.New.getNode());
846   AddUsersToWorklist(TLO.New.getNode());
847
848   // Finally, if the node is now dead, remove it from the graph.  The node
849   // may not be dead if the replacement process recursively simplified to
850   // something else needing this node.
851   if (TLO.Old.getNode()->use_empty())
852     deleteAndRecombine(TLO.Old.getNode());
853 }
854
855 /// Check the specified integer node value to see if it can be simplified or if
856 /// things it uses can be simplified by bit propagation. If so, return true.
857 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
858   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
859   APInt KnownZero, KnownOne;
860   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
861     return false;
862
863   // Revisit the node.
864   AddToWorklist(Op.getNode());
865
866   // Replace the old value with the new one.
867   ++NodesCombined;
868   DEBUG(dbgs() << "\nReplacing.2 ";
869         TLO.Old.getNode()->dump(&DAG);
870         dbgs() << "\nWith: ";
871         TLO.New.getNode()->dump(&DAG);
872         dbgs() << '\n');
873
874   CommitTargetLoweringOpt(TLO);
875   return true;
876 }
877
878 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
879   SDLoc dl(Load);
880   EVT VT = Load->getValueType(0);
881   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
882
883   DEBUG(dbgs() << "\nReplacing.9 ";
884         Load->dump(&DAG);
885         dbgs() << "\nWith: ";
886         Trunc.getNode()->dump(&DAG);
887         dbgs() << '\n');
888   WorklistRemover DeadNodes(*this);
889   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
890   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
891   deleteAndRecombine(Load);
892   AddToWorklist(Trunc.getNode());
893 }
894
895 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
896   Replace = false;
897   SDLoc dl(Op);
898   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
899     EVT MemVT = LD->getMemoryVT();
900     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
901       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
902                                                        : ISD::EXTLOAD)
903       : LD->getExtensionType();
904     Replace = true;
905     return DAG.getExtLoad(ExtType, dl, PVT,
906                           LD->getChain(), LD->getBasePtr(),
907                           MemVT, LD->getMemOperand());
908   }
909
910   unsigned Opc = Op.getOpcode();
911   switch (Opc) {
912   default: break;
913   case ISD::AssertSext:
914     return DAG.getNode(ISD::AssertSext, dl, PVT,
915                        SExtPromoteOperand(Op.getOperand(0), PVT),
916                        Op.getOperand(1));
917   case ISD::AssertZext:
918     return DAG.getNode(ISD::AssertZext, dl, PVT,
919                        ZExtPromoteOperand(Op.getOperand(0), PVT),
920                        Op.getOperand(1));
921   case ISD::Constant: {
922     unsigned ExtOpc =
923       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
924     return DAG.getNode(ExtOpc, dl, PVT, Op);
925   }
926   }
927
928   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
929     return SDValue();
930   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
931 }
932
933 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
934   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
935     return SDValue();
936   EVT OldVT = Op.getValueType();
937   SDLoc dl(Op);
938   bool Replace = false;
939   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
940   if (!NewOp.getNode())
941     return SDValue();
942   AddToWorklist(NewOp.getNode());
943
944   if (Replace)
945     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
946   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
947                      DAG.getValueType(OldVT));
948 }
949
950 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
951   EVT OldVT = Op.getValueType();
952   SDLoc dl(Op);
953   bool Replace = false;
954   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
955   if (!NewOp.getNode())
956     return SDValue();
957   AddToWorklist(NewOp.getNode());
958
959   if (Replace)
960     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
961   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
962 }
963
964 /// Promote the specified integer binary operation if the target indicates it is
965 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
966 /// i32 since i16 instructions are longer.
967 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
968   if (!LegalOperations)
969     return SDValue();
970
971   EVT VT = Op.getValueType();
972   if (VT.isVector() || !VT.isInteger())
973     return SDValue();
974
975   // If operation type is 'undesirable', e.g. i16 on x86, consider
976   // promoting it.
977   unsigned Opc = Op.getOpcode();
978   if (TLI.isTypeDesirableForOp(Opc, VT))
979     return SDValue();
980
981   EVT PVT = VT;
982   // Consult target whether it is a good idea to promote this operation and
983   // what's the right type to promote it to.
984   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
985     assert(PVT != VT && "Don't know what type to promote to!");
986
987     bool Replace0 = false;
988     SDValue N0 = Op.getOperand(0);
989     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
990     if (!NN0.getNode())
991       return SDValue();
992
993     bool Replace1 = false;
994     SDValue N1 = Op.getOperand(1);
995     SDValue NN1;
996     if (N0 == N1)
997       NN1 = NN0;
998     else {
999       NN1 = PromoteOperand(N1, PVT, Replace1);
1000       if (!NN1.getNode())
1001         return SDValue();
1002     }
1003
1004     AddToWorklist(NN0.getNode());
1005     if (NN1.getNode())
1006       AddToWorklist(NN1.getNode());
1007
1008     if (Replace0)
1009       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1010     if (Replace1)
1011       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1012
1013     DEBUG(dbgs() << "\nPromoting ";
1014           Op.getNode()->dump(&DAG));
1015     SDLoc dl(Op);
1016     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1017                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1018   }
1019   return SDValue();
1020 }
1021
1022 /// Promote the specified integer shift operation if the target indicates it is
1023 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1024 /// i32 since i16 instructions are longer.
1025 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1026   if (!LegalOperations)
1027     return SDValue();
1028
1029   EVT VT = Op.getValueType();
1030   if (VT.isVector() || !VT.isInteger())
1031     return SDValue();
1032
1033   // If operation type is 'undesirable', e.g. i16 on x86, consider
1034   // promoting it.
1035   unsigned Opc = Op.getOpcode();
1036   if (TLI.isTypeDesirableForOp(Opc, VT))
1037     return SDValue();
1038
1039   EVT PVT = VT;
1040   // Consult target whether it is a good idea to promote this operation and
1041   // what's the right type to promote it to.
1042   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1043     assert(PVT != VT && "Don't know what type to promote to!");
1044
1045     bool Replace = false;
1046     SDValue N0 = Op.getOperand(0);
1047     if (Opc == ISD::SRA)
1048       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1049     else if (Opc == ISD::SRL)
1050       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1051     else
1052       N0 = PromoteOperand(N0, PVT, Replace);
1053     if (!N0.getNode())
1054       return SDValue();
1055
1056     AddToWorklist(N0.getNode());
1057     if (Replace)
1058       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1059
1060     DEBUG(dbgs() << "\nPromoting ";
1061           Op.getNode()->dump(&DAG));
1062     SDLoc dl(Op);
1063     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1064                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1065   }
1066   return SDValue();
1067 }
1068
1069 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1070   if (!LegalOperations)
1071     return SDValue();
1072
1073   EVT VT = Op.getValueType();
1074   if (VT.isVector() || !VT.isInteger())
1075     return SDValue();
1076
1077   // If operation type is 'undesirable', e.g. i16 on x86, consider
1078   // promoting it.
1079   unsigned Opc = Op.getOpcode();
1080   if (TLI.isTypeDesirableForOp(Opc, VT))
1081     return SDValue();
1082
1083   EVT PVT = VT;
1084   // Consult target whether it is a good idea to promote this operation and
1085   // what's the right type to promote it to.
1086   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1087     assert(PVT != VT && "Don't know what type to promote to!");
1088     // fold (aext (aext x)) -> (aext x)
1089     // fold (aext (zext x)) -> (zext x)
1090     // fold (aext (sext x)) -> (sext x)
1091     DEBUG(dbgs() << "\nPromoting ";
1092           Op.getNode()->dump(&DAG));
1093     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1094   }
1095   return SDValue();
1096 }
1097
1098 bool DAGCombiner::PromoteLoad(SDValue Op) {
1099   if (!LegalOperations)
1100     return false;
1101
1102   EVT VT = Op.getValueType();
1103   if (VT.isVector() || !VT.isInteger())
1104     return false;
1105
1106   // If operation type is 'undesirable', e.g. i16 on x86, consider
1107   // promoting it.
1108   unsigned Opc = Op.getOpcode();
1109   if (TLI.isTypeDesirableForOp(Opc, VT))
1110     return false;
1111
1112   EVT PVT = VT;
1113   // Consult target whether it is a good idea to promote this operation and
1114   // what's the right type to promote it to.
1115   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1116     assert(PVT != VT && "Don't know what type to promote to!");
1117
1118     SDLoc dl(Op);
1119     SDNode *N = Op.getNode();
1120     LoadSDNode *LD = cast<LoadSDNode>(N);
1121     EVT MemVT = LD->getMemoryVT();
1122     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1123       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1124                                                        : ISD::EXTLOAD)
1125       : LD->getExtensionType();
1126     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1127                                    LD->getChain(), LD->getBasePtr(),
1128                                    MemVT, LD->getMemOperand());
1129     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1130
1131     DEBUG(dbgs() << "\nPromoting ";
1132           N->dump(&DAG);
1133           dbgs() << "\nTo: ";
1134           Result.getNode()->dump(&DAG);
1135           dbgs() << '\n');
1136     WorklistRemover DeadNodes(*this);
1137     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1138     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1139     deleteAndRecombine(N);
1140     AddToWorklist(Result.getNode());
1141     return true;
1142   }
1143   return false;
1144 }
1145
1146 /// \brief Recursively delete a node which has no uses and any operands for
1147 /// which it is the only use.
1148 ///
1149 /// Note that this both deletes the nodes and removes them from the worklist.
1150 /// It also adds any nodes who have had a user deleted to the worklist as they
1151 /// may now have only one use and subject to other combines.
1152 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1153   if (!N->use_empty())
1154     return false;
1155
1156   SmallSetVector<SDNode *, 16> Nodes;
1157   Nodes.insert(N);
1158   do {
1159     N = Nodes.pop_back_val();
1160     if (!N)
1161       continue;
1162
1163     if (N->use_empty()) {
1164       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1165         Nodes.insert(N->getOperand(i).getNode());
1166
1167       removeFromWorklist(N);
1168       DAG.DeleteNode(N);
1169     } else {
1170       AddToWorklist(N);
1171     }
1172   } while (!Nodes.empty());
1173   return true;
1174 }
1175
1176 //===----------------------------------------------------------------------===//
1177 //  Main DAG Combiner implementation
1178 //===----------------------------------------------------------------------===//
1179
1180 void DAGCombiner::Run(CombineLevel AtLevel) {
1181   // set the instance variables, so that the various visit routines may use it.
1182   Level = AtLevel;
1183   LegalOperations = Level >= AfterLegalizeVectorOps;
1184   LegalTypes = Level >= AfterLegalizeTypes;
1185
1186   // Early exit if this basic block is in an optnone function.
1187   if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
1188           Attribute::OptimizeNone))
1189     return;
1190
1191   // Add all the dag nodes to the worklist.
1192   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1193        E = DAG.allnodes_end(); I != E; ++I)
1194     AddToWorklist(I);
1195
1196   // Create a dummy node (which is not added to allnodes), that adds a reference
1197   // to the root node, preventing it from being deleted, and tracking any
1198   // changes of the root.
1199   HandleSDNode Dummy(DAG.getRoot());
1200
1201   // while the worklist isn't empty, find a node and
1202   // try and combine it.
1203   while (!WorklistMap.empty()) {
1204     SDNode *N;
1205     // The Worklist holds the SDNodes in order, but it may contain null entries.
1206     do {
1207       N = Worklist.pop_back_val();
1208     } while (!N);
1209
1210     bool GoodWorklistEntry = WorklistMap.erase(N);
1211     (void)GoodWorklistEntry;
1212     assert(GoodWorklistEntry &&
1213            "Found a worklist entry without a corresponding map entry!");
1214
1215     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1216     // N is deleted from the DAG, since they too may now be dead or may have a
1217     // reduced number of uses, allowing other xforms.
1218     if (recursivelyDeleteUnusedNodes(N))
1219       continue;
1220
1221     WorklistRemover DeadNodes(*this);
1222
1223     // If this combine is running after legalizing the DAG, re-legalize any
1224     // nodes pulled off the worklist.
1225     if (Level == AfterLegalizeDAG) {
1226       SmallSetVector<SDNode *, 16> UpdatedNodes;
1227       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1228
1229       for (SDNode *LN : UpdatedNodes) {
1230         AddToWorklist(LN);
1231         AddUsersToWorklist(LN);
1232       }
1233       if (!NIsValid)
1234         continue;
1235     }
1236
1237     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1238
1239     // Add any operands of the new node which have not yet been combined to the
1240     // worklist as well. Because the worklist uniques things already, this
1241     // won't repeatedly process the same operand.
1242     CombinedNodes.insert(N);
1243     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1244       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1245         AddToWorklist(N->getOperand(i).getNode());
1246
1247     SDValue RV = combine(N);
1248
1249     if (!RV.getNode())
1250       continue;
1251
1252     ++NodesCombined;
1253
1254     // If we get back the same node we passed in, rather than a new node or
1255     // zero, we know that the node must have defined multiple values and
1256     // CombineTo was used.  Since CombineTo takes care of the worklist
1257     // mechanics for us, we have no work to do in this case.
1258     if (RV.getNode() == N)
1259       continue;
1260
1261     assert(N->getOpcode() != ISD::DELETED_NODE &&
1262            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1263            "Node was deleted but visit returned new node!");
1264
1265     DEBUG(dbgs() << " ... into: ";
1266           RV.getNode()->dump(&DAG));
1267
1268     // Transfer debug value.
1269     DAG.TransferDbgValues(SDValue(N, 0), RV);
1270     if (N->getNumValues() == RV.getNode()->getNumValues())
1271       DAG.ReplaceAllUsesWith(N, RV.getNode());
1272     else {
1273       assert(N->getValueType(0) == RV.getValueType() &&
1274              N->getNumValues() == 1 && "Type mismatch");
1275       SDValue OpV = RV;
1276       DAG.ReplaceAllUsesWith(N, &OpV);
1277     }
1278
1279     // Push the new node and any users onto the worklist
1280     AddToWorklist(RV.getNode());
1281     AddUsersToWorklist(RV.getNode());
1282
1283     // Finally, if the node is now dead, remove it from the graph.  The node
1284     // may not be dead if the replacement process recursively simplified to
1285     // something else needing this node. This will also take care of adding any
1286     // operands which have lost a user to the worklist.
1287     recursivelyDeleteUnusedNodes(N);
1288   }
1289
1290   // If the root changed (e.g. it was a dead load, update the root).
1291   DAG.setRoot(Dummy.getValue());
1292   DAG.RemoveDeadNodes();
1293 }
1294
1295 SDValue DAGCombiner::visit(SDNode *N) {
1296   switch (N->getOpcode()) {
1297   default: break;
1298   case ISD::TokenFactor:        return visitTokenFactor(N);
1299   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1300   case ISD::ADD:                return visitADD(N);
1301   case ISD::SUB:                return visitSUB(N);
1302   case ISD::ADDC:               return visitADDC(N);
1303   case ISD::SUBC:               return visitSUBC(N);
1304   case ISD::ADDE:               return visitADDE(N);
1305   case ISD::SUBE:               return visitSUBE(N);
1306   case ISD::MUL:                return visitMUL(N);
1307   case ISD::SDIV:               return visitSDIV(N);
1308   case ISD::UDIV:               return visitUDIV(N);
1309   case ISD::SREM:               return visitSREM(N);
1310   case ISD::UREM:               return visitUREM(N);
1311   case ISD::MULHU:              return visitMULHU(N);
1312   case ISD::MULHS:              return visitMULHS(N);
1313   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1314   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1315   case ISD::SMULO:              return visitSMULO(N);
1316   case ISD::UMULO:              return visitUMULO(N);
1317   case ISD::SDIVREM:            return visitSDIVREM(N);
1318   case ISD::UDIVREM:            return visitUDIVREM(N);
1319   case ISD::AND:                return visitAND(N);
1320   case ISD::OR:                 return visitOR(N);
1321   case ISD::XOR:                return visitXOR(N);
1322   case ISD::SHL:                return visitSHL(N);
1323   case ISD::SRA:                return visitSRA(N);
1324   case ISD::SRL:                return visitSRL(N);
1325   case ISD::ROTR:
1326   case ISD::ROTL:               return visitRotate(N);
1327   case ISD::CTLZ:               return visitCTLZ(N);
1328   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1329   case ISD::CTTZ:               return visitCTTZ(N);
1330   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1331   case ISD::CTPOP:              return visitCTPOP(N);
1332   case ISD::SELECT:             return visitSELECT(N);
1333   case ISD::VSELECT:            return visitVSELECT(N);
1334   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1335   case ISD::SETCC:              return visitSETCC(N);
1336   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1337   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1338   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1339   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1340   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1341   case ISD::BITCAST:            return visitBITCAST(N);
1342   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1343   case ISD::FADD:               return visitFADD(N);
1344   case ISD::FSUB:               return visitFSUB(N);
1345   case ISD::FMUL:               return visitFMUL(N);
1346   case ISD::FMA:                return visitFMA(N);
1347   case ISD::FDIV:               return visitFDIV(N);
1348   case ISD::FREM:               return visitFREM(N);
1349   case ISD::FSQRT:              return visitFSQRT(N);
1350   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1351   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1352   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1353   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1354   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1355   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1356   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1357   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1358   case ISD::FNEG:               return visitFNEG(N);
1359   case ISD::FABS:               return visitFABS(N);
1360   case ISD::FFLOOR:             return visitFFLOOR(N);
1361   case ISD::FMINNUM:            return visitFMINNUM(N);
1362   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1363   case ISD::FCEIL:              return visitFCEIL(N);
1364   case ISD::FTRUNC:             return visitFTRUNC(N);
1365   case ISD::BRCOND:             return visitBRCOND(N);
1366   case ISD::BR_CC:              return visitBR_CC(N);
1367   case ISD::LOAD:               return visitLOAD(N);
1368   case ISD::STORE:              return visitSTORE(N);
1369   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1370   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1371   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1372   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1373   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1374   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1375   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1376   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1377   case ISD::MLOAD:              return visitMLOAD(N);
1378   case ISD::MSTORE:             return visitMSTORE(N);
1379   }
1380   return SDValue();
1381 }
1382
1383 SDValue DAGCombiner::combine(SDNode *N) {
1384   SDValue RV = visit(N);
1385
1386   // If nothing happened, try a target-specific DAG combine.
1387   if (!RV.getNode()) {
1388     assert(N->getOpcode() != ISD::DELETED_NODE &&
1389            "Node was deleted but visit returned NULL!");
1390
1391     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1392         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1393
1394       // Expose the DAG combiner to the target combiner impls.
1395       TargetLowering::DAGCombinerInfo
1396         DagCombineInfo(DAG, Level, false, this);
1397
1398       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1399     }
1400   }
1401
1402   // If nothing happened still, try promoting the operation.
1403   if (!RV.getNode()) {
1404     switch (N->getOpcode()) {
1405     default: break;
1406     case ISD::ADD:
1407     case ISD::SUB:
1408     case ISD::MUL:
1409     case ISD::AND:
1410     case ISD::OR:
1411     case ISD::XOR:
1412       RV = PromoteIntBinOp(SDValue(N, 0));
1413       break;
1414     case ISD::SHL:
1415     case ISD::SRA:
1416     case ISD::SRL:
1417       RV = PromoteIntShiftOp(SDValue(N, 0));
1418       break;
1419     case ISD::SIGN_EXTEND:
1420     case ISD::ZERO_EXTEND:
1421     case ISD::ANY_EXTEND:
1422       RV = PromoteExtend(SDValue(N, 0));
1423       break;
1424     case ISD::LOAD:
1425       if (PromoteLoad(SDValue(N, 0)))
1426         RV = SDValue(N, 0);
1427       break;
1428     }
1429   }
1430
1431   // If N is a commutative binary node, try commuting it to enable more
1432   // sdisel CSE.
1433   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1434       N->getNumValues() == 1) {
1435     SDValue N0 = N->getOperand(0);
1436     SDValue N1 = N->getOperand(1);
1437
1438     // Constant operands are canonicalized to RHS.
1439     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1440       SDValue Ops[] = {N1, N0};
1441       SDNode *CSENode;
1442       if (const BinaryWithFlagsSDNode *BinNode =
1443               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1444         CSENode = DAG.getNodeIfExists(
1445             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1446             BinNode->hasNoSignedWrap(), BinNode->isExact());
1447       } else {
1448         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1449       }
1450       if (CSENode)
1451         return SDValue(CSENode, 0);
1452     }
1453   }
1454
1455   return RV;
1456 }
1457
1458 /// Given a node, return its input chain if it has one, otherwise return a null
1459 /// sd operand.
1460 static SDValue getInputChainForNode(SDNode *N) {
1461   if (unsigned NumOps = N->getNumOperands()) {
1462     if (N->getOperand(0).getValueType() == MVT::Other)
1463       return N->getOperand(0);
1464     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1465       return N->getOperand(NumOps-1);
1466     for (unsigned i = 1; i < NumOps-1; ++i)
1467       if (N->getOperand(i).getValueType() == MVT::Other)
1468         return N->getOperand(i);
1469   }
1470   return SDValue();
1471 }
1472
1473 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1474   // If N has two operands, where one has an input chain equal to the other,
1475   // the 'other' chain is redundant.
1476   if (N->getNumOperands() == 2) {
1477     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1478       return N->getOperand(0);
1479     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1480       return N->getOperand(1);
1481   }
1482
1483   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1484   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1485   SmallPtrSet<SDNode*, 16> SeenOps;
1486   bool Changed = false;             // If we should replace this token factor.
1487
1488   // Start out with this token factor.
1489   TFs.push_back(N);
1490
1491   // Iterate through token factors.  The TFs grows when new token factors are
1492   // encountered.
1493   for (unsigned i = 0; i < TFs.size(); ++i) {
1494     SDNode *TF = TFs[i];
1495
1496     // Check each of the operands.
1497     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1498       SDValue Op = TF->getOperand(i);
1499
1500       switch (Op.getOpcode()) {
1501       case ISD::EntryToken:
1502         // Entry tokens don't need to be added to the list. They are
1503         // redundant.
1504         Changed = true;
1505         break;
1506
1507       case ISD::TokenFactor:
1508         if (Op.hasOneUse() &&
1509             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1510           // Queue up for processing.
1511           TFs.push_back(Op.getNode());
1512           // Clean up in case the token factor is removed.
1513           AddToWorklist(Op.getNode());
1514           Changed = true;
1515           break;
1516         }
1517         // Fall thru
1518
1519       default:
1520         // Only add if it isn't already in the list.
1521         if (SeenOps.insert(Op.getNode()).second)
1522           Ops.push_back(Op);
1523         else
1524           Changed = true;
1525         break;
1526       }
1527     }
1528   }
1529
1530   SDValue Result;
1531
1532   // If we've changed things around then replace token factor.
1533   if (Changed) {
1534     if (Ops.empty()) {
1535       // The entry token is the only possible outcome.
1536       Result = DAG.getEntryNode();
1537     } else {
1538       // New and improved token factor.
1539       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1540     }
1541
1542     // Add users to worklist if AA is enabled, since it may introduce
1543     // a lot of new chained token factors while removing memory deps.
1544     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1545       : DAG.getSubtarget().useAA();
1546     return CombineTo(N, Result, UseAA /*add to worklist*/);
1547   }
1548
1549   return Result;
1550 }
1551
1552 /// MERGE_VALUES can always be eliminated.
1553 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1554   WorklistRemover DeadNodes(*this);
1555   // Replacing results may cause a different MERGE_VALUES to suddenly
1556   // be CSE'd with N, and carry its uses with it. Iterate until no
1557   // uses remain, to ensure that the node can be safely deleted.
1558   // First add the users of this node to the work list so that they
1559   // can be tried again once they have new operands.
1560   AddUsersToWorklist(N);
1561   do {
1562     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1563       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1564   } while (!N->use_empty());
1565   deleteAndRecombine(N);
1566   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1567 }
1568
1569 SDValue DAGCombiner::visitADD(SDNode *N) {
1570   SDValue N0 = N->getOperand(0);
1571   SDValue N1 = N->getOperand(1);
1572   EVT VT = N0.getValueType();
1573
1574   // fold vector ops
1575   if (VT.isVector()) {
1576     SDValue FoldedVOp = SimplifyVBinOp(N);
1577     if (FoldedVOp.getNode()) return FoldedVOp;
1578
1579     // fold (add x, 0) -> x, vector edition
1580     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1581       return N0;
1582     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1583       return N1;
1584   }
1585
1586   // fold (add x, undef) -> undef
1587   if (N0.getOpcode() == ISD::UNDEF)
1588     return N0;
1589   if (N1.getOpcode() == ISD::UNDEF)
1590     return N1;
1591   // fold (add c1, c2) -> c1+c2
1592   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1593   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1594   if (N0C && N1C)
1595     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1596   // canonicalize constant to RHS
1597   if (N0C && !N1C)
1598     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1599   // fold (add x, 0) -> x
1600   if (N1C && N1C->isNullValue())
1601     return N0;
1602   // fold (add Sym, c) -> Sym+c
1603   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1604     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1605         GA->getOpcode() == ISD::GlobalAddress)
1606       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1607                                   GA->getOffset() +
1608                                     (uint64_t)N1C->getSExtValue());
1609   // fold ((c1-A)+c2) -> (c1+c2)-A
1610   if (N1C && N0.getOpcode() == ISD::SUB)
1611     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1612       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1613                          DAG.getConstant(N1C->getAPIntValue()+
1614                                          N0C->getAPIntValue(), VT),
1615                          N0.getOperand(1));
1616   // reassociate add
1617   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1618   if (RADD.getNode())
1619     return RADD;
1620   // fold ((0-A) + B) -> B-A
1621   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1622       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1623     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1624   // fold (A + (0-B)) -> A-B
1625   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1626       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1627     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1628   // fold (A+(B-A)) -> B
1629   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1630     return N1.getOperand(0);
1631   // fold ((B-A)+A) -> B
1632   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1633     return N0.getOperand(0);
1634   // fold (A+(B-(A+C))) to (B-C)
1635   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1636       N0 == N1.getOperand(1).getOperand(0))
1637     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1638                        N1.getOperand(1).getOperand(1));
1639   // fold (A+(B-(C+A))) to (B-C)
1640   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1641       N0 == N1.getOperand(1).getOperand(1))
1642     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1643                        N1.getOperand(1).getOperand(0));
1644   // fold (A+((B-A)+or-C)) to (B+or-C)
1645   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1646       N1.getOperand(0).getOpcode() == ISD::SUB &&
1647       N0 == N1.getOperand(0).getOperand(1))
1648     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1649                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1650
1651   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1652   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1653     SDValue N00 = N0.getOperand(0);
1654     SDValue N01 = N0.getOperand(1);
1655     SDValue N10 = N1.getOperand(0);
1656     SDValue N11 = N1.getOperand(1);
1657
1658     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1659       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1660                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1661                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1662   }
1663
1664   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1665     return SDValue(N, 0);
1666
1667   // fold (a+b) -> (a|b) iff a and b share no bits.
1668   if (VT.isInteger() && !VT.isVector()) {
1669     APInt LHSZero, LHSOne;
1670     APInt RHSZero, RHSOne;
1671     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1672
1673     if (LHSZero.getBoolValue()) {
1674       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1675
1676       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1677       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1678       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1679         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1680           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1681       }
1682     }
1683   }
1684
1685   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1686   if (N1.getOpcode() == ISD::SHL &&
1687       N1.getOperand(0).getOpcode() == ISD::SUB)
1688     if (ConstantSDNode *C =
1689           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1690       if (C->getAPIntValue() == 0)
1691         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1692                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1693                                        N1.getOperand(0).getOperand(1),
1694                                        N1.getOperand(1)));
1695   if (N0.getOpcode() == ISD::SHL &&
1696       N0.getOperand(0).getOpcode() == ISD::SUB)
1697     if (ConstantSDNode *C =
1698           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1699       if (C->getAPIntValue() == 0)
1700         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1701                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1702                                        N0.getOperand(0).getOperand(1),
1703                                        N0.getOperand(1)));
1704
1705   if (N1.getOpcode() == ISD::AND) {
1706     SDValue AndOp0 = N1.getOperand(0);
1707     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1708     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1709     unsigned DestBits = VT.getScalarType().getSizeInBits();
1710
1711     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1712     // and similar xforms where the inner op is either ~0 or 0.
1713     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1714       SDLoc DL(N);
1715       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1716     }
1717   }
1718
1719   // add (sext i1), X -> sub X, (zext i1)
1720   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1721       N0.getOperand(0).getValueType() == MVT::i1 &&
1722       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1723     SDLoc DL(N);
1724     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1725     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1726   }
1727
1728   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1729   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1730     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1731     if (TN->getVT() == MVT::i1) {
1732       SDLoc DL(N);
1733       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1734                                  DAG.getConstant(1, VT));
1735       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1736     }
1737   }
1738
1739   return SDValue();
1740 }
1741
1742 SDValue DAGCombiner::visitADDC(SDNode *N) {
1743   SDValue N0 = N->getOperand(0);
1744   SDValue N1 = N->getOperand(1);
1745   EVT VT = N0.getValueType();
1746
1747   // If the flag result is dead, turn this into an ADD.
1748   if (!N->hasAnyUseOfValue(1))
1749     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1750                      DAG.getNode(ISD::CARRY_FALSE,
1751                                  SDLoc(N), MVT::Glue));
1752
1753   // canonicalize constant to RHS.
1754   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1755   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1756   if (N0C && !N1C)
1757     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1758
1759   // fold (addc x, 0) -> x + no carry out
1760   if (N1C && N1C->isNullValue())
1761     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1762                                         SDLoc(N), MVT::Glue));
1763
1764   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1765   APInt LHSZero, LHSOne;
1766   APInt RHSZero, RHSOne;
1767   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1768
1769   if (LHSZero.getBoolValue()) {
1770     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1771
1772     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1773     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1774     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1775       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1776                        DAG.getNode(ISD::CARRY_FALSE,
1777                                    SDLoc(N), MVT::Glue));
1778   }
1779
1780   return SDValue();
1781 }
1782
1783 SDValue DAGCombiner::visitADDE(SDNode *N) {
1784   SDValue N0 = N->getOperand(0);
1785   SDValue N1 = N->getOperand(1);
1786   SDValue CarryIn = N->getOperand(2);
1787
1788   // canonicalize constant to RHS
1789   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1790   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1791   if (N0C && !N1C)
1792     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1793                        N1, N0, CarryIn);
1794
1795   // fold (adde x, y, false) -> (addc x, y)
1796   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1797     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1798
1799   return SDValue();
1800 }
1801
1802 // Since it may not be valid to emit a fold to zero for vector initializers
1803 // check if we can before folding.
1804 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1805                              SelectionDAG &DAG,
1806                              bool LegalOperations, bool LegalTypes) {
1807   if (!VT.isVector())
1808     return DAG.getConstant(0, VT);
1809   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1810     return DAG.getConstant(0, VT);
1811   return SDValue();
1812 }
1813
1814 SDValue DAGCombiner::visitSUB(SDNode *N) {
1815   SDValue N0 = N->getOperand(0);
1816   SDValue N1 = N->getOperand(1);
1817   EVT VT = N0.getValueType();
1818
1819   // fold vector ops
1820   if (VT.isVector()) {
1821     SDValue FoldedVOp = SimplifyVBinOp(N);
1822     if (FoldedVOp.getNode()) return FoldedVOp;
1823
1824     // fold (sub x, 0) -> x, vector edition
1825     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1826       return N0;
1827   }
1828
1829   // fold (sub x, x) -> 0
1830   // FIXME: Refactor this and xor and other similar operations together.
1831   if (N0 == N1)
1832     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1833   // fold (sub c1, c2) -> c1-c2
1834   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1835   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1836   if (N0C && N1C)
1837     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1838   // fold (sub x, c) -> (add x, -c)
1839   if (N1C)
1840     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1841                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1842   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1843   if (N0C && N0C->isAllOnesValue())
1844     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1845   // fold A-(A-B) -> B
1846   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1847     return N1.getOperand(1);
1848   // fold (A+B)-A -> B
1849   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1850     return N0.getOperand(1);
1851   // fold (A+B)-B -> A
1852   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1853     return N0.getOperand(0);
1854   // fold C2-(A+C1) -> (C2-C1)-A
1855   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1856     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1857   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1858     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1859                                    VT);
1860     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1861                        N1.getOperand(0));
1862   }
1863   // fold ((A+(B+or-C))-B) -> A+or-C
1864   if (N0.getOpcode() == ISD::ADD &&
1865       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1866        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1867       N0.getOperand(1).getOperand(0) == N1)
1868     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1869                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1870   // fold ((A+(C+B))-B) -> A+C
1871   if (N0.getOpcode() == ISD::ADD &&
1872       N0.getOperand(1).getOpcode() == ISD::ADD &&
1873       N0.getOperand(1).getOperand(1) == N1)
1874     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1875                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1876   // fold ((A-(B-C))-C) -> A-B
1877   if (N0.getOpcode() == ISD::SUB &&
1878       N0.getOperand(1).getOpcode() == ISD::SUB &&
1879       N0.getOperand(1).getOperand(1) == N1)
1880     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1881                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1882
1883   // If either operand of a sub is undef, the result is undef
1884   if (N0.getOpcode() == ISD::UNDEF)
1885     return N0;
1886   if (N1.getOpcode() == ISD::UNDEF)
1887     return N1;
1888
1889   // If the relocation model supports it, consider symbol offsets.
1890   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1891     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1892       // fold (sub Sym, c) -> Sym-c
1893       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1894         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1895                                     GA->getOffset() -
1896                                       (uint64_t)N1C->getSExtValue());
1897       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1898       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1899         if (GA->getGlobal() == GB->getGlobal())
1900           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1901                                  VT);
1902     }
1903
1904   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1905   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1906     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1907     if (TN->getVT() == MVT::i1) {
1908       SDLoc DL(N);
1909       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1910                                  DAG.getConstant(1, VT));
1911       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1912     }
1913   }
1914
1915   return SDValue();
1916 }
1917
1918 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1919   SDValue N0 = N->getOperand(0);
1920   SDValue N1 = N->getOperand(1);
1921   EVT VT = N0.getValueType();
1922
1923   // If the flag result is dead, turn this into an SUB.
1924   if (!N->hasAnyUseOfValue(1))
1925     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1926                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1927                                  MVT::Glue));
1928
1929   // fold (subc x, x) -> 0 + no borrow
1930   if (N0 == N1)
1931     return CombineTo(N, DAG.getConstant(0, VT),
1932                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1933                                  MVT::Glue));
1934
1935   // fold (subc x, 0) -> x + no borrow
1936   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1937   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1938   if (N1C && N1C->isNullValue())
1939     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1940                                         MVT::Glue));
1941
1942   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1943   if (N0C && N0C->isAllOnesValue())
1944     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1945                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1946                                  MVT::Glue));
1947
1948   return SDValue();
1949 }
1950
1951 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1952   SDValue N0 = N->getOperand(0);
1953   SDValue N1 = N->getOperand(1);
1954   SDValue CarryIn = N->getOperand(2);
1955
1956   // fold (sube x, y, false) -> (subc x, y)
1957   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1958     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1959
1960   return SDValue();
1961 }
1962
1963 SDValue DAGCombiner::visitMUL(SDNode *N) {
1964   SDValue N0 = N->getOperand(0);
1965   SDValue N1 = N->getOperand(1);
1966   EVT VT = N0.getValueType();
1967
1968   // fold (mul x, undef) -> 0
1969   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1970     return DAG.getConstant(0, VT);
1971
1972   bool N0IsConst = false;
1973   bool N1IsConst = false;
1974   APInt ConstValue0, ConstValue1;
1975   // fold vector ops
1976   if (VT.isVector()) {
1977     SDValue FoldedVOp = SimplifyVBinOp(N);
1978     if (FoldedVOp.getNode()) return FoldedVOp;
1979
1980     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1981     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1982   } else {
1983     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1984     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1985                             : APInt();
1986     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1987     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1988                             : APInt();
1989   }
1990
1991   // fold (mul c1, c2) -> c1*c2
1992   if (N0IsConst && N1IsConst)
1993     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1994
1995   // canonicalize constant to RHS
1996   if (N0IsConst && !N1IsConst)
1997     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1998   // fold (mul x, 0) -> 0
1999   if (N1IsConst && ConstValue1 == 0)
2000     return N1;
2001   // We require a splat of the entire scalar bit width for non-contiguous
2002   // bit patterns.
2003   bool IsFullSplat =
2004     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2005   // fold (mul x, 1) -> x
2006   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2007     return N0;
2008   // fold (mul x, -1) -> 0-x
2009   if (N1IsConst && ConstValue1.isAllOnesValue())
2010     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2011                        DAG.getConstant(0, VT), N0);
2012   // fold (mul x, (1 << c)) -> x << c
2013   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
2014     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2015                        DAG.getConstant(ConstValue1.logBase2(),
2016                                        getShiftAmountTy(N0.getValueType())));
2017   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2018   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
2019     unsigned Log2Val = (-ConstValue1).logBase2();
2020     // FIXME: If the input is something that is easily negated (e.g. a
2021     // single-use add), we should put the negate there.
2022     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2023                        DAG.getConstant(0, VT),
2024                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2025                             DAG.getConstant(Log2Val,
2026                                       getShiftAmountTy(N0.getValueType()))));
2027   }
2028
2029   APInt Val;
2030   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2031   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2032       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2033                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2034     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2035                              N1, N0.getOperand(1));
2036     AddToWorklist(C3.getNode());
2037     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2038                        N0.getOperand(0), C3);
2039   }
2040
2041   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2042   // use.
2043   {
2044     SDValue Sh(nullptr,0), Y(nullptr,0);
2045     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2046     if (N0.getOpcode() == ISD::SHL &&
2047         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2048                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2049         N0.getNode()->hasOneUse()) {
2050       Sh = N0; Y = N1;
2051     } else if (N1.getOpcode() == ISD::SHL &&
2052                isa<ConstantSDNode>(N1.getOperand(1)) &&
2053                N1.getNode()->hasOneUse()) {
2054       Sh = N1; Y = N0;
2055     }
2056
2057     if (Sh.getNode()) {
2058       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2059                                 Sh.getOperand(0), Y);
2060       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2061                          Mul, Sh.getOperand(1));
2062     }
2063   }
2064
2065   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2066   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2067       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2068                      isa<ConstantSDNode>(N0.getOperand(1))))
2069     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2070                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2071                                    N0.getOperand(0), N1),
2072                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2073                                    N0.getOperand(1), N1));
2074
2075   // reassociate mul
2076   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2077   if (RMUL.getNode())
2078     return RMUL;
2079
2080   return SDValue();
2081 }
2082
2083 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2084   SDValue N0 = N->getOperand(0);
2085   SDValue N1 = N->getOperand(1);
2086   EVT VT = N->getValueType(0);
2087
2088   // fold vector ops
2089   if (VT.isVector()) {
2090     SDValue FoldedVOp = SimplifyVBinOp(N);
2091     if (FoldedVOp.getNode()) return FoldedVOp;
2092   }
2093
2094   // fold (sdiv c1, c2) -> c1/c2
2095   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2096   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2097   if (N0C && N1C && !N1C->isNullValue())
2098     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2099   // fold (sdiv X, 1) -> X
2100   if (N1C && N1C->getAPIntValue() == 1LL)
2101     return N0;
2102   // fold (sdiv X, -1) -> 0-X
2103   if (N1C && N1C->isAllOnesValue())
2104     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2105                        DAG.getConstant(0, VT), N0);
2106   // If we know the sign bits of both operands are zero, strength reduce to a
2107   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2108   if (!VT.isVector()) {
2109     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2110       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2111                          N0, N1);
2112   }
2113
2114   // fold (sdiv X, pow2) -> simple ops after legalize
2115   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2116                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2117     // If dividing by powers of two is cheap, then don't perform the following
2118     // fold.
2119     if (TLI.isPow2SDivCheap())
2120       return SDValue();
2121
2122     // Target-specific implementation of sdiv x, pow2.
2123     SDValue Res = BuildSDIVPow2(N);
2124     if (Res.getNode())
2125       return Res;
2126
2127     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2128
2129     // Splat the sign bit into the register
2130     SDValue SGN =
2131         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2132                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2133                                     getShiftAmountTy(N0.getValueType())));
2134     AddToWorklist(SGN.getNode());
2135
2136     // Add (N0 < 0) ? abs2 - 1 : 0;
2137     SDValue SRL =
2138         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2139                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2140                                     getShiftAmountTy(SGN.getValueType())));
2141     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2142     AddToWorklist(SRL.getNode());
2143     AddToWorklist(ADD.getNode());    // Divide by pow2
2144     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2145                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2146
2147     // If we're dividing by a positive value, we're done.  Otherwise, we must
2148     // negate the result.
2149     if (N1C->getAPIntValue().isNonNegative())
2150       return SRA;
2151
2152     AddToWorklist(SRA.getNode());
2153     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2154   }
2155
2156   // if integer divide is expensive and we satisfy the requirements, emit an
2157   // alternate sequence.
2158   if (N1C && !TLI.isIntDivCheap()) {
2159     SDValue Op = BuildSDIV(N);
2160     if (Op.getNode()) return Op;
2161   }
2162
2163   // undef / X -> 0
2164   if (N0.getOpcode() == ISD::UNDEF)
2165     return DAG.getConstant(0, VT);
2166   // X / undef -> undef
2167   if (N1.getOpcode() == ISD::UNDEF)
2168     return N1;
2169
2170   return SDValue();
2171 }
2172
2173 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2174   SDValue N0 = N->getOperand(0);
2175   SDValue N1 = N->getOperand(1);
2176   EVT VT = N->getValueType(0);
2177
2178   // fold vector ops
2179   if (VT.isVector()) {
2180     SDValue FoldedVOp = SimplifyVBinOp(N);
2181     if (FoldedVOp.getNode()) return FoldedVOp;
2182   }
2183
2184   // fold (udiv c1, c2) -> c1/c2
2185   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2186   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2187   if (N0C && N1C && !N1C->isNullValue())
2188     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2189   // fold (udiv x, (1 << c)) -> x >>u c
2190   if (N1C && N1C->getAPIntValue().isPowerOf2())
2191     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2192                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2193                                        getShiftAmountTy(N0.getValueType())));
2194   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2195   if (N1.getOpcode() == ISD::SHL) {
2196     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2197       if (SHC->getAPIntValue().isPowerOf2()) {
2198         EVT ADDVT = N1.getOperand(1).getValueType();
2199         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2200                                   N1.getOperand(1),
2201                                   DAG.getConstant(SHC->getAPIntValue()
2202                                                                   .logBase2(),
2203                                                   ADDVT));
2204         AddToWorklist(Add.getNode());
2205         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2206       }
2207     }
2208   }
2209   // fold (udiv x, c) -> alternate
2210   if (N1C && !TLI.isIntDivCheap()) {
2211     SDValue Op = BuildUDIV(N);
2212     if (Op.getNode()) return Op;
2213   }
2214
2215   // undef / X -> 0
2216   if (N0.getOpcode() == ISD::UNDEF)
2217     return DAG.getConstant(0, VT);
2218   // X / undef -> undef
2219   if (N1.getOpcode() == ISD::UNDEF)
2220     return N1;
2221
2222   return SDValue();
2223 }
2224
2225 SDValue DAGCombiner::visitSREM(SDNode *N) {
2226   SDValue N0 = N->getOperand(0);
2227   SDValue N1 = N->getOperand(1);
2228   EVT VT = N->getValueType(0);
2229
2230   // fold (srem c1, c2) -> c1%c2
2231   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2232   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2233   if (N0C && N1C && !N1C->isNullValue())
2234     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2235   // If we know the sign bits of both operands are zero, strength reduce to a
2236   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2237   if (!VT.isVector()) {
2238     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2239       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2240   }
2241
2242   // If X/C can be simplified by the division-by-constant logic, lower
2243   // X%C to the equivalent of X-X/C*C.
2244   if (N1C && !N1C->isNullValue()) {
2245     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2246     AddToWorklist(Div.getNode());
2247     SDValue OptimizedDiv = combine(Div.getNode());
2248     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2249       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2250                                 OptimizedDiv, N1);
2251       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2252       AddToWorklist(Mul.getNode());
2253       return Sub;
2254     }
2255   }
2256
2257   // undef % X -> 0
2258   if (N0.getOpcode() == ISD::UNDEF)
2259     return DAG.getConstant(0, VT);
2260   // X % undef -> undef
2261   if (N1.getOpcode() == ISD::UNDEF)
2262     return N1;
2263
2264   return SDValue();
2265 }
2266
2267 SDValue DAGCombiner::visitUREM(SDNode *N) {
2268   SDValue N0 = N->getOperand(0);
2269   SDValue N1 = N->getOperand(1);
2270   EVT VT = N->getValueType(0);
2271
2272   // fold (urem c1, c2) -> c1%c2
2273   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2274   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2275   if (N0C && N1C && !N1C->isNullValue())
2276     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2277   // fold (urem x, pow2) -> (and x, pow2-1)
2278   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2279     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2280                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2281   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2282   if (N1.getOpcode() == ISD::SHL) {
2283     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2284       if (SHC->getAPIntValue().isPowerOf2()) {
2285         SDValue Add =
2286           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2287                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2288                                  VT));
2289         AddToWorklist(Add.getNode());
2290         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2291       }
2292     }
2293   }
2294
2295   // If X/C can be simplified by the division-by-constant logic, lower
2296   // X%C to the equivalent of X-X/C*C.
2297   if (N1C && !N1C->isNullValue()) {
2298     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2299     AddToWorklist(Div.getNode());
2300     SDValue OptimizedDiv = combine(Div.getNode());
2301     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2302       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2303                                 OptimizedDiv, N1);
2304       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2305       AddToWorklist(Mul.getNode());
2306       return Sub;
2307     }
2308   }
2309
2310   // undef % X -> 0
2311   if (N0.getOpcode() == ISD::UNDEF)
2312     return DAG.getConstant(0, VT);
2313   // X % undef -> undef
2314   if (N1.getOpcode() == ISD::UNDEF)
2315     return N1;
2316
2317   return SDValue();
2318 }
2319
2320 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2321   SDValue N0 = N->getOperand(0);
2322   SDValue N1 = N->getOperand(1);
2323   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2324   EVT VT = N->getValueType(0);
2325   SDLoc DL(N);
2326
2327   // fold (mulhs x, 0) -> 0
2328   if (N1C && N1C->isNullValue())
2329     return N1;
2330   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2331   if (N1C && N1C->getAPIntValue() == 1)
2332     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2333                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2334                                        getShiftAmountTy(N0.getValueType())));
2335   // fold (mulhs x, undef) -> 0
2336   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2337     return DAG.getConstant(0, VT);
2338
2339   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2340   // plus a shift.
2341   if (VT.isSimple() && !VT.isVector()) {
2342     MVT Simple = VT.getSimpleVT();
2343     unsigned SimpleSize = Simple.getSizeInBits();
2344     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2345     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2346       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2347       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2348       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2349       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2350             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2351       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2352     }
2353   }
2354
2355   return SDValue();
2356 }
2357
2358 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2359   SDValue N0 = N->getOperand(0);
2360   SDValue N1 = N->getOperand(1);
2361   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2362   EVT VT = N->getValueType(0);
2363   SDLoc DL(N);
2364
2365   // fold (mulhu x, 0) -> 0
2366   if (N1C && N1C->isNullValue())
2367     return N1;
2368   // fold (mulhu x, 1) -> 0
2369   if (N1C && N1C->getAPIntValue() == 1)
2370     return DAG.getConstant(0, N0.getValueType());
2371   // fold (mulhu x, undef) -> 0
2372   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2373     return DAG.getConstant(0, VT);
2374
2375   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2376   // plus a shift.
2377   if (VT.isSimple() && !VT.isVector()) {
2378     MVT Simple = VT.getSimpleVT();
2379     unsigned SimpleSize = Simple.getSizeInBits();
2380     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2381     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2382       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2383       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2384       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2385       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2386             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2387       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2388     }
2389   }
2390
2391   return SDValue();
2392 }
2393
2394 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2395 /// give the opcodes for the two computations that are being performed. Return
2396 /// true if a simplification was made.
2397 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2398                                                 unsigned HiOp) {
2399   // If the high half is not needed, just compute the low half.
2400   bool HiExists = N->hasAnyUseOfValue(1);
2401   if (!HiExists &&
2402       (!LegalOperations ||
2403        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2404     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2405     return CombineTo(N, Res, Res);
2406   }
2407
2408   // If the low half is not needed, just compute the high half.
2409   bool LoExists = N->hasAnyUseOfValue(0);
2410   if (!LoExists &&
2411       (!LegalOperations ||
2412        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2413     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2414     return CombineTo(N, Res, Res);
2415   }
2416
2417   // If both halves are used, return as it is.
2418   if (LoExists && HiExists)
2419     return SDValue();
2420
2421   // If the two computed results can be simplified separately, separate them.
2422   if (LoExists) {
2423     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2424     AddToWorklist(Lo.getNode());
2425     SDValue LoOpt = combine(Lo.getNode());
2426     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2427         (!LegalOperations ||
2428          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2429       return CombineTo(N, LoOpt, LoOpt);
2430   }
2431
2432   if (HiExists) {
2433     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2434     AddToWorklist(Hi.getNode());
2435     SDValue HiOpt = combine(Hi.getNode());
2436     if (HiOpt.getNode() && HiOpt != Hi &&
2437         (!LegalOperations ||
2438          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2439       return CombineTo(N, HiOpt, HiOpt);
2440   }
2441
2442   return SDValue();
2443 }
2444
2445 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2446   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2447   if (Res.getNode()) return Res;
2448
2449   EVT VT = N->getValueType(0);
2450   SDLoc DL(N);
2451
2452   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2453   // plus a shift.
2454   if (VT.isSimple() && !VT.isVector()) {
2455     MVT Simple = VT.getSimpleVT();
2456     unsigned SimpleSize = Simple.getSizeInBits();
2457     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2458     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2459       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2460       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2461       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2462       // Compute the high part as N1.
2463       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2464             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2465       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2466       // Compute the low part as N0.
2467       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2468       return CombineTo(N, Lo, Hi);
2469     }
2470   }
2471
2472   return SDValue();
2473 }
2474
2475 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2476   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2477   if (Res.getNode()) return Res;
2478
2479   EVT VT = N->getValueType(0);
2480   SDLoc DL(N);
2481
2482   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2483   // plus a shift.
2484   if (VT.isSimple() && !VT.isVector()) {
2485     MVT Simple = VT.getSimpleVT();
2486     unsigned SimpleSize = Simple.getSizeInBits();
2487     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2488     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2489       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2490       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2491       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2492       // Compute the high part as N1.
2493       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2494             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2495       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2496       // Compute the low part as N0.
2497       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2498       return CombineTo(N, Lo, Hi);
2499     }
2500   }
2501
2502   return SDValue();
2503 }
2504
2505 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2506   // (smulo x, 2) -> (saddo x, x)
2507   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2508     if (C2->getAPIntValue() == 2)
2509       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2510                          N->getOperand(0), N->getOperand(0));
2511
2512   return SDValue();
2513 }
2514
2515 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2516   // (umulo x, 2) -> (uaddo x, x)
2517   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2518     if (C2->getAPIntValue() == 2)
2519       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2520                          N->getOperand(0), N->getOperand(0));
2521
2522   return SDValue();
2523 }
2524
2525 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2526   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2527   if (Res.getNode()) return Res;
2528
2529   return SDValue();
2530 }
2531
2532 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2533   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2534   if (Res.getNode()) return Res;
2535
2536   return SDValue();
2537 }
2538
2539 /// If this is a binary operator with two operands of the same opcode, try to
2540 /// simplify it.
2541 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2542   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2543   EVT VT = N0.getValueType();
2544   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2545
2546   // Bail early if none of these transforms apply.
2547   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2548
2549   // For each of OP in AND/OR/XOR:
2550   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2551   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2552   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2553   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2554   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2555   //
2556   // do not sink logical op inside of a vector extend, since it may combine
2557   // into a vsetcc.
2558   EVT Op0VT = N0.getOperand(0).getValueType();
2559   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2560        N0.getOpcode() == ISD::SIGN_EXTEND ||
2561        N0.getOpcode() == ISD::BSWAP ||
2562        // Avoid infinite looping with PromoteIntBinOp.
2563        (N0.getOpcode() == ISD::ANY_EXTEND &&
2564         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2565        (N0.getOpcode() == ISD::TRUNCATE &&
2566         (!TLI.isZExtFree(VT, Op0VT) ||
2567          !TLI.isTruncateFree(Op0VT, VT)) &&
2568         TLI.isTypeLegal(Op0VT))) &&
2569       !VT.isVector() &&
2570       Op0VT == N1.getOperand(0).getValueType() &&
2571       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2572     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2573                                  N0.getOperand(0).getValueType(),
2574                                  N0.getOperand(0), N1.getOperand(0));
2575     AddToWorklist(ORNode.getNode());
2576     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2577   }
2578
2579   // For each of OP in SHL/SRL/SRA/AND...
2580   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2581   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2582   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2583   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2584        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2585       N0.getOperand(1) == N1.getOperand(1)) {
2586     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2587                                  N0.getOperand(0).getValueType(),
2588                                  N0.getOperand(0), N1.getOperand(0));
2589     AddToWorklist(ORNode.getNode());
2590     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2591                        ORNode, N0.getOperand(1));
2592   }
2593
2594   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2595   // Only perform this optimization after type legalization and before
2596   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2597   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2598   // we don't want to undo this promotion.
2599   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2600   // on scalars.
2601   if ((N0.getOpcode() == ISD::BITCAST ||
2602        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2603       Level == AfterLegalizeTypes) {
2604     SDValue In0 = N0.getOperand(0);
2605     SDValue In1 = N1.getOperand(0);
2606     EVT In0Ty = In0.getValueType();
2607     EVT In1Ty = In1.getValueType();
2608     SDLoc DL(N);
2609     // If both incoming values are integers, and the original types are the
2610     // same.
2611     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2612       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2613       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2614       AddToWorklist(Op.getNode());
2615       return BC;
2616     }
2617   }
2618
2619   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2620   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2621   // If both shuffles use the same mask, and both shuffle within a single
2622   // vector, then it is worthwhile to move the swizzle after the operation.
2623   // The type-legalizer generates this pattern when loading illegal
2624   // vector types from memory. In many cases this allows additional shuffle
2625   // optimizations.
2626   // There are other cases where moving the shuffle after the xor/and/or
2627   // is profitable even if shuffles don't perform a swizzle.
2628   // If both shuffles use the same mask, and both shuffles have the same first
2629   // or second operand, then it might still be profitable to move the shuffle
2630   // after the xor/and/or operation.
2631   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2632     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2633     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2634
2635     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2636            "Inputs to shuffles are not the same type");
2637
2638     // Check that both shuffles use the same mask. The masks are known to be of
2639     // the same length because the result vector type is the same.
2640     // Check also that shuffles have only one use to avoid introducing extra
2641     // instructions.
2642     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2643         SVN0->getMask().equals(SVN1->getMask())) {
2644       SDValue ShOp = N0->getOperand(1);
2645
2646       // Don't try to fold this node if it requires introducing a
2647       // build vector of all zeros that might be illegal at this stage.
2648       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2649         if (!LegalTypes)
2650           ShOp = DAG.getConstant(0, VT);
2651         else
2652           ShOp = SDValue();
2653       }
2654
2655       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2656       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2657       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2658       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2659         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2660                                       N0->getOperand(0), N1->getOperand(0));
2661         AddToWorklist(NewNode.getNode());
2662         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2663                                     &SVN0->getMask()[0]);
2664       }
2665
2666       // Don't try to fold this node if it requires introducing a
2667       // build vector of all zeros that might be illegal at this stage.
2668       ShOp = N0->getOperand(0);
2669       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2670         if (!LegalTypes)
2671           ShOp = DAG.getConstant(0, VT);
2672         else
2673           ShOp = SDValue();
2674       }
2675
2676       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2677       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2678       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2679       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2680         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2681                                       N0->getOperand(1), N1->getOperand(1));
2682         AddToWorklist(NewNode.getNode());
2683         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2684                                     &SVN0->getMask()[0]);
2685       }
2686     }
2687   }
2688
2689   return SDValue();
2690 }
2691
2692 /// This contains all DAGCombine rules which reduce two values combined by
2693 /// an And operation to a single value. This makes them reusable in the context
2694 /// of visitSELECT(). Rules involving constants are not included as
2695 /// visitSELECT() already handles those cases.
2696 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2697                                   SDNode *LocReference) {
2698   EVT VT = N1.getValueType();
2699
2700   // fold (and x, undef) -> 0
2701   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2702     return DAG.getConstant(0, VT);
2703   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2704   SDValue LL, LR, RL, RR, CC0, CC1;
2705   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2706     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2707     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2708
2709     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2710         LL.getValueType().isInteger()) {
2711       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2712       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2713         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2714                                      LR.getValueType(), LL, RL);
2715         AddToWorklist(ORNode.getNode());
2716         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2717       }
2718       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2719       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2720         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2721                                       LR.getValueType(), LL, RL);
2722         AddToWorklist(ANDNode.getNode());
2723         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2724       }
2725       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2726       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2727         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2728                                      LR.getValueType(), LL, RL);
2729         AddToWorklist(ORNode.getNode());
2730         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2731       }
2732     }
2733     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2734     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2735         Op0 == Op1 && LL.getValueType().isInteger() &&
2736       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2737                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2738                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2739                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2740       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2741                                     LL, DAG.getConstant(1, LL.getValueType()));
2742       AddToWorklist(ADDNode.getNode());
2743       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2744                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2745     }
2746     // canonicalize equivalent to ll == rl
2747     if (LL == RR && LR == RL) {
2748       Op1 = ISD::getSetCCSwappedOperands(Op1);
2749       std::swap(RL, RR);
2750     }
2751     if (LL == RL && LR == RR) {
2752       bool isInteger = LL.getValueType().isInteger();
2753       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2754       if (Result != ISD::SETCC_INVALID &&
2755           (!LegalOperations ||
2756            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2757             TLI.isOperationLegal(ISD::SETCC,
2758                             getSetCCResultType(N0.getSimpleValueType())))))
2759         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2760                             LL, LR, Result);
2761     }
2762   }
2763
2764   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2765       VT.getSizeInBits() <= 64) {
2766     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2767       APInt ADDC = ADDI->getAPIntValue();
2768       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2769         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2770         // immediate for an add, but it is legal if its top c2 bits are set,
2771         // transform the ADD so the immediate doesn't need to be materialized
2772         // in a register.
2773         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2774           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2775                                              SRLI->getZExtValue());
2776           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2777             ADDC |= Mask;
2778             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2779               SDValue NewAdd =
2780                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2781                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2782               CombineTo(N0.getNode(), NewAdd);
2783               // Return N so it doesn't get rechecked!
2784               return SDValue(LocReference, 0);
2785             }
2786           }
2787         }
2788       }
2789     }
2790   }
2791
2792   return SDValue();
2793 }
2794
2795 SDValue DAGCombiner::visitAND(SDNode *N) {
2796   SDValue N0 = N->getOperand(0);
2797   SDValue N1 = N->getOperand(1);
2798   EVT VT = N1.getValueType();
2799
2800   // fold vector ops
2801   if (VT.isVector()) {
2802     SDValue FoldedVOp = SimplifyVBinOp(N);
2803     if (FoldedVOp.getNode()) return FoldedVOp;
2804
2805     // fold (and x, 0) -> 0, vector edition
2806     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2807       // do not return N0, because undef node may exist in N0
2808       return DAG.getConstant(
2809           APInt::getNullValue(
2810               N0.getValueType().getScalarType().getSizeInBits()),
2811           N0.getValueType());
2812     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2813       // do not return N1, because undef node may exist in N1
2814       return DAG.getConstant(
2815           APInt::getNullValue(
2816               N1.getValueType().getScalarType().getSizeInBits()),
2817           N1.getValueType());
2818
2819     // fold (and x, -1) -> x, vector edition
2820     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2821       return N1;
2822     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2823       return N0;
2824   }
2825
2826   // fold (and c1, c2) -> c1&c2
2827   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2828   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2829   if (N0C && N1C)
2830     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2831   // canonicalize constant to RHS
2832   if (N0C && !N1C)
2833     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2834   // fold (and x, -1) -> x
2835   if (N1C && N1C->isAllOnesValue())
2836     return N0;
2837   // if (and x, c) is known to be zero, return 0
2838   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2839   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2840                                    APInt::getAllOnesValue(BitWidth)))
2841     return DAG.getConstant(0, VT);
2842   // reassociate and
2843   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2844   if (RAND.getNode())
2845     return RAND;
2846   // fold (and (or x, C), D) -> D if (C & D) == D
2847   if (N1C && N0.getOpcode() == ISD::OR)
2848     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2849       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2850         return N1;
2851   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2852   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2853     SDValue N0Op0 = N0.getOperand(0);
2854     APInt Mask = ~N1C->getAPIntValue();
2855     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2856     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2857       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2858                                  N0.getValueType(), N0Op0);
2859
2860       // Replace uses of the AND with uses of the Zero extend node.
2861       CombineTo(N, Zext);
2862
2863       // We actually want to replace all uses of the any_extend with the
2864       // zero_extend, to avoid duplicating things.  This will later cause this
2865       // AND to be folded.
2866       CombineTo(N0.getNode(), Zext);
2867       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2868     }
2869   }
2870   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2871   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2872   // already be zero by virtue of the width of the base type of the load.
2873   //
2874   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2875   // more cases.
2876   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2877        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2878       N0.getOpcode() == ISD::LOAD) {
2879     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2880                                          N0 : N0.getOperand(0) );
2881
2882     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2883     // This can be a pure constant or a vector splat, in which case we treat the
2884     // vector as a scalar and use the splat value.
2885     APInt Constant = APInt::getNullValue(1);
2886     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2887       Constant = C->getAPIntValue();
2888     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2889       APInt SplatValue, SplatUndef;
2890       unsigned SplatBitSize;
2891       bool HasAnyUndefs;
2892       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2893                                              SplatBitSize, HasAnyUndefs);
2894       if (IsSplat) {
2895         // Undef bits can contribute to a possible optimisation if set, so
2896         // set them.
2897         SplatValue |= SplatUndef;
2898
2899         // The splat value may be something like "0x00FFFFFF", which means 0 for
2900         // the first vector value and FF for the rest, repeating. We need a mask
2901         // that will apply equally to all members of the vector, so AND all the
2902         // lanes of the constant together.
2903         EVT VT = Vector->getValueType(0);
2904         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2905
2906         // If the splat value has been compressed to a bitlength lower
2907         // than the size of the vector lane, we need to re-expand it to
2908         // the lane size.
2909         if (BitWidth > SplatBitSize)
2910           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2911                SplatBitSize < BitWidth;
2912                SplatBitSize = SplatBitSize * 2)
2913             SplatValue |= SplatValue.shl(SplatBitSize);
2914
2915         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2916         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2917         if (SplatBitSize % BitWidth == 0) {
2918           Constant = APInt::getAllOnesValue(BitWidth);
2919           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2920             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2921         }
2922       }
2923     }
2924
2925     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2926     // actually legal and isn't going to get expanded, else this is a false
2927     // optimisation.
2928     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2929                                                     Load->getValueType(0),
2930                                                     Load->getMemoryVT());
2931
2932     // Resize the constant to the same size as the original memory access before
2933     // extension. If it is still the AllOnesValue then this AND is completely
2934     // unneeded.
2935     Constant =
2936       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2937
2938     bool B;
2939     switch (Load->getExtensionType()) {
2940     default: B = false; break;
2941     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2942     case ISD::ZEXTLOAD:
2943     case ISD::NON_EXTLOAD: B = true; break;
2944     }
2945
2946     if (B && Constant.isAllOnesValue()) {
2947       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2948       // preserve semantics once we get rid of the AND.
2949       SDValue NewLoad(Load, 0);
2950       if (Load->getExtensionType() == ISD::EXTLOAD) {
2951         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2952                               Load->getValueType(0), SDLoc(Load),
2953                               Load->getChain(), Load->getBasePtr(),
2954                               Load->getOffset(), Load->getMemoryVT(),
2955                               Load->getMemOperand());
2956         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2957         if (Load->getNumValues() == 3) {
2958           // PRE/POST_INC loads have 3 values.
2959           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2960                            NewLoad.getValue(2) };
2961           CombineTo(Load, To, 3, true);
2962         } else {
2963           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2964         }
2965       }
2966
2967       // Fold the AND away, taking care not to fold to the old load node if we
2968       // replaced it.
2969       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2970
2971       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2972     }
2973   }
2974
2975   // fold (and (load x), 255) -> (zextload x, i8)
2976   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2977   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2978   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2979               (N0.getOpcode() == ISD::ANY_EXTEND &&
2980                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2981     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2982     LoadSDNode *LN0 = HasAnyExt
2983       ? cast<LoadSDNode>(N0.getOperand(0))
2984       : cast<LoadSDNode>(N0);
2985     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2986         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2987       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2988       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2989         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2990         EVT LoadedVT = LN0->getMemoryVT();
2991         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2992
2993         if (ExtVT == LoadedVT &&
2994             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
2995                                                     ExtVT))) {
2996
2997           SDValue NewLoad =
2998             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2999                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3000                            LN0->getMemOperand());
3001           AddToWorklist(N);
3002           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3003           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3004         }
3005
3006         // Do not change the width of a volatile load.
3007         // Do not generate loads of non-round integer types since these can
3008         // be expensive (and would be wrong if the type is not byte sized).
3009         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3010             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3011                                                     ExtVT))) {
3012           EVT PtrType = LN0->getOperand(1).getValueType();
3013
3014           unsigned Alignment = LN0->getAlignment();
3015           SDValue NewPtr = LN0->getBasePtr();
3016
3017           // For big endian targets, we need to add an offset to the pointer
3018           // to load the correct bytes.  For little endian systems, we merely
3019           // need to read fewer bytes from the same pointer.
3020           if (TLI.isBigEndian()) {
3021             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3022             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3023             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3024             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
3025                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
3026             Alignment = MinAlign(Alignment, PtrOff);
3027           }
3028
3029           AddToWorklist(NewPtr.getNode());
3030
3031           SDValue Load =
3032             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3033                            LN0->getChain(), NewPtr,
3034                            LN0->getPointerInfo(),
3035                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3036                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3037           AddToWorklist(N);
3038           CombineTo(LN0, Load, Load.getValue(1));
3039           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3040         }
3041       }
3042     }
3043   }
3044
3045   if (SDValue Combined = visitANDLike(N0, N1, N))
3046     return Combined;
3047
3048   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3049   if (N0.getOpcode() == N1.getOpcode()) {
3050     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3051     if (Tmp.getNode()) return Tmp;
3052   }
3053
3054   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3055   // fold (and (sra)) -> (and (srl)) when possible.
3056   if (!VT.isVector() &&
3057       SimplifyDemandedBits(SDValue(N, 0)))
3058     return SDValue(N, 0);
3059
3060   // fold (zext_inreg (extload x)) -> (zextload x)
3061   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3062     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3063     EVT MemVT = LN0->getMemoryVT();
3064     // If we zero all the possible extended bits, then we can turn this into
3065     // a zextload if we are running before legalize or the operation is legal.
3066     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3067     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3068                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3069         ((!LegalOperations && !LN0->isVolatile()) ||
3070          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3071       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3072                                        LN0->getChain(), LN0->getBasePtr(),
3073                                        MemVT, LN0->getMemOperand());
3074       AddToWorklist(N);
3075       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3076       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3077     }
3078   }
3079   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3080   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3081       N0.hasOneUse()) {
3082     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3083     EVT MemVT = LN0->getMemoryVT();
3084     // If we zero all the possible extended bits, then we can turn this into
3085     // a zextload if we are running before legalize or the operation is legal.
3086     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3087     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3088                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3089         ((!LegalOperations && !LN0->isVolatile()) ||
3090          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3091       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3092                                        LN0->getChain(), LN0->getBasePtr(),
3093                                        MemVT, LN0->getMemOperand());
3094       AddToWorklist(N);
3095       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3096       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3097     }
3098   }
3099   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3100   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3101     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3102                                        N0.getOperand(1), false);
3103     if (BSwap.getNode())
3104       return BSwap;
3105   }
3106
3107   return SDValue();
3108 }
3109
3110 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3111 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3112                                         bool DemandHighBits) {
3113   if (!LegalOperations)
3114     return SDValue();
3115
3116   EVT VT = N->getValueType(0);
3117   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3118     return SDValue();
3119   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3120     return SDValue();
3121
3122   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3123   bool LookPassAnd0 = false;
3124   bool LookPassAnd1 = false;
3125   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3126       std::swap(N0, N1);
3127   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3128       std::swap(N0, N1);
3129   if (N0.getOpcode() == ISD::AND) {
3130     if (!N0.getNode()->hasOneUse())
3131       return SDValue();
3132     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3133     if (!N01C || N01C->getZExtValue() != 0xFF00)
3134       return SDValue();
3135     N0 = N0.getOperand(0);
3136     LookPassAnd0 = true;
3137   }
3138
3139   if (N1.getOpcode() == ISD::AND) {
3140     if (!N1.getNode()->hasOneUse())
3141       return SDValue();
3142     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3143     if (!N11C || N11C->getZExtValue() != 0xFF)
3144       return SDValue();
3145     N1 = N1.getOperand(0);
3146     LookPassAnd1 = true;
3147   }
3148
3149   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3150     std::swap(N0, N1);
3151   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3152     return SDValue();
3153   if (!N0.getNode()->hasOneUse() ||
3154       !N1.getNode()->hasOneUse())
3155     return SDValue();
3156
3157   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3158   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3159   if (!N01C || !N11C)
3160     return SDValue();
3161   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3162     return SDValue();
3163
3164   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3165   SDValue N00 = N0->getOperand(0);
3166   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3167     if (!N00.getNode()->hasOneUse())
3168       return SDValue();
3169     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3170     if (!N001C || N001C->getZExtValue() != 0xFF)
3171       return SDValue();
3172     N00 = N00.getOperand(0);
3173     LookPassAnd0 = true;
3174   }
3175
3176   SDValue N10 = N1->getOperand(0);
3177   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3178     if (!N10.getNode()->hasOneUse())
3179       return SDValue();
3180     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3181     if (!N101C || N101C->getZExtValue() != 0xFF00)
3182       return SDValue();
3183     N10 = N10.getOperand(0);
3184     LookPassAnd1 = true;
3185   }
3186
3187   if (N00 != N10)
3188     return SDValue();
3189
3190   // Make sure everything beyond the low halfword gets set to zero since the SRL
3191   // 16 will clear the top bits.
3192   unsigned OpSizeInBits = VT.getSizeInBits();
3193   if (DemandHighBits && OpSizeInBits > 16) {
3194     // If the left-shift isn't masked out then the only way this is a bswap is
3195     // if all bits beyond the low 8 are 0. In that case the entire pattern
3196     // reduces to a left shift anyway: leave it for other parts of the combiner.
3197     if (!LookPassAnd0)
3198       return SDValue();
3199
3200     // However, if the right shift isn't masked out then it might be because
3201     // it's not needed. See if we can spot that too.
3202     if (!LookPassAnd1 &&
3203         !DAG.MaskedValueIsZero(
3204             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3205       return SDValue();
3206   }
3207
3208   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3209   if (OpSizeInBits > 16)
3210     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3211                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3212   return Res;
3213 }
3214
3215 /// Return true if the specified node is an element that makes up a 32-bit
3216 /// packed halfword byteswap.
3217 /// ((x & 0x000000ff) << 8) |
3218 /// ((x & 0x0000ff00) >> 8) |
3219 /// ((x & 0x00ff0000) << 8) |
3220 /// ((x & 0xff000000) >> 8)
3221 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3222   if (!N.getNode()->hasOneUse())
3223     return false;
3224
3225   unsigned Opc = N.getOpcode();
3226   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3227     return false;
3228
3229   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3230   if (!N1C)
3231     return false;
3232
3233   unsigned Num;
3234   switch (N1C->getZExtValue()) {
3235   default:
3236     return false;
3237   case 0xFF:       Num = 0; break;
3238   case 0xFF00:     Num = 1; break;
3239   case 0xFF0000:   Num = 2; break;
3240   case 0xFF000000: Num = 3; break;
3241   }
3242
3243   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3244   SDValue N0 = N.getOperand(0);
3245   if (Opc == ISD::AND) {
3246     if (Num == 0 || Num == 2) {
3247       // (x >> 8) & 0xff
3248       // (x >> 8) & 0xff0000
3249       if (N0.getOpcode() != ISD::SRL)
3250         return false;
3251       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3252       if (!C || C->getZExtValue() != 8)
3253         return false;
3254     } else {
3255       // (x << 8) & 0xff00
3256       // (x << 8) & 0xff000000
3257       if (N0.getOpcode() != ISD::SHL)
3258         return false;
3259       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3260       if (!C || C->getZExtValue() != 8)
3261         return false;
3262     }
3263   } else if (Opc == ISD::SHL) {
3264     // (x & 0xff) << 8
3265     // (x & 0xff0000) << 8
3266     if (Num != 0 && Num != 2)
3267       return false;
3268     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3269     if (!C || C->getZExtValue() != 8)
3270       return false;
3271   } else { // Opc == ISD::SRL
3272     // (x & 0xff00) >> 8
3273     // (x & 0xff000000) >> 8
3274     if (Num != 1 && Num != 3)
3275       return false;
3276     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3277     if (!C || C->getZExtValue() != 8)
3278       return false;
3279   }
3280
3281   if (Parts[Num])
3282     return false;
3283
3284   Parts[Num] = N0.getOperand(0).getNode();
3285   return true;
3286 }
3287
3288 /// Match a 32-bit packed halfword bswap. That is
3289 /// ((x & 0x000000ff) << 8) |
3290 /// ((x & 0x0000ff00) >> 8) |
3291 /// ((x & 0x00ff0000) << 8) |
3292 /// ((x & 0xff000000) >> 8)
3293 /// => (rotl (bswap x), 16)
3294 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3295   if (!LegalOperations)
3296     return SDValue();
3297
3298   EVT VT = N->getValueType(0);
3299   if (VT != MVT::i32)
3300     return SDValue();
3301   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3302     return SDValue();
3303
3304   // Look for either
3305   // (or (or (and), (and)), (or (and), (and)))
3306   // (or (or (or (and), (and)), (and)), (and))
3307   if (N0.getOpcode() != ISD::OR)
3308     return SDValue();
3309   SDValue N00 = N0.getOperand(0);
3310   SDValue N01 = N0.getOperand(1);
3311   SDNode *Parts[4] = {};
3312
3313   if (N1.getOpcode() == ISD::OR &&
3314       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3315     // (or (or (and), (and)), (or (and), (and)))
3316     SDValue N000 = N00.getOperand(0);
3317     if (!isBSwapHWordElement(N000, Parts))
3318       return SDValue();
3319
3320     SDValue N001 = N00.getOperand(1);
3321     if (!isBSwapHWordElement(N001, Parts))
3322       return SDValue();
3323     SDValue N010 = N01.getOperand(0);
3324     if (!isBSwapHWordElement(N010, Parts))
3325       return SDValue();
3326     SDValue N011 = N01.getOperand(1);
3327     if (!isBSwapHWordElement(N011, Parts))
3328       return SDValue();
3329   } else {
3330     // (or (or (or (and), (and)), (and)), (and))
3331     if (!isBSwapHWordElement(N1, Parts))
3332       return SDValue();
3333     if (!isBSwapHWordElement(N01, Parts))
3334       return SDValue();
3335     if (N00.getOpcode() != ISD::OR)
3336       return SDValue();
3337     SDValue N000 = N00.getOperand(0);
3338     if (!isBSwapHWordElement(N000, Parts))
3339       return SDValue();
3340     SDValue N001 = N00.getOperand(1);
3341     if (!isBSwapHWordElement(N001, Parts))
3342       return SDValue();
3343   }
3344
3345   // Make sure the parts are all coming from the same node.
3346   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3347     return SDValue();
3348
3349   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3350                               SDValue(Parts[0],0));
3351
3352   // Result of the bswap should be rotated by 16. If it's not legal, then
3353   // do  (x << 16) | (x >> 16).
3354   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3355   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3356     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3357   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3358     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3359   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3360                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3361                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3362 }
3363
3364 /// This contains all DAGCombine rules which reduce two values combined by
3365 /// an Or operation to a single value \see visitANDLike().
3366 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3367   EVT VT = N1.getValueType();
3368   // fold (or x, undef) -> -1
3369   if (!LegalOperations &&
3370       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3371     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3372     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3373   }
3374   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3375   SDValue LL, LR, RL, RR, CC0, CC1;
3376   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3377     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3378     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3379
3380     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3381         LL.getValueType().isInteger()) {
3382       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3383       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3384       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3385           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3386         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3387                                      LR.getValueType(), LL, RL);
3388         AddToWorklist(ORNode.getNode());
3389         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3390       }
3391       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3392       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3393       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3394           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3395         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3396                                       LR.getValueType(), LL, RL);
3397         AddToWorklist(ANDNode.getNode());
3398         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3399       }
3400     }
3401     // canonicalize equivalent to ll == rl
3402     if (LL == RR && LR == RL) {
3403       Op1 = ISD::getSetCCSwappedOperands(Op1);
3404       std::swap(RL, RR);
3405     }
3406     if (LL == RL && LR == RR) {
3407       bool isInteger = LL.getValueType().isInteger();
3408       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3409       if (Result != ISD::SETCC_INVALID &&
3410           (!LegalOperations ||
3411            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3412             TLI.isOperationLegal(ISD::SETCC,
3413               getSetCCResultType(N0.getValueType())))))
3414         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3415                             LL, LR, Result);
3416     }
3417   }
3418
3419   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3420   if (N0.getOpcode() == ISD::AND &&
3421       N1.getOpcode() == ISD::AND &&
3422       N0.getOperand(1).getOpcode() == ISD::Constant &&
3423       N1.getOperand(1).getOpcode() == ISD::Constant &&
3424       // Don't increase # computations.
3425       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3426     // We can only do this xform if we know that bits from X that are set in C2
3427     // but not in C1 are already zero.  Likewise for Y.
3428     const APInt &LHSMask =
3429       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3430     const APInt &RHSMask =
3431       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3432
3433     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3434         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3435       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3436                               N0.getOperand(0), N1.getOperand(0));
3437       return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, X,
3438                          DAG.getConstant(LHSMask | RHSMask, VT));
3439     }
3440   }
3441
3442   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3443   if (N0.getOpcode() == ISD::AND &&
3444       N1.getOpcode() == ISD::AND &&
3445       N0.getOperand(0) == N1.getOperand(0) &&
3446       // Don't increase # computations.
3447       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3448     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3449                             N0.getOperand(1), N1.getOperand(1));
3450     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3451   }
3452
3453   return SDValue();
3454 }
3455
3456 SDValue DAGCombiner::visitOR(SDNode *N) {
3457   SDValue N0 = N->getOperand(0);
3458   SDValue N1 = N->getOperand(1);
3459   EVT VT = N1.getValueType();
3460
3461   // fold vector ops
3462   if (VT.isVector()) {
3463     SDValue FoldedVOp = SimplifyVBinOp(N);
3464     if (FoldedVOp.getNode()) return FoldedVOp;
3465
3466     // fold (or x, 0) -> x, vector edition
3467     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3468       return N1;
3469     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3470       return N0;
3471
3472     // fold (or x, -1) -> -1, vector edition
3473     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3474       // do not return N0, because undef node may exist in N0
3475       return DAG.getConstant(
3476           APInt::getAllOnesValue(
3477               N0.getValueType().getScalarType().getSizeInBits()),
3478           N0.getValueType());
3479     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3480       // do not return N1, because undef node may exist in N1
3481       return DAG.getConstant(
3482           APInt::getAllOnesValue(
3483               N1.getValueType().getScalarType().getSizeInBits()),
3484           N1.getValueType());
3485
3486     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3487     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3488     // Do this only if the resulting shuffle is legal.
3489     if (isa<ShuffleVectorSDNode>(N0) &&
3490         isa<ShuffleVectorSDNode>(N1) &&
3491         // Avoid folding a node with illegal type.
3492         TLI.isTypeLegal(VT) &&
3493         N0->getOperand(1) == N1->getOperand(1) &&
3494         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3495       bool CanFold = true;
3496       unsigned NumElts = VT.getVectorNumElements();
3497       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3498       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3499       // We construct two shuffle masks:
3500       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3501       // and N1 as the second operand.
3502       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3503       // and N0 as the second operand.
3504       // We do this because OR is commutable and therefore there might be
3505       // two ways to fold this node into a shuffle.
3506       SmallVector<int,4> Mask1;
3507       SmallVector<int,4> Mask2;
3508
3509       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3510         int M0 = SV0->getMaskElt(i);
3511         int M1 = SV1->getMaskElt(i);
3512
3513         // Both shuffle indexes are undef. Propagate Undef.
3514         if (M0 < 0 && M1 < 0) {
3515           Mask1.push_back(M0);
3516           Mask2.push_back(M0);
3517           continue;
3518         }
3519
3520         if (M0 < 0 || M1 < 0 ||
3521             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3522             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3523           CanFold = false;
3524           break;
3525         }
3526
3527         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3528         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3529       }
3530
3531       if (CanFold) {
3532         // Fold this sequence only if the resulting shuffle is 'legal'.
3533         if (TLI.isShuffleMaskLegal(Mask1, VT))
3534           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3535                                       N1->getOperand(0), &Mask1[0]);
3536         if (TLI.isShuffleMaskLegal(Mask2, VT))
3537           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3538                                       N0->getOperand(0), &Mask2[0]);
3539       }
3540     }
3541   }
3542
3543   // fold (or c1, c2) -> c1|c2
3544   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3545   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3546   if (N0C && N1C)
3547     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3548   // canonicalize constant to RHS
3549   if (N0C && !N1C)
3550     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3551   // fold (or x, 0) -> x
3552   if (N1C && N1C->isNullValue())
3553     return N0;
3554   // fold (or x, -1) -> -1
3555   if (N1C && N1C->isAllOnesValue())
3556     return N1;
3557   // fold (or x, c) -> c iff (x & ~c) == 0
3558   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3559     return N1;
3560
3561   if (SDValue Combined = visitORLike(N0, N1, N))
3562     return Combined;
3563
3564   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3565   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3566   if (BSwap.getNode())
3567     return BSwap;
3568   BSwap = MatchBSwapHWordLow(N, N0, N1);
3569   if (BSwap.getNode())
3570     return BSwap;
3571
3572   // reassociate or
3573   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3574   if (ROR.getNode())
3575     return ROR;
3576   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3577   // iff (c1 & c2) == 0.
3578   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3579              isa<ConstantSDNode>(N0.getOperand(1))) {
3580     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3581     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3582       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1))
3583         return DAG.getNode(
3584             ISD::AND, SDLoc(N), VT,
3585             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3586       return SDValue();
3587     }
3588   }
3589   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3590   if (N0.getOpcode() == N1.getOpcode()) {
3591     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3592     if (Tmp.getNode()) return Tmp;
3593   }
3594
3595   // See if this is some rotate idiom.
3596   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3597     return SDValue(Rot, 0);
3598
3599   // Simplify the operands using demanded-bits information.
3600   if (!VT.isVector() &&
3601       SimplifyDemandedBits(SDValue(N, 0)))
3602     return SDValue(N, 0);
3603
3604   return SDValue();
3605 }
3606
3607 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3608 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3609   if (Op.getOpcode() == ISD::AND) {
3610     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3611       Mask = Op.getOperand(1);
3612       Op = Op.getOperand(0);
3613     } else {
3614       return false;
3615     }
3616   }
3617
3618   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3619     Shift = Op;
3620     return true;
3621   }
3622
3623   return false;
3624 }
3625
3626 // Return true if we can prove that, whenever Neg and Pos are both in the
3627 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3628 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3629 //
3630 //     (or (shift1 X, Neg), (shift2 X, Pos))
3631 //
3632 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3633 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3634 // to consider shift amounts with defined behavior.
3635 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3636   // If OpSize is a power of 2 then:
3637   //
3638   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3639   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3640   //
3641   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3642   // for the stronger condition:
3643   //
3644   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3645   //
3646   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3647   // we can just replace Neg with Neg' for the rest of the function.
3648   //
3649   // In other cases we check for the even stronger condition:
3650   //
3651   //     Neg == OpSize - Pos                                    [B]
3652   //
3653   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3654   // behavior if Pos == 0 (and consequently Neg == OpSize).
3655   //
3656   // We could actually use [A] whenever OpSize is a power of 2, but the
3657   // only extra cases that it would match are those uninteresting ones
3658   // where Neg and Pos are never in range at the same time.  E.g. for
3659   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3660   // as well as (sub 32, Pos), but:
3661   //
3662   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3663   //
3664   // always invokes undefined behavior for 32-bit X.
3665   //
3666   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3667   unsigned MaskLoBits = 0;
3668   if (Neg.getOpcode() == ISD::AND &&
3669       isPowerOf2_64(OpSize) &&
3670       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3671       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3672     Neg = Neg.getOperand(0);
3673     MaskLoBits = Log2_64(OpSize);
3674   }
3675
3676   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3677   if (Neg.getOpcode() != ISD::SUB)
3678     return 0;
3679   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3680   if (!NegC)
3681     return 0;
3682   SDValue NegOp1 = Neg.getOperand(1);
3683
3684   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3685   // Pos'.  The truncation is redundant for the purpose of the equality.
3686   if (MaskLoBits &&
3687       Pos.getOpcode() == ISD::AND &&
3688       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3689       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3690     Pos = Pos.getOperand(0);
3691
3692   // The condition we need is now:
3693   //
3694   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3695   //
3696   // If NegOp1 == Pos then we need:
3697   //
3698   //              OpSize & Mask == NegC & Mask
3699   //
3700   // (because "x & Mask" is a truncation and distributes through subtraction).
3701   APInt Width;
3702   if (Pos == NegOp1)
3703     Width = NegC->getAPIntValue();
3704   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3705   // Then the condition we want to prove becomes:
3706   //
3707   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3708   //
3709   // which, again because "x & Mask" is a truncation, becomes:
3710   //
3711   //                NegC & Mask == (OpSize - PosC) & Mask
3712   //              OpSize & Mask == (NegC + PosC) & Mask
3713   else if (Pos.getOpcode() == ISD::ADD &&
3714            Pos.getOperand(0) == NegOp1 &&
3715            Pos.getOperand(1).getOpcode() == ISD::Constant)
3716     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3717              NegC->getAPIntValue());
3718   else
3719     return false;
3720
3721   // Now we just need to check that OpSize & Mask == Width & Mask.
3722   if (MaskLoBits)
3723     // Opsize & Mask is 0 since Mask is Opsize - 1.
3724     return Width.getLoBits(MaskLoBits) == 0;
3725   return Width == OpSize;
3726 }
3727
3728 // A subroutine of MatchRotate used once we have found an OR of two opposite
3729 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3730 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3731 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3732 // Neg with outer conversions stripped away.
3733 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3734                                        SDValue Neg, SDValue InnerPos,
3735                                        SDValue InnerNeg, unsigned PosOpcode,
3736                                        unsigned NegOpcode, SDLoc DL) {
3737   // fold (or (shl x, (*ext y)),
3738   //          (srl x, (*ext (sub 32, y)))) ->
3739   //   (rotl x, y) or (rotr x, (sub 32, y))
3740   //
3741   // fold (or (shl x, (*ext (sub 32, y))),
3742   //          (srl x, (*ext y))) ->
3743   //   (rotr x, y) or (rotl x, (sub 32, y))
3744   EVT VT = Shifted.getValueType();
3745   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3746     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3747     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3748                        HasPos ? Pos : Neg).getNode();
3749   }
3750
3751   return nullptr;
3752 }
3753
3754 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3755 // idioms for rotate, and if the target supports rotation instructions, generate
3756 // a rot[lr].
3757 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3758   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3759   EVT VT = LHS.getValueType();
3760   if (!TLI.isTypeLegal(VT)) return nullptr;
3761
3762   // The target must have at least one rotate flavor.
3763   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3764   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3765   if (!HasROTL && !HasROTR) return nullptr;
3766
3767   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3768   SDValue LHSShift;   // The shift.
3769   SDValue LHSMask;    // AND value if any.
3770   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3771     return nullptr; // Not part of a rotate.
3772
3773   SDValue RHSShift;   // The shift.
3774   SDValue RHSMask;    // AND value if any.
3775   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3776     return nullptr; // Not part of a rotate.
3777
3778   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3779     return nullptr;   // Not shifting the same value.
3780
3781   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3782     return nullptr;   // Shifts must disagree.
3783
3784   // Canonicalize shl to left side in a shl/srl pair.
3785   if (RHSShift.getOpcode() == ISD::SHL) {
3786     std::swap(LHS, RHS);
3787     std::swap(LHSShift, RHSShift);
3788     std::swap(LHSMask , RHSMask );
3789   }
3790
3791   unsigned OpSizeInBits = VT.getSizeInBits();
3792   SDValue LHSShiftArg = LHSShift.getOperand(0);
3793   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3794   SDValue RHSShiftArg = RHSShift.getOperand(0);
3795   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3796
3797   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3798   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3799   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3800       RHSShiftAmt.getOpcode() == ISD::Constant) {
3801     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3802     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3803     if ((LShVal + RShVal) != OpSizeInBits)
3804       return nullptr;
3805
3806     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3807                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3808
3809     // If there is an AND of either shifted operand, apply it to the result.
3810     if (LHSMask.getNode() || RHSMask.getNode()) {
3811       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3812
3813       if (LHSMask.getNode()) {
3814         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3815         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3816       }
3817       if (RHSMask.getNode()) {
3818         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3819         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3820       }
3821
3822       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3823     }
3824
3825     return Rot.getNode();
3826   }
3827
3828   // If there is a mask here, and we have a variable shift, we can't be sure
3829   // that we're masking out the right stuff.
3830   if (LHSMask.getNode() || RHSMask.getNode())
3831     return nullptr;
3832
3833   // If the shift amount is sign/zext/any-extended just peel it off.
3834   SDValue LExtOp0 = LHSShiftAmt;
3835   SDValue RExtOp0 = RHSShiftAmt;
3836   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3837        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3838        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3839        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3840       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3841        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3842        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3843        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3844     LExtOp0 = LHSShiftAmt.getOperand(0);
3845     RExtOp0 = RHSShiftAmt.getOperand(0);
3846   }
3847
3848   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3849                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3850   if (TryL)
3851     return TryL;
3852
3853   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3854                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3855   if (TryR)
3856     return TryR;
3857
3858   return nullptr;
3859 }
3860
3861 SDValue DAGCombiner::visitXOR(SDNode *N) {
3862   SDValue N0 = N->getOperand(0);
3863   SDValue N1 = N->getOperand(1);
3864   EVT VT = N0.getValueType();
3865
3866   // fold vector ops
3867   if (VT.isVector()) {
3868     SDValue FoldedVOp = SimplifyVBinOp(N);
3869     if (FoldedVOp.getNode()) return FoldedVOp;
3870
3871     // fold (xor x, 0) -> x, vector edition
3872     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3873       return N1;
3874     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3875       return N0;
3876   }
3877
3878   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3879   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3880     return DAG.getConstant(0, VT);
3881   // fold (xor x, undef) -> undef
3882   if (N0.getOpcode() == ISD::UNDEF)
3883     return N0;
3884   if (N1.getOpcode() == ISD::UNDEF)
3885     return N1;
3886   // fold (xor c1, c2) -> c1^c2
3887   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3888   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3889   if (N0C && N1C)
3890     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3891   // canonicalize constant to RHS
3892   if (N0C && !N1C)
3893     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3894   // fold (xor x, 0) -> x
3895   if (N1C && N1C->isNullValue())
3896     return N0;
3897   // reassociate xor
3898   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3899   if (RXOR.getNode())
3900     return RXOR;
3901
3902   // fold !(x cc y) -> (x !cc y)
3903   SDValue LHS, RHS, CC;
3904   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3905     bool isInt = LHS.getValueType().isInteger();
3906     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3907                                                isInt);
3908
3909     if (!LegalOperations ||
3910         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3911       switch (N0.getOpcode()) {
3912       default:
3913         llvm_unreachable("Unhandled SetCC Equivalent!");
3914       case ISD::SETCC:
3915         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3916       case ISD::SELECT_CC:
3917         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3918                                N0.getOperand(3), NotCC);
3919       }
3920     }
3921   }
3922
3923   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3924   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3925       N0.getNode()->hasOneUse() &&
3926       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3927     SDValue V = N0.getOperand(0);
3928     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3929                     DAG.getConstant(1, V.getValueType()));
3930     AddToWorklist(V.getNode());
3931     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3932   }
3933
3934   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3935   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3936       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3937     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3938     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3939       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3940       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3941       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3942       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3943       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3944     }
3945   }
3946   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3947   if (N1C && N1C->isAllOnesValue() &&
3948       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3949     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3950     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3951       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3952       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3953       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3954       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3955       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3956     }
3957   }
3958   // fold (xor (and x, y), y) -> (and (not x), y)
3959   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3960       N0->getOperand(1) == N1) {
3961     SDValue X = N0->getOperand(0);
3962     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3963     AddToWorklist(NotX.getNode());
3964     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3965   }
3966   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3967   if (N1C && N0.getOpcode() == ISD::XOR) {
3968     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3969     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3970     if (N00C)
3971       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3972                          DAG.getConstant(N1C->getAPIntValue() ^
3973                                          N00C->getAPIntValue(), VT));
3974     if (N01C)
3975       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3976                          DAG.getConstant(N1C->getAPIntValue() ^
3977                                          N01C->getAPIntValue(), VT));
3978   }
3979   // fold (xor x, x) -> 0
3980   if (N0 == N1)
3981     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3982
3983   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3984   if (N0.getOpcode() == N1.getOpcode()) {
3985     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3986     if (Tmp.getNode()) return Tmp;
3987   }
3988
3989   // Simplify the expression using non-local knowledge.
3990   if (!VT.isVector() &&
3991       SimplifyDemandedBits(SDValue(N, 0)))
3992     return SDValue(N, 0);
3993
3994   return SDValue();
3995 }
3996
3997 /// Handle transforms common to the three shifts, when the shift amount is a
3998 /// constant.
3999 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4000   // We can't and shouldn't fold opaque constants.
4001   if (Amt->isOpaque())
4002     return SDValue();
4003
4004   SDNode *LHS = N->getOperand(0).getNode();
4005   if (!LHS->hasOneUse()) return SDValue();
4006
4007   // We want to pull some binops through shifts, so that we have (and (shift))
4008   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4009   // thing happens with address calculations, so it's important to canonicalize
4010   // it.
4011   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4012
4013   switch (LHS->getOpcode()) {
4014   default: return SDValue();
4015   case ISD::OR:
4016   case ISD::XOR:
4017     HighBitSet = false; // We can only transform sra if the high bit is clear.
4018     break;
4019   case ISD::AND:
4020     HighBitSet = true;  // We can only transform sra if the high bit is set.
4021     break;
4022   case ISD::ADD:
4023     if (N->getOpcode() != ISD::SHL)
4024       return SDValue(); // only shl(add) not sr[al](add).
4025     HighBitSet = false; // We can only transform sra if the high bit is clear.
4026     break;
4027   }
4028
4029   // We require the RHS of the binop to be a constant and not opaque as well.
4030   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
4031   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
4032
4033   // FIXME: disable this unless the input to the binop is a shift by a constant.
4034   // If it is not a shift, it pessimizes some common cases like:
4035   //
4036   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4037   //    int bar(int *X, int i) { return X[i & 255]; }
4038   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4039   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4040        BinOpLHSVal->getOpcode() != ISD::SRA &&
4041        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4042       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4043     return SDValue();
4044
4045   EVT VT = N->getValueType(0);
4046
4047   // If this is a signed shift right, and the high bit is modified by the
4048   // logical operation, do not perform the transformation. The highBitSet
4049   // boolean indicates the value of the high bit of the constant which would
4050   // cause it to be modified for this operation.
4051   if (N->getOpcode() == ISD::SRA) {
4052     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4053     if (BinOpRHSSignSet != HighBitSet)
4054       return SDValue();
4055   }
4056
4057   if (!TLI.isDesirableToCommuteWithShift(LHS))
4058     return SDValue();
4059
4060   // Fold the constants, shifting the binop RHS by the shift amount.
4061   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4062                                N->getValueType(0),
4063                                LHS->getOperand(1), N->getOperand(1));
4064   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4065
4066   // Create the new shift.
4067   SDValue NewShift = DAG.getNode(N->getOpcode(),
4068                                  SDLoc(LHS->getOperand(0)),
4069                                  VT, LHS->getOperand(0), N->getOperand(1));
4070
4071   // Create the new binop.
4072   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4073 }
4074
4075 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4076   assert(N->getOpcode() == ISD::TRUNCATE);
4077   assert(N->getOperand(0).getOpcode() == ISD::AND);
4078
4079   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4080   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4081     SDValue N01 = N->getOperand(0).getOperand(1);
4082
4083     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4084       EVT TruncVT = N->getValueType(0);
4085       SDValue N00 = N->getOperand(0).getOperand(0);
4086       APInt TruncC = N01C->getAPIntValue();
4087       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4088
4089       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4090                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4091                          DAG.getConstant(TruncC, TruncVT));
4092     }
4093   }
4094
4095   return SDValue();
4096 }
4097
4098 SDValue DAGCombiner::visitRotate(SDNode *N) {
4099   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4100   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4101       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4102     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4103     if (NewOp1.getNode())
4104       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4105                          N->getOperand(0), NewOp1);
4106   }
4107   return SDValue();
4108 }
4109
4110 SDValue DAGCombiner::visitSHL(SDNode *N) {
4111   SDValue N0 = N->getOperand(0);
4112   SDValue N1 = N->getOperand(1);
4113   EVT VT = N0.getValueType();
4114   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4115
4116   // fold vector ops
4117   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4118   if (VT.isVector()) {
4119     SDValue FoldedVOp = SimplifyVBinOp(N);
4120     if (FoldedVOp.getNode()) return FoldedVOp;
4121
4122     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4123     // If setcc produces all-one true value then:
4124     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4125     if (N1CV && N1CV->isConstant()) {
4126       if (N0.getOpcode() == ISD::AND) {
4127         SDValue N00 = N0->getOperand(0);
4128         SDValue N01 = N0->getOperand(1);
4129         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4130
4131         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4132             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4133                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4134           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV))
4135             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4136         }
4137       } else {
4138         N1C = isConstOrConstSplat(N1);
4139       }
4140     }
4141   }
4142
4143   // fold (shl c1, c2) -> c1<<c2
4144   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4145   if (N0C && N1C)
4146     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4147   // fold (shl 0, x) -> 0
4148   if (N0C && N0C->isNullValue())
4149     return N0;
4150   // fold (shl x, c >= size(x)) -> undef
4151   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4152     return DAG.getUNDEF(VT);
4153   // fold (shl x, 0) -> x
4154   if (N1C && N1C->isNullValue())
4155     return N0;
4156   // fold (shl undef, x) -> 0
4157   if (N0.getOpcode() == ISD::UNDEF)
4158     return DAG.getConstant(0, VT);
4159   // if (shl x, c) is known to be zero, return 0
4160   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4161                             APInt::getAllOnesValue(OpSizeInBits)))
4162     return DAG.getConstant(0, VT);
4163   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4164   if (N1.getOpcode() == ISD::TRUNCATE &&
4165       N1.getOperand(0).getOpcode() == ISD::AND) {
4166     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4167     if (NewOp1.getNode())
4168       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4169   }
4170
4171   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4172     return SDValue(N, 0);
4173
4174   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4175   if (N1C && N0.getOpcode() == ISD::SHL) {
4176     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4177       uint64_t c1 = N0C1->getZExtValue();
4178       uint64_t c2 = N1C->getZExtValue();
4179       if (c1 + c2 >= OpSizeInBits)
4180         return DAG.getConstant(0, VT);
4181       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4182                          DAG.getConstant(c1 + c2, N1.getValueType()));
4183     }
4184   }
4185
4186   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4187   // For this to be valid, the second form must not preserve any of the bits
4188   // that are shifted out by the inner shift in the first form.  This means
4189   // the outer shift size must be >= the number of bits added by the ext.
4190   // As a corollary, we don't care what kind of ext it is.
4191   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4192               N0.getOpcode() == ISD::ANY_EXTEND ||
4193               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4194       N0.getOperand(0).getOpcode() == ISD::SHL) {
4195     SDValue N0Op0 = N0.getOperand(0);
4196     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4197       uint64_t c1 = N0Op0C1->getZExtValue();
4198       uint64_t c2 = N1C->getZExtValue();
4199       EVT InnerShiftVT = N0Op0.getValueType();
4200       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4201       if (c2 >= OpSizeInBits - InnerShiftSize) {
4202         if (c1 + c2 >= OpSizeInBits)
4203           return DAG.getConstant(0, VT);
4204         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4205                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4206                                        N0Op0->getOperand(0)),
4207                            DAG.getConstant(c1 + c2, N1.getValueType()));
4208       }
4209     }
4210   }
4211
4212   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4213   // Only fold this if the inner zext has no other uses to avoid increasing
4214   // the total number of instructions.
4215   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4216       N0.getOperand(0).getOpcode() == ISD::SRL) {
4217     SDValue N0Op0 = N0.getOperand(0);
4218     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4219       uint64_t c1 = N0Op0C1->getZExtValue();
4220       if (c1 < VT.getScalarSizeInBits()) {
4221         uint64_t c2 = N1C->getZExtValue();
4222         if (c1 == c2) {
4223           SDValue NewOp0 = N0.getOperand(0);
4224           EVT CountVT = NewOp0.getOperand(1).getValueType();
4225           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4226                                        NewOp0, DAG.getConstant(c2, CountVT));
4227           AddToWorklist(NewSHL.getNode());
4228           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4229         }
4230       }
4231     }
4232   }
4233
4234   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4235   //                               (and (srl x, (sub c1, c2), MASK)
4236   // Only fold this if the inner shift has no other uses -- if it does, folding
4237   // this will increase the total number of instructions.
4238   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4239     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4240       uint64_t c1 = N0C1->getZExtValue();
4241       if (c1 < OpSizeInBits) {
4242         uint64_t c2 = N1C->getZExtValue();
4243         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4244         SDValue Shift;
4245         if (c2 > c1) {
4246           Mask = Mask.shl(c2 - c1);
4247           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4248                               DAG.getConstant(c2 - c1, N1.getValueType()));
4249         } else {
4250           Mask = Mask.lshr(c1 - c2);
4251           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4252                               DAG.getConstant(c1 - c2, N1.getValueType()));
4253         }
4254         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4255                            DAG.getConstant(Mask, VT));
4256       }
4257     }
4258   }
4259   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4260   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4261     unsigned BitSize = VT.getScalarSizeInBits();
4262     SDValue HiBitsMask =
4263       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4264                                             BitSize - N1C->getZExtValue()), VT);
4265     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4266                        HiBitsMask);
4267   }
4268
4269   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4270   // Variant of version done on multiply, except mul by a power of 2 is turned
4271   // into a shift.
4272   APInt Val;
4273   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4274       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4275        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4276     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4277     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4278     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4279   }
4280
4281   if (N1C) {
4282     SDValue NewSHL = visitShiftByConstant(N, N1C);
4283     if (NewSHL.getNode())
4284       return NewSHL;
4285   }
4286
4287   return SDValue();
4288 }
4289
4290 SDValue DAGCombiner::visitSRA(SDNode *N) {
4291   SDValue N0 = N->getOperand(0);
4292   SDValue N1 = N->getOperand(1);
4293   EVT VT = N0.getValueType();
4294   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4295
4296   // fold vector ops
4297   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4298   if (VT.isVector()) {
4299     SDValue FoldedVOp = SimplifyVBinOp(N);
4300     if (FoldedVOp.getNode()) return FoldedVOp;
4301
4302     N1C = isConstOrConstSplat(N1);
4303   }
4304
4305   // fold (sra c1, c2) -> (sra c1, c2)
4306   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4307   if (N0C && N1C)
4308     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4309   // fold (sra 0, x) -> 0
4310   if (N0C && N0C->isNullValue())
4311     return N0;
4312   // fold (sra -1, x) -> -1
4313   if (N0C && N0C->isAllOnesValue())
4314     return N0;
4315   // fold (sra x, (setge c, size(x))) -> undef
4316   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4317     return DAG.getUNDEF(VT);
4318   // fold (sra x, 0) -> x
4319   if (N1C && N1C->isNullValue())
4320     return N0;
4321   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4322   // sext_inreg.
4323   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4324     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4325     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4326     if (VT.isVector())
4327       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4328                                ExtVT, VT.getVectorNumElements());
4329     if ((!LegalOperations ||
4330          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4331       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4332                          N0.getOperand(0), DAG.getValueType(ExtVT));
4333   }
4334
4335   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4336   if (N1C && N0.getOpcode() == ISD::SRA) {
4337     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4338       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4339       if (Sum >= OpSizeInBits)
4340         Sum = OpSizeInBits - 1;
4341       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4342                          DAG.getConstant(Sum, N1.getValueType()));
4343     }
4344   }
4345
4346   // fold (sra (shl X, m), (sub result_size, n))
4347   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4348   // result_size - n != m.
4349   // If truncate is free for the target sext(shl) is likely to result in better
4350   // code.
4351   if (N0.getOpcode() == ISD::SHL && N1C) {
4352     // Get the two constanst of the shifts, CN0 = m, CN = n.
4353     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4354     if (N01C) {
4355       LLVMContext &Ctx = *DAG.getContext();
4356       // Determine what the truncate's result bitsize and type would be.
4357       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4358
4359       if (VT.isVector())
4360         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4361
4362       // Determine the residual right-shift amount.
4363       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4364
4365       // If the shift is not a no-op (in which case this should be just a sign
4366       // extend already), the truncated to type is legal, sign_extend is legal
4367       // on that type, and the truncate to that type is both legal and free,
4368       // perform the transform.
4369       if ((ShiftAmt > 0) &&
4370           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4371           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4372           TLI.isTruncateFree(VT, TruncVT)) {
4373
4374           SDValue Amt = DAG.getConstant(ShiftAmt,
4375               getShiftAmountTy(N0.getOperand(0).getValueType()));
4376           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4377                                       N0.getOperand(0), Amt);
4378           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4379                                       Shift);
4380           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4381                              N->getValueType(0), Trunc);
4382       }
4383     }
4384   }
4385
4386   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4387   if (N1.getOpcode() == ISD::TRUNCATE &&
4388       N1.getOperand(0).getOpcode() == ISD::AND) {
4389     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4390     if (NewOp1.getNode())
4391       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4392   }
4393
4394   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4395   //      if c1 is equal to the number of bits the trunc removes
4396   if (N0.getOpcode() == ISD::TRUNCATE &&
4397       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4398        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4399       N0.getOperand(0).hasOneUse() &&
4400       N0.getOperand(0).getOperand(1).hasOneUse() &&
4401       N1C) {
4402     SDValue N0Op0 = N0.getOperand(0);
4403     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4404       unsigned LargeShiftVal = LargeShift->getZExtValue();
4405       EVT LargeVT = N0Op0.getValueType();
4406
4407       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4408         SDValue Amt =
4409           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4410                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4411         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4412                                   N0Op0.getOperand(0), Amt);
4413         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4414       }
4415     }
4416   }
4417
4418   // Simplify, based on bits shifted out of the LHS.
4419   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4420     return SDValue(N, 0);
4421
4422
4423   // If the sign bit is known to be zero, switch this to a SRL.
4424   if (DAG.SignBitIsZero(N0))
4425     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4426
4427   if (N1C) {
4428     SDValue NewSRA = visitShiftByConstant(N, N1C);
4429     if (NewSRA.getNode())
4430       return NewSRA;
4431   }
4432
4433   return SDValue();
4434 }
4435
4436 SDValue DAGCombiner::visitSRL(SDNode *N) {
4437   SDValue N0 = N->getOperand(0);
4438   SDValue N1 = N->getOperand(1);
4439   EVT VT = N0.getValueType();
4440   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4441
4442   // fold vector ops
4443   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4444   if (VT.isVector()) {
4445     SDValue FoldedVOp = SimplifyVBinOp(N);
4446     if (FoldedVOp.getNode()) return FoldedVOp;
4447
4448     N1C = isConstOrConstSplat(N1);
4449   }
4450
4451   // fold (srl c1, c2) -> c1 >>u c2
4452   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4453   if (N0C && N1C)
4454     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4455   // fold (srl 0, x) -> 0
4456   if (N0C && N0C->isNullValue())
4457     return N0;
4458   // fold (srl x, c >= size(x)) -> undef
4459   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4460     return DAG.getUNDEF(VT);
4461   // fold (srl x, 0) -> x
4462   if (N1C && N1C->isNullValue())
4463     return N0;
4464   // if (srl x, c) is known to be zero, return 0
4465   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4466                                    APInt::getAllOnesValue(OpSizeInBits)))
4467     return DAG.getConstant(0, VT);
4468
4469   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4470   if (N1C && N0.getOpcode() == ISD::SRL) {
4471     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4472       uint64_t c1 = N01C->getZExtValue();
4473       uint64_t c2 = N1C->getZExtValue();
4474       if (c1 + c2 >= OpSizeInBits)
4475         return DAG.getConstant(0, VT);
4476       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4477                          DAG.getConstant(c1 + c2, N1.getValueType()));
4478     }
4479   }
4480
4481   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4482   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4483       N0.getOperand(0).getOpcode() == ISD::SRL &&
4484       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4485     uint64_t c1 =
4486       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4487     uint64_t c2 = N1C->getZExtValue();
4488     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4489     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4490     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4491     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4492     if (c1 + OpSizeInBits == InnerShiftSize) {
4493       if (c1 + c2 >= InnerShiftSize)
4494         return DAG.getConstant(0, VT);
4495       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4496                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4497                                      N0.getOperand(0)->getOperand(0),
4498                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4499     }
4500   }
4501
4502   // fold (srl (shl x, c), c) -> (and x, cst2)
4503   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4504     unsigned BitSize = N0.getScalarValueSizeInBits();
4505     if (BitSize <= 64) {
4506       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4507       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4508                          DAG.getConstant(~0ULL >> ShAmt, VT));
4509     }
4510   }
4511
4512   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4513   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4514     // Shifting in all undef bits?
4515     EVT SmallVT = N0.getOperand(0).getValueType();
4516     unsigned BitSize = SmallVT.getScalarSizeInBits();
4517     if (N1C->getZExtValue() >= BitSize)
4518       return DAG.getUNDEF(VT);
4519
4520     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4521       uint64_t ShiftAmt = N1C->getZExtValue();
4522       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4523                                        N0.getOperand(0),
4524                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4525       AddToWorklist(SmallShift.getNode());
4526       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4527       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4528                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4529                          DAG.getConstant(Mask, VT));
4530     }
4531   }
4532
4533   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4534   // bit, which is unmodified by sra.
4535   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4536     if (N0.getOpcode() == ISD::SRA)
4537       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4538   }
4539
4540   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4541   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4542       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4543     APInt KnownZero, KnownOne;
4544     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4545
4546     // If any of the input bits are KnownOne, then the input couldn't be all
4547     // zeros, thus the result of the srl will always be zero.
4548     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4549
4550     // If all of the bits input the to ctlz node are known to be zero, then
4551     // the result of the ctlz is "32" and the result of the shift is one.
4552     APInt UnknownBits = ~KnownZero;
4553     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4554
4555     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4556     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4557       // Okay, we know that only that the single bit specified by UnknownBits
4558       // could be set on input to the CTLZ node. If this bit is set, the SRL
4559       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4560       // to an SRL/XOR pair, which is likely to simplify more.
4561       unsigned ShAmt = UnknownBits.countTrailingZeros();
4562       SDValue Op = N0.getOperand(0);
4563
4564       if (ShAmt) {
4565         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4566                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4567         AddToWorklist(Op.getNode());
4568       }
4569
4570       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4571                          Op, DAG.getConstant(1, VT));
4572     }
4573   }
4574
4575   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4576   if (N1.getOpcode() == ISD::TRUNCATE &&
4577       N1.getOperand(0).getOpcode() == ISD::AND) {
4578     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4579     if (NewOp1.getNode())
4580       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4581   }
4582
4583   // fold operands of srl based on knowledge that the low bits are not
4584   // demanded.
4585   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4586     return SDValue(N, 0);
4587
4588   if (N1C) {
4589     SDValue NewSRL = visitShiftByConstant(N, N1C);
4590     if (NewSRL.getNode())
4591       return NewSRL;
4592   }
4593
4594   // Attempt to convert a srl of a load into a narrower zero-extending load.
4595   SDValue NarrowLoad = ReduceLoadWidth(N);
4596   if (NarrowLoad.getNode())
4597     return NarrowLoad;
4598
4599   // Here is a common situation. We want to optimize:
4600   //
4601   //   %a = ...
4602   //   %b = and i32 %a, 2
4603   //   %c = srl i32 %b, 1
4604   //   brcond i32 %c ...
4605   //
4606   // into
4607   //
4608   //   %a = ...
4609   //   %b = and %a, 2
4610   //   %c = setcc eq %b, 0
4611   //   brcond %c ...
4612   //
4613   // However when after the source operand of SRL is optimized into AND, the SRL
4614   // itself may not be optimized further. Look for it and add the BRCOND into
4615   // the worklist.
4616   if (N->hasOneUse()) {
4617     SDNode *Use = *N->use_begin();
4618     if (Use->getOpcode() == ISD::BRCOND)
4619       AddToWorklist(Use);
4620     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4621       // Also look pass the truncate.
4622       Use = *Use->use_begin();
4623       if (Use->getOpcode() == ISD::BRCOND)
4624         AddToWorklist(Use);
4625     }
4626   }
4627
4628   return SDValue();
4629 }
4630
4631 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4632   SDValue N0 = N->getOperand(0);
4633   EVT VT = N->getValueType(0);
4634
4635   // fold (ctlz c1) -> c2
4636   if (isa<ConstantSDNode>(N0))
4637     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4638   return SDValue();
4639 }
4640
4641 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4642   SDValue N0 = N->getOperand(0);
4643   EVT VT = N->getValueType(0);
4644
4645   // fold (ctlz_zero_undef c1) -> c2
4646   if (isa<ConstantSDNode>(N0))
4647     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4648   return SDValue();
4649 }
4650
4651 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4652   SDValue N0 = N->getOperand(0);
4653   EVT VT = N->getValueType(0);
4654
4655   // fold (cttz c1) -> c2
4656   if (isa<ConstantSDNode>(N0))
4657     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4658   return SDValue();
4659 }
4660
4661 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4662   SDValue N0 = N->getOperand(0);
4663   EVT VT = N->getValueType(0);
4664
4665   // fold (cttz_zero_undef c1) -> c2
4666   if (isa<ConstantSDNode>(N0))
4667     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4668   return SDValue();
4669 }
4670
4671 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4672   SDValue N0 = N->getOperand(0);
4673   EVT VT = N->getValueType(0);
4674
4675   // fold (ctpop c1) -> c2
4676   if (isa<ConstantSDNode>(N0))
4677     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4678   return SDValue();
4679 }
4680
4681
4682 /// \brief Generate Min/Max node
4683 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4684                                    SDValue True, SDValue False,
4685                                    ISD::CondCode CC, const TargetLowering &TLI,
4686                                    SelectionDAG &DAG) {
4687   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4688     return SDValue();
4689
4690   switch (CC) {
4691   case ISD::SETOLT:
4692   case ISD::SETOLE:
4693   case ISD::SETLT:
4694   case ISD::SETLE:
4695   case ISD::SETULT:
4696   case ISD::SETULE: {
4697     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4698     if (TLI.isOperationLegal(Opcode, VT))
4699       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4700     return SDValue();
4701   }
4702   case ISD::SETOGT:
4703   case ISD::SETOGE:
4704   case ISD::SETGT:
4705   case ISD::SETGE:
4706   case ISD::SETUGT:
4707   case ISD::SETUGE: {
4708     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4709     if (TLI.isOperationLegal(Opcode, VT))
4710       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4711     return SDValue();
4712   }
4713   default:
4714     return SDValue();
4715   }
4716 }
4717
4718 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4719   SDValue N0 = N->getOperand(0);
4720   SDValue N1 = N->getOperand(1);
4721   SDValue N2 = N->getOperand(2);
4722   EVT VT = N->getValueType(0);
4723   EVT VT0 = N0.getValueType();
4724
4725   // fold (select C, X, X) -> X
4726   if (N1 == N2)
4727     return N1;
4728   // fold (select true, X, Y) -> X
4729   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4730   if (N0C && !N0C->isNullValue())
4731     return N1;
4732   // fold (select false, X, Y) -> Y
4733   if (N0C && N0C->isNullValue())
4734     return N2;
4735   // fold (select C, 1, X) -> (or C, X)
4736   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4737   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4738     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4739   // fold (select C, 0, 1) -> (xor C, 1)
4740   // We can't do this reliably if integer based booleans have different contents
4741   // to floating point based booleans. This is because we can't tell whether we
4742   // have an integer-based boolean or a floating-point-based boolean unless we
4743   // can find the SETCC that produced it and inspect its operands. This is
4744   // fairly easy if C is the SETCC node, but it can potentially be
4745   // undiscoverable (or not reasonably discoverable). For example, it could be
4746   // in another basic block or it could require searching a complicated
4747   // expression.
4748   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4749   if (VT.isInteger() &&
4750       (VT0 == MVT::i1 || (VT0.isInteger() &&
4751                           TLI.getBooleanContents(false, false) ==
4752                               TLI.getBooleanContents(false, true) &&
4753                           TLI.getBooleanContents(false, false) ==
4754                               TargetLowering::ZeroOrOneBooleanContent)) &&
4755       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4756     SDValue XORNode;
4757     if (VT == VT0)
4758       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4759                          N0, DAG.getConstant(1, VT0));
4760     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4761                           N0, DAG.getConstant(1, VT0));
4762     AddToWorklist(XORNode.getNode());
4763     if (VT.bitsGT(VT0))
4764       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4765     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4766   }
4767   // fold (select C, 0, X) -> (and (not C), X)
4768   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4769     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4770     AddToWorklist(NOTNode.getNode());
4771     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4772   }
4773   // fold (select C, X, 1) -> (or (not C), X)
4774   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4775     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4776     AddToWorklist(NOTNode.getNode());
4777     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4778   }
4779   // fold (select C, X, 0) -> (and C, X)
4780   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4781     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4782   // fold (select X, X, Y) -> (or X, Y)
4783   // fold (select X, 1, Y) -> (or X, Y)
4784   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4785     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4786   // fold (select X, Y, X) -> (and X, Y)
4787   // fold (select X, Y, 0) -> (and X, Y)
4788   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4789     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4790
4791   // If we can fold this based on the true/false value, do so.
4792   if (SimplifySelectOps(N, N1, N2))
4793     return SDValue(N, 0);  // Don't revisit N.
4794
4795   // fold selects based on a setcc into other things, such as min/max/abs
4796   if (N0.getOpcode() == ISD::SETCC) {
4797     // select x, y (fcmp lt x, y) -> fminnum x, y
4798     // select x, y (fcmp gt x, y) -> fmaxnum x, y
4799     //
4800     // This is OK if we don't care about what happens if either operand is a
4801     // NaN.
4802     //
4803
4804     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4805     // no signed zeros as well as no nans.
4806     const TargetOptions &Options = DAG.getTarget().Options;
4807     if (Options.UnsafeFPMath &&
4808         VT.isFloatingPoint() && N0.hasOneUse() &&
4809         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4810       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4811
4812       SDValue FMinMax =
4813           combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4814                               N1, N2, CC, TLI, DAG);
4815       if (FMinMax)
4816         return FMinMax;
4817     }
4818
4819     if ((!LegalOperations &&
4820          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4821         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4822       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4823                          N0.getOperand(0), N0.getOperand(1),
4824                          N1, N2, N0.getOperand(2));
4825     return SimplifySelect(SDLoc(N), N0, N1, N2);
4826   }
4827
4828   if (VT0 == MVT::i1) {
4829     if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4830       // select (and Cond0, Cond1), X, Y
4831       //   -> select Cond0, (select Cond1, X, Y), Y
4832       if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4833         SDValue Cond0 = N0->getOperand(0);
4834         SDValue Cond1 = N0->getOperand(1);
4835         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4836                                           N1.getValueType(), Cond1, N1, N2);
4837         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4838                            InnerSelect, N2);
4839       }
4840       // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4841       if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4842         SDValue Cond0 = N0->getOperand(0);
4843         SDValue Cond1 = N0->getOperand(1);
4844         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4845                                           N1.getValueType(), Cond1, N1, N2);
4846         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4847                            InnerSelect);
4848       }
4849     }
4850
4851     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4852     if (N1->getOpcode() == ISD::SELECT) {
4853       SDValue N1_0 = N1->getOperand(0);
4854       SDValue N1_1 = N1->getOperand(1);
4855       SDValue N1_2 = N1->getOperand(2);
4856       if (N1_2 == N2) {
4857         // Create the actual and node if we can generate good code for it.
4858         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4859           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4860                                     N0, N1_0);
4861           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4862                              N1_1, N2);
4863         }
4864         // Otherwise see if we can optimize the "and" to a better pattern.
4865         if (SDValue Combined = visitANDLike(N0, N1_0, N))
4866           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4867                              N1_1, N2);
4868       }
4869     }
4870     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4871     if (N2->getOpcode() == ISD::SELECT) {
4872       SDValue N2_0 = N2->getOperand(0);
4873       SDValue N2_1 = N2->getOperand(1);
4874       SDValue N2_2 = N2->getOperand(2);
4875       if (N2_1 == N1) {
4876         // Create the actual or node if we can generate good code for it.
4877         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4878           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
4879                                    N0, N2_0);
4880           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
4881                              N1, N2_2);
4882         }
4883         // Otherwise see if we can optimize to a better pattern.
4884         if (SDValue Combined = visitORLike(N0, N2_0, N))
4885           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4886                              N1, N2_2);
4887       }
4888     }
4889   }
4890
4891   return SDValue();
4892 }
4893
4894 static
4895 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4896   SDLoc DL(N);
4897   EVT LoVT, HiVT;
4898   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4899
4900   // Split the inputs.
4901   SDValue Lo, Hi, LL, LH, RL, RH;
4902   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4903   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4904
4905   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4906   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4907
4908   return std::make_pair(Lo, Hi);
4909 }
4910
4911 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4912 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4913 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4914   SDLoc dl(N);
4915   SDValue Cond = N->getOperand(0);
4916   SDValue LHS = N->getOperand(1);
4917   SDValue RHS = N->getOperand(2);
4918   EVT VT = N->getValueType(0);
4919   int NumElems = VT.getVectorNumElements();
4920   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4921          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4922          Cond.getOpcode() == ISD::BUILD_VECTOR);
4923
4924   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4925   // binary ones here.
4926   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4927     return SDValue();
4928
4929   // We're sure we have an even number of elements due to the
4930   // concat_vectors we have as arguments to vselect.
4931   // Skip BV elements until we find one that's not an UNDEF
4932   // After we find an UNDEF element, keep looping until we get to half the
4933   // length of the BV and see if all the non-undef nodes are the same.
4934   ConstantSDNode *BottomHalf = nullptr;
4935   for (int i = 0; i < NumElems / 2; ++i) {
4936     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4937       continue;
4938
4939     if (BottomHalf == nullptr)
4940       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4941     else if (Cond->getOperand(i).getNode() != BottomHalf)
4942       return SDValue();
4943   }
4944
4945   // Do the same for the second half of the BuildVector
4946   ConstantSDNode *TopHalf = nullptr;
4947   for (int i = NumElems / 2; i < NumElems; ++i) {
4948     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4949       continue;
4950
4951     if (TopHalf == nullptr)
4952       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4953     else if (Cond->getOperand(i).getNode() != TopHalf)
4954       return SDValue();
4955   }
4956
4957   assert(TopHalf && BottomHalf &&
4958          "One half of the selector was all UNDEFs and the other was all the "
4959          "same value. This should have been addressed before this function.");
4960   return DAG.getNode(
4961       ISD::CONCAT_VECTORS, dl, VT,
4962       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4963       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4964 }
4965
4966 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
4967
4968   if (Level >= AfterLegalizeTypes)
4969     return SDValue();
4970
4971   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
4972   SDValue Mask = MST->getMask();
4973   SDValue Data  = MST->getValue();
4974   SDLoc DL(N);
4975
4976   // If the MSTORE data type requires splitting and the mask is provided by a
4977   // SETCC, then split both nodes and its operands before legalization. This
4978   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4979   // and enables future optimizations (e.g. min/max pattern matching on X86).
4980   if (Mask.getOpcode() == ISD::SETCC) {
4981
4982     // Check if any splitting is required.
4983     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
4984         TargetLowering::TypeSplitVector)
4985       return SDValue();
4986
4987     SDValue MaskLo, MaskHi, Lo, Hi;
4988     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4989
4990     EVT LoVT, HiVT;
4991     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
4992
4993     SDValue Chain = MST->getChain();
4994     SDValue Ptr   = MST->getBasePtr();
4995
4996     EVT MemoryVT = MST->getMemoryVT();
4997     unsigned Alignment = MST->getOriginalAlignment();
4998
4999     // if Alignment is equal to the vector size,
5000     // take the half of it for the second part
5001     unsigned SecondHalfAlignment =
5002       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5003          Alignment/2 : Alignment;
5004
5005     EVT LoMemVT, HiMemVT;
5006     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5007
5008     SDValue DataLo, DataHi;
5009     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5010
5011     MachineMemOperand *MMO = DAG.getMachineFunction().
5012       getMachineMemOperand(MST->getPointerInfo(),
5013                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5014                            Alignment, MST->getAAInfo(), MST->getRanges());
5015
5016     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5017                             MST->isTruncatingStore());
5018
5019     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5020     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5021                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
5022
5023     MMO = DAG.getMachineFunction().
5024       getMachineMemOperand(MST->getPointerInfo(),
5025                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5026                            SecondHalfAlignment, MST->getAAInfo(),
5027                            MST->getRanges());
5028
5029     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5030                             MST->isTruncatingStore());
5031
5032     AddToWorklist(Lo.getNode());
5033     AddToWorklist(Hi.getNode());
5034
5035     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5036   }
5037   return SDValue();
5038 }
5039
5040 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5041
5042   if (Level >= AfterLegalizeTypes)
5043     return SDValue();
5044
5045   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5046   SDValue Mask = MLD->getMask();
5047   SDLoc DL(N);
5048
5049   // If the MLOAD result requires splitting and the mask is provided by a
5050   // SETCC, then split both nodes and its operands before legalization. This
5051   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5052   // and enables future optimizations (e.g. min/max pattern matching on X86).
5053
5054   if (Mask.getOpcode() == ISD::SETCC) {
5055     EVT VT = N->getValueType(0);
5056
5057     // Check if any splitting is required.
5058     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5059         TargetLowering::TypeSplitVector)
5060       return SDValue();
5061
5062     SDValue MaskLo, MaskHi, Lo, Hi;
5063     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5064
5065     SDValue Src0 = MLD->getSrc0();
5066     SDValue Src0Lo, Src0Hi;
5067     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5068
5069     EVT LoVT, HiVT;
5070     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5071
5072     SDValue Chain = MLD->getChain();
5073     SDValue Ptr   = MLD->getBasePtr();
5074     EVT MemoryVT = MLD->getMemoryVT();
5075     unsigned Alignment = MLD->getOriginalAlignment();
5076
5077     // if Alignment is equal to the vector size,
5078     // take the half of it for the second part
5079     unsigned SecondHalfAlignment =
5080       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5081          Alignment/2 : Alignment;
5082
5083     EVT LoMemVT, HiMemVT;
5084     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5085
5086     MachineMemOperand *MMO = DAG.getMachineFunction().
5087     getMachineMemOperand(MLD->getPointerInfo(),
5088                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5089                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5090
5091     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5092                            ISD::NON_EXTLOAD);
5093
5094     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5095     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5096                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
5097
5098     MMO = DAG.getMachineFunction().
5099     getMachineMemOperand(MLD->getPointerInfo(),
5100                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5101                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5102
5103     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5104                            ISD::NON_EXTLOAD);
5105
5106     AddToWorklist(Lo.getNode());
5107     AddToWorklist(Hi.getNode());
5108
5109     // Build a factor node to remember that this load is independent of the
5110     // other one.
5111     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5112                         Hi.getValue(1));
5113
5114     // Legalized the chain result - switch anything that used the old chain to
5115     // use the new one.
5116     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5117
5118     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5119
5120     SDValue RetOps[] = { LoadRes, Chain };
5121     return DAG.getMergeValues(RetOps, DL);
5122   }
5123   return SDValue();
5124 }
5125
5126 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5127   SDValue N0 = N->getOperand(0);
5128   SDValue N1 = N->getOperand(1);
5129   SDValue N2 = N->getOperand(2);
5130   SDLoc DL(N);
5131
5132   // Canonicalize integer abs.
5133   // vselect (setg[te] X,  0),  X, -X ->
5134   // vselect (setgt    X, -1),  X, -X ->
5135   // vselect (setl[te] X,  0), -X,  X ->
5136   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5137   if (N0.getOpcode() == ISD::SETCC) {
5138     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5139     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5140     bool isAbs = false;
5141     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5142
5143     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5144          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5145         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5146       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5147     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5148              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5149       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5150
5151     if (isAbs) {
5152       EVT VT = LHS.getValueType();
5153       SDValue Shift = DAG.getNode(
5154           ISD::SRA, DL, VT, LHS,
5155           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
5156       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5157       AddToWorklist(Shift.getNode());
5158       AddToWorklist(Add.getNode());
5159       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5160     }
5161   }
5162
5163   // If the VSELECT result requires splitting and the mask is provided by a
5164   // SETCC, then split both nodes and its operands before legalization. This
5165   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5166   // and enables future optimizations (e.g. min/max pattern matching on X86).
5167   if (N0.getOpcode() == ISD::SETCC) {
5168     EVT VT = N->getValueType(0);
5169
5170     // Check if any splitting is required.
5171     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5172         TargetLowering::TypeSplitVector)
5173       return SDValue();
5174
5175     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5176     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5177     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5178     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5179
5180     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5181     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5182
5183     // Add the new VSELECT nodes to the work list in case they need to be split
5184     // again.
5185     AddToWorklist(Lo.getNode());
5186     AddToWorklist(Hi.getNode());
5187
5188     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5189   }
5190
5191   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5192   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5193     return N1;
5194   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5195   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5196     return N2;
5197
5198   // The ConvertSelectToConcatVector function is assuming both the above
5199   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5200   // and addressed.
5201   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5202       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5203       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5204     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5205     if (CV.getNode())
5206       return CV;
5207   }
5208
5209   return SDValue();
5210 }
5211
5212 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5213   SDValue N0 = N->getOperand(0);
5214   SDValue N1 = N->getOperand(1);
5215   SDValue N2 = N->getOperand(2);
5216   SDValue N3 = N->getOperand(3);
5217   SDValue N4 = N->getOperand(4);
5218   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5219
5220   // fold select_cc lhs, rhs, x, x, cc -> x
5221   if (N2 == N3)
5222     return N2;
5223
5224   // Determine if the condition we're dealing with is constant
5225   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5226                               N0, N1, CC, SDLoc(N), false);
5227   if (SCC.getNode()) {
5228     AddToWorklist(SCC.getNode());
5229
5230     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5231       if (!SCCC->isNullValue())
5232         return N2;    // cond always true -> true val
5233       else
5234         return N3;    // cond always false -> false val
5235     } else if (SCC->getOpcode() == ISD::UNDEF) {
5236       // When the condition is UNDEF, just return the first operand. This is
5237       // coherent the DAG creation, no setcc node is created in this case
5238       return N2;
5239     } else if (SCC.getOpcode() == ISD::SETCC) {
5240       // Fold to a simpler select_cc
5241       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5242                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5243                          SCC.getOperand(2));
5244     }
5245   }
5246
5247   // If we can fold this based on the true/false value, do so.
5248   if (SimplifySelectOps(N, N2, N3))
5249     return SDValue(N, 0);  // Don't revisit N.
5250
5251   // fold select_cc into other things, such as min/max/abs
5252   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5253 }
5254
5255 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5256   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5257                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5258                        SDLoc(N));
5259 }
5260
5261 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5262 // dag node into a ConstantSDNode or a build_vector of constants.
5263 // This function is called by the DAGCombiner when visiting sext/zext/aext
5264 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5265 // Vector extends are not folded if operations are legal; this is to
5266 // avoid introducing illegal build_vector dag nodes.
5267 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5268                                          SelectionDAG &DAG, bool LegalTypes,
5269                                          bool LegalOperations) {
5270   unsigned Opcode = N->getOpcode();
5271   SDValue N0 = N->getOperand(0);
5272   EVT VT = N->getValueType(0);
5273
5274   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5275          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5276
5277   // fold (sext c1) -> c1
5278   // fold (zext c1) -> c1
5279   // fold (aext c1) -> c1
5280   if (isa<ConstantSDNode>(N0))
5281     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5282
5283   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5284   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5285   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5286   EVT SVT = VT.getScalarType();
5287   if (!(VT.isVector() &&
5288       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5289       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5290     return nullptr;
5291
5292   // We can fold this node into a build_vector.
5293   unsigned VTBits = SVT.getSizeInBits();
5294   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5295   unsigned ShAmt = VTBits - EVTBits;
5296   SmallVector<SDValue, 8> Elts;
5297   unsigned NumElts = N0->getNumOperands();
5298   SDLoc DL(N);
5299
5300   for (unsigned i=0; i != NumElts; ++i) {
5301     SDValue Op = N0->getOperand(i);
5302     if (Op->getOpcode() == ISD::UNDEF) {
5303       Elts.push_back(DAG.getUNDEF(SVT));
5304       continue;
5305     }
5306
5307     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5308     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5309     if (Opcode == ISD::SIGN_EXTEND)
5310       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5311                                      SVT));
5312     else
5313       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5314                                      SVT));
5315   }
5316
5317   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5318 }
5319
5320 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5321 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5322 // transformation. Returns true if extension are possible and the above
5323 // mentioned transformation is profitable.
5324 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5325                                     unsigned ExtOpc,
5326                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5327                                     const TargetLowering &TLI) {
5328   bool HasCopyToRegUses = false;
5329   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5330   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5331                             UE = N0.getNode()->use_end();
5332        UI != UE; ++UI) {
5333     SDNode *User = *UI;
5334     if (User == N)
5335       continue;
5336     if (UI.getUse().getResNo() != N0.getResNo())
5337       continue;
5338     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5339     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5340       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5341       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5342         // Sign bits will be lost after a zext.
5343         return false;
5344       bool Add = false;
5345       for (unsigned i = 0; i != 2; ++i) {
5346         SDValue UseOp = User->getOperand(i);
5347         if (UseOp == N0)
5348           continue;
5349         if (!isa<ConstantSDNode>(UseOp))
5350           return false;
5351         Add = true;
5352       }
5353       if (Add)
5354         ExtendNodes.push_back(User);
5355       continue;
5356     }
5357     // If truncates aren't free and there are users we can't
5358     // extend, it isn't worthwhile.
5359     if (!isTruncFree)
5360       return false;
5361     // Remember if this value is live-out.
5362     if (User->getOpcode() == ISD::CopyToReg)
5363       HasCopyToRegUses = true;
5364   }
5365
5366   if (HasCopyToRegUses) {
5367     bool BothLiveOut = false;
5368     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5369          UI != UE; ++UI) {
5370       SDUse &Use = UI.getUse();
5371       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5372         BothLiveOut = true;
5373         break;
5374       }
5375     }
5376     if (BothLiveOut)
5377       // Both unextended and extended values are live out. There had better be
5378       // a good reason for the transformation.
5379       return ExtendNodes.size();
5380   }
5381   return true;
5382 }
5383
5384 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5385                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5386                                   ISD::NodeType ExtType) {
5387   // Extend SetCC uses if necessary.
5388   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5389     SDNode *SetCC = SetCCs[i];
5390     SmallVector<SDValue, 4> Ops;
5391
5392     for (unsigned j = 0; j != 2; ++j) {
5393       SDValue SOp = SetCC->getOperand(j);
5394       if (SOp == Trunc)
5395         Ops.push_back(ExtLoad);
5396       else
5397         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5398     }
5399
5400     Ops.push_back(SetCC->getOperand(2));
5401     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5402   }
5403 }
5404
5405 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5406 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5407   SDValue N0 = N->getOperand(0);
5408   EVT DstVT = N->getValueType(0);
5409   EVT SrcVT = N0.getValueType();
5410
5411   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5412           N->getOpcode() == ISD::ZERO_EXTEND) &&
5413          "Unexpected node type (not an extend)!");
5414
5415   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5416   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5417   //   (v8i32 (sext (v8i16 (load x))))
5418   // into:
5419   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5420   //                          (v4i32 (sextload (x + 16)))))
5421   // Where uses of the original load, i.e.:
5422   //   (v8i16 (load x))
5423   // are replaced with:
5424   //   (v8i16 (truncate
5425   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5426   //                            (v4i32 (sextload (x + 16)))))))
5427   //
5428   // This combine is only applicable to illegal, but splittable, vectors.
5429   // All legal types, and illegal non-vector types, are handled elsewhere.
5430   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5431   //
5432   if (N0->getOpcode() != ISD::LOAD)
5433     return SDValue();
5434
5435   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5436
5437   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5438       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5439       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5440     return SDValue();
5441
5442   SmallVector<SDNode *, 4> SetCCs;
5443   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5444     return SDValue();
5445
5446   ISD::LoadExtType ExtType =
5447       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5448
5449   // Try to split the vector types to get down to legal types.
5450   EVT SplitSrcVT = SrcVT;
5451   EVT SplitDstVT = DstVT;
5452   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5453          SplitSrcVT.getVectorNumElements() > 1) {
5454     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5455     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5456   }
5457
5458   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5459     return SDValue();
5460
5461   SDLoc DL(N);
5462   const unsigned NumSplits =
5463       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5464   const unsigned Stride = SplitSrcVT.getStoreSize();
5465   SmallVector<SDValue, 4> Loads;
5466   SmallVector<SDValue, 4> Chains;
5467
5468   SDValue BasePtr = LN0->getBasePtr();
5469   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5470     const unsigned Offset = Idx * Stride;
5471     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5472
5473     SDValue SplitLoad = DAG.getExtLoad(
5474         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5475         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5476         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5477         Align, LN0->getAAInfo());
5478
5479     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5480                           DAG.getConstant(Stride, BasePtr.getValueType()));
5481
5482     Loads.push_back(SplitLoad.getValue(0));
5483     Chains.push_back(SplitLoad.getValue(1));
5484   }
5485
5486   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5487   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5488
5489   CombineTo(N, NewValue);
5490
5491   // Replace uses of the original load (before extension)
5492   // with a truncate of the concatenated sextloaded vectors.
5493   SDValue Trunc =
5494       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5495   CombineTo(N0.getNode(), Trunc, NewChain);
5496   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5497                   (ISD::NodeType)N->getOpcode());
5498   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5499 }
5500
5501 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5502   SDValue N0 = N->getOperand(0);
5503   EVT VT = N->getValueType(0);
5504
5505   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5506                                               LegalOperations))
5507     return SDValue(Res, 0);
5508
5509   // fold (sext (sext x)) -> (sext x)
5510   // fold (sext (aext x)) -> (sext x)
5511   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5512     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5513                        N0.getOperand(0));
5514
5515   if (N0.getOpcode() == ISD::TRUNCATE) {
5516     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5517     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5518     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5519     if (NarrowLoad.getNode()) {
5520       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5521       if (NarrowLoad.getNode() != N0.getNode()) {
5522         CombineTo(N0.getNode(), NarrowLoad);
5523         // CombineTo deleted the truncate, if needed, but not what's under it.
5524         AddToWorklist(oye);
5525       }
5526       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5527     }
5528
5529     // See if the value being truncated is already sign extended.  If so, just
5530     // eliminate the trunc/sext pair.
5531     SDValue Op = N0.getOperand(0);
5532     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5533     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5534     unsigned DestBits = VT.getScalarType().getSizeInBits();
5535     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5536
5537     if (OpBits == DestBits) {
5538       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5539       // bits, it is already ready.
5540       if (NumSignBits > DestBits-MidBits)
5541         return Op;
5542     } else if (OpBits < DestBits) {
5543       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5544       // bits, just sext from i32.
5545       if (NumSignBits > OpBits-MidBits)
5546         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5547     } else {
5548       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5549       // bits, just truncate to i32.
5550       if (NumSignBits > OpBits-MidBits)
5551         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5552     }
5553
5554     // fold (sext (truncate x)) -> (sextinreg x).
5555     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5556                                                  N0.getValueType())) {
5557       if (OpBits < DestBits)
5558         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5559       else if (OpBits > DestBits)
5560         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5561       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5562                          DAG.getValueType(N0.getValueType()));
5563     }
5564   }
5565
5566   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5567   // Only generate vector extloads when 1) they're legal, and 2) they are
5568   // deemed desirable by the target.
5569   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5570       ((!LegalOperations && !VT.isVector() &&
5571         !cast<LoadSDNode>(N0)->isVolatile()) ||
5572        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5573     bool DoXform = true;
5574     SmallVector<SDNode*, 4> SetCCs;
5575     if (!N0.hasOneUse())
5576       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5577     if (VT.isVector())
5578       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5579     if (DoXform) {
5580       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5581       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5582                                        LN0->getChain(),
5583                                        LN0->getBasePtr(), N0.getValueType(),
5584                                        LN0->getMemOperand());
5585       CombineTo(N, ExtLoad);
5586       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5587                                   N0.getValueType(), ExtLoad);
5588       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5589       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5590                       ISD::SIGN_EXTEND);
5591       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5592     }
5593   }
5594
5595   // fold (sext (load x)) to multiple smaller sextloads.
5596   // Only on illegal but splittable vectors.
5597   if (SDValue ExtLoad = CombineExtLoad(N))
5598     return ExtLoad;
5599
5600   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5601   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5602   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5603       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5604     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5605     EVT MemVT = LN0->getMemoryVT();
5606     if ((!LegalOperations && !LN0->isVolatile()) ||
5607         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5608       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5609                                        LN0->getChain(),
5610                                        LN0->getBasePtr(), MemVT,
5611                                        LN0->getMemOperand());
5612       CombineTo(N, ExtLoad);
5613       CombineTo(N0.getNode(),
5614                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5615                             N0.getValueType(), ExtLoad),
5616                 ExtLoad.getValue(1));
5617       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5618     }
5619   }
5620
5621   // fold (sext (and/or/xor (load x), cst)) ->
5622   //      (and/or/xor (sextload x), (sext cst))
5623   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5624        N0.getOpcode() == ISD::XOR) &&
5625       isa<LoadSDNode>(N0.getOperand(0)) &&
5626       N0.getOperand(1).getOpcode() == ISD::Constant &&
5627       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5628       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5629     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5630     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5631       bool DoXform = true;
5632       SmallVector<SDNode*, 4> SetCCs;
5633       if (!N0.hasOneUse())
5634         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5635                                           SetCCs, TLI);
5636       if (DoXform) {
5637         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5638                                          LN0->getChain(), LN0->getBasePtr(),
5639                                          LN0->getMemoryVT(),
5640                                          LN0->getMemOperand());
5641         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5642         Mask = Mask.sext(VT.getSizeInBits());
5643         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5644                                   ExtLoad, DAG.getConstant(Mask, VT));
5645         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5646                                     SDLoc(N0.getOperand(0)),
5647                                     N0.getOperand(0).getValueType(), ExtLoad);
5648         CombineTo(N, And);
5649         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5650         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5651                         ISD::SIGN_EXTEND);
5652         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5653       }
5654     }
5655   }
5656
5657   if (N0.getOpcode() == ISD::SETCC) {
5658     EVT N0VT = N0.getOperand(0).getValueType();
5659     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5660     // Only do this before legalize for now.
5661     if (VT.isVector() && !LegalOperations &&
5662         TLI.getBooleanContents(N0VT) ==
5663             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5664       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5665       // of the same size as the compared operands. Only optimize sext(setcc())
5666       // if this is the case.
5667       EVT SVT = getSetCCResultType(N0VT);
5668
5669       // We know that the # elements of the results is the same as the
5670       // # elements of the compare (and the # elements of the compare result
5671       // for that matter).  Check to see that they are the same size.  If so,
5672       // we know that the element size of the sext'd result matches the
5673       // element size of the compare operands.
5674       if (VT.getSizeInBits() == SVT.getSizeInBits())
5675         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5676                              N0.getOperand(1),
5677                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5678
5679       // If the desired elements are smaller or larger than the source
5680       // elements we can use a matching integer vector type and then
5681       // truncate/sign extend
5682       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5683       if (SVT == MatchingVectorType) {
5684         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5685                                N0.getOperand(0), N0.getOperand(1),
5686                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5687         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5688       }
5689     }
5690
5691     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5692     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5693     SDValue NegOne =
5694       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5695     SDValue SCC =
5696       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5697                        NegOne, DAG.getConstant(0, VT),
5698                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5699     if (SCC.getNode()) return SCC;
5700
5701     if (!VT.isVector()) {
5702       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5703       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5704         SDLoc DL(N);
5705         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5706         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5707                                      N0.getOperand(0), N0.getOperand(1), CC);
5708         return DAG.getSelect(DL, VT, SetCC,
5709                              NegOne, DAG.getConstant(0, VT));
5710       }
5711     }
5712   }
5713
5714   // fold (sext x) -> (zext x) if the sign bit is known zero.
5715   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5716       DAG.SignBitIsZero(N0))
5717     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5718
5719   return SDValue();
5720 }
5721
5722 // isTruncateOf - If N is a truncate of some other value, return true, record
5723 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5724 // This function computes KnownZero to avoid a duplicated call to
5725 // computeKnownBits in the caller.
5726 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5727                          APInt &KnownZero) {
5728   APInt KnownOne;
5729   if (N->getOpcode() == ISD::TRUNCATE) {
5730     Op = N->getOperand(0);
5731     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5732     return true;
5733   }
5734
5735   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5736       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5737     return false;
5738
5739   SDValue Op0 = N->getOperand(0);
5740   SDValue Op1 = N->getOperand(1);
5741   assert(Op0.getValueType() == Op1.getValueType());
5742
5743   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5744   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5745   if (COp0 && COp0->isNullValue())
5746     Op = Op1;
5747   else if (COp1 && COp1->isNullValue())
5748     Op = Op0;
5749   else
5750     return false;
5751
5752   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5753
5754   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5755     return false;
5756
5757   return true;
5758 }
5759
5760 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5761   SDValue N0 = N->getOperand(0);
5762   EVT VT = N->getValueType(0);
5763
5764   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5765                                               LegalOperations))
5766     return SDValue(Res, 0);
5767
5768   // fold (zext (zext x)) -> (zext x)
5769   // fold (zext (aext x)) -> (zext x)
5770   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5771     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5772                        N0.getOperand(0));
5773
5774   // fold (zext (truncate x)) -> (zext x) or
5775   //      (zext (truncate x)) -> (truncate x)
5776   // This is valid when the truncated bits of x are already zero.
5777   // FIXME: We should extend this to work for vectors too.
5778   SDValue Op;
5779   APInt KnownZero;
5780   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5781     APInt TruncatedBits =
5782       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5783       APInt(Op.getValueSizeInBits(), 0) :
5784       APInt::getBitsSet(Op.getValueSizeInBits(),
5785                         N0.getValueSizeInBits(),
5786                         std::min(Op.getValueSizeInBits(),
5787                                  VT.getSizeInBits()));
5788     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5789       if (VT.bitsGT(Op.getValueType()))
5790         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5791       if (VT.bitsLT(Op.getValueType()))
5792         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5793
5794       return Op;
5795     }
5796   }
5797
5798   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5799   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5800   if (N0.getOpcode() == ISD::TRUNCATE) {
5801     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5802     if (NarrowLoad.getNode()) {
5803       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5804       if (NarrowLoad.getNode() != N0.getNode()) {
5805         CombineTo(N0.getNode(), NarrowLoad);
5806         // CombineTo deleted the truncate, if needed, but not what's under it.
5807         AddToWorklist(oye);
5808       }
5809       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5810     }
5811   }
5812
5813   // fold (zext (truncate x)) -> (and x, mask)
5814   if (N0.getOpcode() == ISD::TRUNCATE &&
5815       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5816
5817     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5818     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5819     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5820     if (NarrowLoad.getNode()) {
5821       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5822       if (NarrowLoad.getNode() != N0.getNode()) {
5823         CombineTo(N0.getNode(), NarrowLoad);
5824         // CombineTo deleted the truncate, if needed, but not what's under it.
5825         AddToWorklist(oye);
5826       }
5827       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5828     }
5829
5830     SDValue Op = N0.getOperand(0);
5831     if (Op.getValueType().bitsLT(VT)) {
5832       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5833       AddToWorklist(Op.getNode());
5834     } else if (Op.getValueType().bitsGT(VT)) {
5835       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5836       AddToWorklist(Op.getNode());
5837     }
5838     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5839                                   N0.getValueType().getScalarType());
5840   }
5841
5842   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5843   // if either of the casts is not free.
5844   if (N0.getOpcode() == ISD::AND &&
5845       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5846       N0.getOperand(1).getOpcode() == ISD::Constant &&
5847       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5848                            N0.getValueType()) ||
5849        !TLI.isZExtFree(N0.getValueType(), VT))) {
5850     SDValue X = N0.getOperand(0).getOperand(0);
5851     if (X.getValueType().bitsLT(VT)) {
5852       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5853     } else if (X.getValueType().bitsGT(VT)) {
5854       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5855     }
5856     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5857     Mask = Mask.zext(VT.getSizeInBits());
5858     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5859                        X, DAG.getConstant(Mask, VT));
5860   }
5861
5862   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5863   // Only generate vector extloads when 1) they're legal, and 2) they are
5864   // deemed desirable by the target.
5865   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5866       ((!LegalOperations && !VT.isVector() &&
5867         !cast<LoadSDNode>(N0)->isVolatile()) ||
5868        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
5869     bool DoXform = true;
5870     SmallVector<SDNode*, 4> SetCCs;
5871     if (!N0.hasOneUse())
5872       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5873     if (VT.isVector())
5874       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5875     if (DoXform) {
5876       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5877       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5878                                        LN0->getChain(),
5879                                        LN0->getBasePtr(), N0.getValueType(),
5880                                        LN0->getMemOperand());
5881       CombineTo(N, ExtLoad);
5882       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5883                                   N0.getValueType(), ExtLoad);
5884       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5885
5886       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5887                       ISD::ZERO_EXTEND);
5888       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5889     }
5890   }
5891
5892   // fold (zext (load x)) to multiple smaller zextloads.
5893   // Only on illegal but splittable vectors.
5894   if (SDValue ExtLoad = CombineExtLoad(N))
5895     return ExtLoad;
5896
5897   // fold (zext (and/or/xor (load x), cst)) ->
5898   //      (and/or/xor (zextload x), (zext cst))
5899   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5900        N0.getOpcode() == ISD::XOR) &&
5901       isa<LoadSDNode>(N0.getOperand(0)) &&
5902       N0.getOperand(1).getOpcode() == ISD::Constant &&
5903       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
5904       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5905     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5906     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5907       bool DoXform = true;
5908       SmallVector<SDNode*, 4> SetCCs;
5909       if (!N0.hasOneUse())
5910         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5911                                           SetCCs, TLI);
5912       if (DoXform) {
5913         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5914                                          LN0->getChain(), LN0->getBasePtr(),
5915                                          LN0->getMemoryVT(),
5916                                          LN0->getMemOperand());
5917         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5918         Mask = Mask.zext(VT.getSizeInBits());
5919         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5920                                   ExtLoad, DAG.getConstant(Mask, VT));
5921         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5922                                     SDLoc(N0.getOperand(0)),
5923                                     N0.getOperand(0).getValueType(), ExtLoad);
5924         CombineTo(N, And);
5925         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5926         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5927                         ISD::ZERO_EXTEND);
5928         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5929       }
5930     }
5931   }
5932
5933   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5934   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5935   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5936       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5937     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5938     EVT MemVT = LN0->getMemoryVT();
5939     if ((!LegalOperations && !LN0->isVolatile()) ||
5940         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
5941       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5942                                        LN0->getChain(),
5943                                        LN0->getBasePtr(), MemVT,
5944                                        LN0->getMemOperand());
5945       CombineTo(N, ExtLoad);
5946       CombineTo(N0.getNode(),
5947                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5948                             ExtLoad),
5949                 ExtLoad.getValue(1));
5950       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5951     }
5952   }
5953
5954   if (N0.getOpcode() == ISD::SETCC) {
5955     if (!LegalOperations && VT.isVector() &&
5956         N0.getValueType().getVectorElementType() == MVT::i1) {
5957       EVT N0VT = N0.getOperand(0).getValueType();
5958       if (getSetCCResultType(N0VT) == N0.getValueType())
5959         return SDValue();
5960
5961       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5962       // Only do this before legalize for now.
5963       EVT EltVT = VT.getVectorElementType();
5964       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5965                                     DAG.getConstant(1, EltVT));
5966       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5967         // We know that the # elements of the results is the same as the
5968         // # elements of the compare (and the # elements of the compare result
5969         // for that matter).  Check to see that they are the same size.  If so,
5970         // we know that the element size of the sext'd result matches the
5971         // element size of the compare operands.
5972         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5973                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5974                                          N0.getOperand(1),
5975                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5976                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5977                                        OneOps));
5978
5979       // If the desired elements are smaller or larger than the source
5980       // elements we can use a matching integer vector type and then
5981       // truncate/sign extend
5982       EVT MatchingElementType =
5983         EVT::getIntegerVT(*DAG.getContext(),
5984                           N0VT.getScalarType().getSizeInBits());
5985       EVT MatchingVectorType =
5986         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5987                          N0VT.getVectorNumElements());
5988       SDValue VsetCC =
5989         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5990                       N0.getOperand(1),
5991                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5992       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5993                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5994                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5995     }
5996
5997     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5998     SDValue SCC =
5999       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
6000                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
6001                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6002     if (SCC.getNode()) return SCC;
6003   }
6004
6005   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6006   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6007       isa<ConstantSDNode>(N0.getOperand(1)) &&
6008       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6009       N0.hasOneUse()) {
6010     SDValue ShAmt = N0.getOperand(1);
6011     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6012     if (N0.getOpcode() == ISD::SHL) {
6013       SDValue InnerZExt = N0.getOperand(0);
6014       // If the original shl may be shifting out bits, do not perform this
6015       // transformation.
6016       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6017         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6018       if (ShAmtVal > KnownZeroBits)
6019         return SDValue();
6020     }
6021
6022     SDLoc DL(N);
6023
6024     // Ensure that the shift amount is wide enough for the shifted value.
6025     if (VT.getSizeInBits() >= 256)
6026       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6027
6028     return DAG.getNode(N0.getOpcode(), DL, VT,
6029                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6030                        ShAmt);
6031   }
6032
6033   return SDValue();
6034 }
6035
6036 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6037   SDValue N0 = N->getOperand(0);
6038   EVT VT = N->getValueType(0);
6039
6040   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6041                                               LegalOperations))
6042     return SDValue(Res, 0);
6043
6044   // fold (aext (aext x)) -> (aext x)
6045   // fold (aext (zext x)) -> (zext x)
6046   // fold (aext (sext x)) -> (sext x)
6047   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6048       N0.getOpcode() == ISD::ZERO_EXTEND ||
6049       N0.getOpcode() == ISD::SIGN_EXTEND)
6050     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6051
6052   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6053   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6054   if (N0.getOpcode() == ISD::TRUNCATE) {
6055     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6056     if (NarrowLoad.getNode()) {
6057       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6058       if (NarrowLoad.getNode() != N0.getNode()) {
6059         CombineTo(N0.getNode(), NarrowLoad);
6060         // CombineTo deleted the truncate, if needed, but not what's under it.
6061         AddToWorklist(oye);
6062       }
6063       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6064     }
6065   }
6066
6067   // fold (aext (truncate x))
6068   if (N0.getOpcode() == ISD::TRUNCATE) {
6069     SDValue TruncOp = N0.getOperand(0);
6070     if (TruncOp.getValueType() == VT)
6071       return TruncOp; // x iff x size == zext size.
6072     if (TruncOp.getValueType().bitsGT(VT))
6073       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6074     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6075   }
6076
6077   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6078   // if the trunc is not free.
6079   if (N0.getOpcode() == ISD::AND &&
6080       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6081       N0.getOperand(1).getOpcode() == ISD::Constant &&
6082       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6083                           N0.getValueType())) {
6084     SDValue X = N0.getOperand(0).getOperand(0);
6085     if (X.getValueType().bitsLT(VT)) {
6086       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6087     } else if (X.getValueType().bitsGT(VT)) {
6088       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6089     }
6090     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6091     Mask = Mask.zext(VT.getSizeInBits());
6092     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6093                        X, DAG.getConstant(Mask, VT));
6094   }
6095
6096   // fold (aext (load x)) -> (aext (truncate (extload x)))
6097   // None of the supported targets knows how to perform load and any_ext
6098   // on vectors in one instruction.  We only perform this transformation on
6099   // scalars.
6100   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6101       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6102       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6103     bool DoXform = true;
6104     SmallVector<SDNode*, 4> SetCCs;
6105     if (!N0.hasOneUse())
6106       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6107     if (DoXform) {
6108       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6109       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6110                                        LN0->getChain(),
6111                                        LN0->getBasePtr(), N0.getValueType(),
6112                                        LN0->getMemOperand());
6113       CombineTo(N, ExtLoad);
6114       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6115                                   N0.getValueType(), ExtLoad);
6116       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6117       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6118                       ISD::ANY_EXTEND);
6119       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6120     }
6121   }
6122
6123   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6124   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6125   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6126   if (N0.getOpcode() == ISD::LOAD &&
6127       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6128       N0.hasOneUse()) {
6129     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6130     ISD::LoadExtType ExtType = LN0->getExtensionType();
6131     EVT MemVT = LN0->getMemoryVT();
6132     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6133       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6134                                        VT, LN0->getChain(), LN0->getBasePtr(),
6135                                        MemVT, LN0->getMemOperand());
6136       CombineTo(N, ExtLoad);
6137       CombineTo(N0.getNode(),
6138                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6139                             N0.getValueType(), ExtLoad),
6140                 ExtLoad.getValue(1));
6141       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6142     }
6143   }
6144
6145   if (N0.getOpcode() == ISD::SETCC) {
6146     // For vectors:
6147     // aext(setcc) -> vsetcc
6148     // aext(setcc) -> truncate(vsetcc)
6149     // aext(setcc) -> aext(vsetcc)
6150     // Only do this before legalize for now.
6151     if (VT.isVector() && !LegalOperations) {
6152       EVT N0VT = N0.getOperand(0).getValueType();
6153         // We know that the # elements of the results is the same as the
6154         // # elements of the compare (and the # elements of the compare result
6155         // for that matter).  Check to see that they are the same size.  If so,
6156         // we know that the element size of the sext'd result matches the
6157         // element size of the compare operands.
6158       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6159         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6160                              N0.getOperand(1),
6161                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6162       // If the desired elements are smaller or larger than the source
6163       // elements we can use a matching integer vector type and then
6164       // truncate/any extend
6165       else {
6166         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6167         SDValue VsetCC =
6168           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6169                         N0.getOperand(1),
6170                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6171         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6172       }
6173     }
6174
6175     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6176     SDValue SCC =
6177       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
6178                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
6179                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6180     if (SCC.getNode())
6181       return SCC;
6182   }
6183
6184   return SDValue();
6185 }
6186
6187 /// See if the specified operand can be simplified with the knowledge that only
6188 /// the bits specified by Mask are used.  If so, return the simpler operand,
6189 /// otherwise return a null SDValue.
6190 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6191   switch (V.getOpcode()) {
6192   default: break;
6193   case ISD::Constant: {
6194     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6195     assert(CV && "Const value should be ConstSDNode.");
6196     const APInt &CVal = CV->getAPIntValue();
6197     APInt NewVal = CVal & Mask;
6198     if (NewVal != CVal)
6199       return DAG.getConstant(NewVal, V.getValueType());
6200     break;
6201   }
6202   case ISD::OR:
6203   case ISD::XOR:
6204     // If the LHS or RHS don't contribute bits to the or, drop them.
6205     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6206       return V.getOperand(1);
6207     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6208       return V.getOperand(0);
6209     break;
6210   case ISD::SRL:
6211     // Only look at single-use SRLs.
6212     if (!V.getNode()->hasOneUse())
6213       break;
6214     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6215       // See if we can recursively simplify the LHS.
6216       unsigned Amt = RHSC->getZExtValue();
6217
6218       // Watch out for shift count overflow though.
6219       if (Amt >= Mask.getBitWidth()) break;
6220       APInt NewMask = Mask << Amt;
6221       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6222       if (SimplifyLHS.getNode())
6223         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6224                            SimplifyLHS, V.getOperand(1));
6225     }
6226   }
6227   return SDValue();
6228 }
6229
6230 /// If the result of a wider load is shifted to right of N  bits and then
6231 /// truncated to a narrower type and where N is a multiple of number of bits of
6232 /// the narrower type, transform it to a narrower load from address + N / num of
6233 /// bits of new type. If the result is to be extended, also fold the extension
6234 /// to form a extending load.
6235 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6236   unsigned Opc = N->getOpcode();
6237
6238   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6239   SDValue N0 = N->getOperand(0);
6240   EVT VT = N->getValueType(0);
6241   EVT ExtVT = VT;
6242
6243   // This transformation isn't valid for vector loads.
6244   if (VT.isVector())
6245     return SDValue();
6246
6247   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6248   // extended to VT.
6249   if (Opc == ISD::SIGN_EXTEND_INREG) {
6250     ExtType = ISD::SEXTLOAD;
6251     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6252   } else if (Opc == ISD::SRL) {
6253     // Another special-case: SRL is basically zero-extending a narrower value.
6254     ExtType = ISD::ZEXTLOAD;
6255     N0 = SDValue(N, 0);
6256     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6257     if (!N01) return SDValue();
6258     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6259                               VT.getSizeInBits() - N01->getZExtValue());
6260   }
6261   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6262     return SDValue();
6263
6264   unsigned EVTBits = ExtVT.getSizeInBits();
6265
6266   // Do not generate loads of non-round integer types since these can
6267   // be expensive (and would be wrong if the type is not byte sized).
6268   if (!ExtVT.isRound())
6269     return SDValue();
6270
6271   unsigned ShAmt = 0;
6272   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6273     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6274       ShAmt = N01->getZExtValue();
6275       // Is the shift amount a multiple of size of VT?
6276       if ((ShAmt & (EVTBits-1)) == 0) {
6277         N0 = N0.getOperand(0);
6278         // Is the load width a multiple of size of VT?
6279         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6280           return SDValue();
6281       }
6282
6283       // At this point, we must have a load or else we can't do the transform.
6284       if (!isa<LoadSDNode>(N0)) return SDValue();
6285
6286       // Because a SRL must be assumed to *need* to zero-extend the high bits
6287       // (as opposed to anyext the high bits), we can't combine the zextload
6288       // lowering of SRL and an sextload.
6289       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6290         return SDValue();
6291
6292       // If the shift amount is larger than the input type then we're not
6293       // accessing any of the loaded bytes.  If the load was a zextload/extload
6294       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6295       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6296         return SDValue();
6297     }
6298   }
6299
6300   // If the load is shifted left (and the result isn't shifted back right),
6301   // we can fold the truncate through the shift.
6302   unsigned ShLeftAmt = 0;
6303   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6304       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6305     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6306       ShLeftAmt = N01->getZExtValue();
6307       N0 = N0.getOperand(0);
6308     }
6309   }
6310
6311   // If we haven't found a load, we can't narrow it.  Don't transform one with
6312   // multiple uses, this would require adding a new load.
6313   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6314     return SDValue();
6315
6316   // Don't change the width of a volatile load.
6317   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6318   if (LN0->isVolatile())
6319     return SDValue();
6320
6321   // Verify that we are actually reducing a load width here.
6322   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6323     return SDValue();
6324
6325   // For the transform to be legal, the load must produce only two values
6326   // (the value loaded and the chain).  Don't transform a pre-increment
6327   // load, for example, which produces an extra value.  Otherwise the
6328   // transformation is not equivalent, and the downstream logic to replace
6329   // uses gets things wrong.
6330   if (LN0->getNumValues() > 2)
6331     return SDValue();
6332
6333   // If the load that we're shrinking is an extload and we're not just
6334   // discarding the extension we can't simply shrink the load. Bail.
6335   // TODO: It would be possible to merge the extensions in some cases.
6336   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6337       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6338     return SDValue();
6339
6340   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6341     return SDValue();
6342
6343   EVT PtrType = N0.getOperand(1).getValueType();
6344
6345   if (PtrType == MVT::Untyped || PtrType.isExtended())
6346     // It's not possible to generate a constant of extended or untyped type.
6347     return SDValue();
6348
6349   // For big endian targets, we need to adjust the offset to the pointer to
6350   // load the correct bytes.
6351   if (TLI.isBigEndian()) {
6352     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6353     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6354     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6355   }
6356
6357   uint64_t PtrOff = ShAmt / 8;
6358   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6359   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
6360                                PtrType, LN0->getBasePtr(),
6361                                DAG.getConstant(PtrOff, PtrType));
6362   AddToWorklist(NewPtr.getNode());
6363
6364   SDValue Load;
6365   if (ExtType == ISD::NON_EXTLOAD)
6366     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6367                         LN0->getPointerInfo().getWithOffset(PtrOff),
6368                         LN0->isVolatile(), LN0->isNonTemporal(),
6369                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6370   else
6371     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6372                           LN0->getPointerInfo().getWithOffset(PtrOff),
6373                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6374                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6375
6376   // Replace the old load's chain with the new load's chain.
6377   WorklistRemover DeadNodes(*this);
6378   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6379
6380   // Shift the result left, if we've swallowed a left shift.
6381   SDValue Result = Load;
6382   if (ShLeftAmt != 0) {
6383     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6384     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6385       ShImmTy = VT;
6386     // If the shift amount is as large as the result size (but, presumably,
6387     // no larger than the source) then the useful bits of the result are
6388     // zero; we can't simply return the shortened shift, because the result
6389     // of that operation is undefined.
6390     if (ShLeftAmt >= VT.getSizeInBits())
6391       Result = DAG.getConstant(0, VT);
6392     else
6393       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
6394                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
6395   }
6396
6397   // Return the new loaded value.
6398   return Result;
6399 }
6400
6401 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6402   SDValue N0 = N->getOperand(0);
6403   SDValue N1 = N->getOperand(1);
6404   EVT VT = N->getValueType(0);
6405   EVT EVT = cast<VTSDNode>(N1)->getVT();
6406   unsigned VTBits = VT.getScalarType().getSizeInBits();
6407   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6408
6409   // fold (sext_in_reg c1) -> c1
6410   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6411     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6412
6413   // If the input is already sign extended, just drop the extension.
6414   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6415     return N0;
6416
6417   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6418   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6419       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6420     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6421                        N0.getOperand(0), N1);
6422
6423   // fold (sext_in_reg (sext x)) -> (sext x)
6424   // fold (sext_in_reg (aext x)) -> (sext x)
6425   // if x is small enough.
6426   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6427     SDValue N00 = N0.getOperand(0);
6428     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6429         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6430       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6431   }
6432
6433   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6434   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6435     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6436
6437   // fold operands of sext_in_reg based on knowledge that the top bits are not
6438   // demanded.
6439   if (SimplifyDemandedBits(SDValue(N, 0)))
6440     return SDValue(N, 0);
6441
6442   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6443   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6444   SDValue NarrowLoad = ReduceLoadWidth(N);
6445   if (NarrowLoad.getNode())
6446     return NarrowLoad;
6447
6448   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6449   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6450   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6451   if (N0.getOpcode() == ISD::SRL) {
6452     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6453       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6454         // We can turn this into an SRA iff the input to the SRL is already sign
6455         // extended enough.
6456         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6457         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6458           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6459                              N0.getOperand(0), N0.getOperand(1));
6460       }
6461   }
6462
6463   // fold (sext_inreg (extload x)) -> (sextload x)
6464   if (ISD::isEXTLoad(N0.getNode()) &&
6465       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6466       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6467       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6468        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6469     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6470     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6471                                      LN0->getChain(),
6472                                      LN0->getBasePtr(), EVT,
6473                                      LN0->getMemOperand());
6474     CombineTo(N, ExtLoad);
6475     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6476     AddToWorklist(ExtLoad.getNode());
6477     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6478   }
6479   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6480   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6481       N0.hasOneUse() &&
6482       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6483       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6484        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6485     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6486     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6487                                      LN0->getChain(),
6488                                      LN0->getBasePtr(), EVT,
6489                                      LN0->getMemOperand());
6490     CombineTo(N, ExtLoad);
6491     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6492     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6493   }
6494
6495   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6496   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6497     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6498                                        N0.getOperand(1), false);
6499     if (BSwap.getNode())
6500       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6501                          BSwap, N1);
6502   }
6503
6504   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6505   // into a build_vector.
6506   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6507     SmallVector<SDValue, 8> Elts;
6508     unsigned NumElts = N0->getNumOperands();
6509     unsigned ShAmt = VTBits - EVTBits;
6510
6511     for (unsigned i = 0; i != NumElts; ++i) {
6512       SDValue Op = N0->getOperand(i);
6513       if (Op->getOpcode() == ISD::UNDEF) {
6514         Elts.push_back(Op);
6515         continue;
6516       }
6517
6518       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6519       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6520       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6521                                      Op.getValueType()));
6522     }
6523
6524     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6525   }
6526
6527   return SDValue();
6528 }
6529
6530 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6531   SDValue N0 = N->getOperand(0);
6532   EVT VT = N->getValueType(0);
6533   bool isLE = TLI.isLittleEndian();
6534
6535   // noop truncate
6536   if (N0.getValueType() == N->getValueType(0))
6537     return N0;
6538   // fold (truncate c1) -> c1
6539   if (isa<ConstantSDNode>(N0))
6540     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6541   // fold (truncate (truncate x)) -> (truncate x)
6542   if (N0.getOpcode() == ISD::TRUNCATE)
6543     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6544   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6545   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6546       N0.getOpcode() == ISD::SIGN_EXTEND ||
6547       N0.getOpcode() == ISD::ANY_EXTEND) {
6548     if (N0.getOperand(0).getValueType().bitsLT(VT))
6549       // if the source is smaller than the dest, we still need an extend
6550       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6551                          N0.getOperand(0));
6552     if (N0.getOperand(0).getValueType().bitsGT(VT))
6553       // if the source is larger than the dest, than we just need the truncate
6554       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6555     // if the source and dest are the same type, we can drop both the extend
6556     // and the truncate.
6557     return N0.getOperand(0);
6558   }
6559
6560   // Fold extract-and-trunc into a narrow extract. For example:
6561   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6562   //   i32 y = TRUNCATE(i64 x)
6563   //        -- becomes --
6564   //   v16i8 b = BITCAST (v2i64 val)
6565   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6566   //
6567   // Note: We only run this optimization after type legalization (which often
6568   // creates this pattern) and before operation legalization after which
6569   // we need to be more careful about the vector instructions that we generate.
6570   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6571       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6572
6573     EVT VecTy = N0.getOperand(0).getValueType();
6574     EVT ExTy = N0.getValueType();
6575     EVT TrTy = N->getValueType(0);
6576
6577     unsigned NumElem = VecTy.getVectorNumElements();
6578     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6579
6580     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6581     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6582
6583     SDValue EltNo = N0->getOperand(1);
6584     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6585       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6586       EVT IndexTy = TLI.getVectorIdxTy();
6587       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6588
6589       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6590                               NVT, N0.getOperand(0));
6591
6592       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6593                          SDLoc(N), TrTy, V,
6594                          DAG.getConstant(Index, IndexTy));
6595     }
6596   }
6597
6598   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6599   if (N0.getOpcode() == ISD::SELECT) {
6600     EVT SrcVT = N0.getValueType();
6601     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6602         TLI.isTruncateFree(SrcVT, VT)) {
6603       SDLoc SL(N0);
6604       SDValue Cond = N0.getOperand(0);
6605       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6606       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6607       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6608     }
6609   }
6610
6611   // Fold a series of buildvector, bitcast, and truncate if possible.
6612   // For example fold
6613   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6614   //   (2xi32 (buildvector x, y)).
6615   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6616       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6617       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6618       N0.getOperand(0).hasOneUse()) {
6619
6620     SDValue BuildVect = N0.getOperand(0);
6621     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6622     EVT TruncVecEltTy = VT.getVectorElementType();
6623
6624     // Check that the element types match.
6625     if (BuildVectEltTy == TruncVecEltTy) {
6626       // Now we only need to compute the offset of the truncated elements.
6627       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6628       unsigned TruncVecNumElts = VT.getVectorNumElements();
6629       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6630
6631       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6632              "Invalid number of elements");
6633
6634       SmallVector<SDValue, 8> Opnds;
6635       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6636         Opnds.push_back(BuildVect.getOperand(i));
6637
6638       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6639     }
6640   }
6641
6642   // See if we can simplify the input to this truncate through knowledge that
6643   // only the low bits are being used.
6644   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6645   // Currently we only perform this optimization on scalars because vectors
6646   // may have different active low bits.
6647   if (!VT.isVector()) {
6648     SDValue Shorter =
6649       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6650                                                VT.getSizeInBits()));
6651     if (Shorter.getNode())
6652       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6653   }
6654   // fold (truncate (load x)) -> (smaller load x)
6655   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6656   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6657     SDValue Reduced = ReduceLoadWidth(N);
6658     if (Reduced.getNode())
6659       return Reduced;
6660     // Handle the case where the load remains an extending load even
6661     // after truncation.
6662     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6663       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6664       if (!LN0->isVolatile() &&
6665           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6666         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6667                                          VT, LN0->getChain(), LN0->getBasePtr(),
6668                                          LN0->getMemoryVT(),
6669                                          LN0->getMemOperand());
6670         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6671         return NewLoad;
6672       }
6673     }
6674   }
6675   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6676   // where ... are all 'undef'.
6677   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6678     SmallVector<EVT, 8> VTs;
6679     SDValue V;
6680     unsigned Idx = 0;
6681     unsigned NumDefs = 0;
6682
6683     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6684       SDValue X = N0.getOperand(i);
6685       if (X.getOpcode() != ISD::UNDEF) {
6686         V = X;
6687         Idx = i;
6688         NumDefs++;
6689       }
6690       // Stop if more than one members are non-undef.
6691       if (NumDefs > 1)
6692         break;
6693       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6694                                      VT.getVectorElementType(),
6695                                      X.getValueType().getVectorNumElements()));
6696     }
6697
6698     if (NumDefs == 0)
6699       return DAG.getUNDEF(VT);
6700
6701     if (NumDefs == 1) {
6702       assert(V.getNode() && "The single defined operand is empty!");
6703       SmallVector<SDValue, 8> Opnds;
6704       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6705         if (i != Idx) {
6706           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6707           continue;
6708         }
6709         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6710         AddToWorklist(NV.getNode());
6711         Opnds.push_back(NV);
6712       }
6713       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6714     }
6715   }
6716
6717   // Simplify the operands using demanded-bits information.
6718   if (!VT.isVector() &&
6719       SimplifyDemandedBits(SDValue(N, 0)))
6720     return SDValue(N, 0);
6721
6722   return SDValue();
6723 }
6724
6725 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6726   SDValue Elt = N->getOperand(i);
6727   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6728     return Elt.getNode();
6729   return Elt.getOperand(Elt.getResNo()).getNode();
6730 }
6731
6732 /// build_pair (load, load) -> load
6733 /// if load locations are consecutive.
6734 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6735   assert(N->getOpcode() == ISD::BUILD_PAIR);
6736
6737   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6738   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6739   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6740       LD1->getAddressSpace() != LD2->getAddressSpace())
6741     return SDValue();
6742   EVT LD1VT = LD1->getValueType(0);
6743
6744   if (ISD::isNON_EXTLoad(LD2) &&
6745       LD2->hasOneUse() &&
6746       // If both are volatile this would reduce the number of volatile loads.
6747       // If one is volatile it might be ok, but play conservative and bail out.
6748       !LD1->isVolatile() &&
6749       !LD2->isVolatile() &&
6750       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6751     unsigned Align = LD1->getAlignment();
6752     unsigned NewAlign = TLI.getDataLayout()->
6753       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6754
6755     if (NewAlign <= Align &&
6756         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6757       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6758                          LD1->getBasePtr(), LD1->getPointerInfo(),
6759                          false, false, false, Align);
6760   }
6761
6762   return SDValue();
6763 }
6764
6765 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6766   SDValue N0 = N->getOperand(0);
6767   EVT VT = N->getValueType(0);
6768
6769   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6770   // Only do this before legalize, since afterward the target may be depending
6771   // on the bitconvert.
6772   // First check to see if this is all constant.
6773   if (!LegalTypes &&
6774       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6775       VT.isVector()) {
6776     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6777
6778     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6779     assert(!DestEltVT.isVector() &&
6780            "Element type of vector ValueType must not be vector!");
6781     if (isSimple)
6782       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6783   }
6784
6785   // If the input is a constant, let getNode fold it.
6786   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6787     // If we can't allow illegal operations, we need to check that this is just
6788     // a fp -> int or int -> conversion and that the resulting operation will
6789     // be legal.
6790     if (!LegalOperations ||
6791         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
6792          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
6793         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
6794          TLI.isOperationLegal(ISD::Constant, VT)))
6795       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6796   }
6797
6798   // (conv (conv x, t1), t2) -> (conv x, t2)
6799   if (N0.getOpcode() == ISD::BITCAST)
6800     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6801                        N0.getOperand(0));
6802
6803   // fold (conv (load x)) -> (load (conv*)x)
6804   // If the resultant load doesn't need a higher alignment than the original!
6805   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6806       // Do not change the width of a volatile load.
6807       !cast<LoadSDNode>(N0)->isVolatile() &&
6808       // Do not remove the cast if the types differ in endian layout.
6809       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6810       TLI.hasBigEndianPartOrdering(VT) &&
6811       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6812       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6813     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6814     unsigned Align = TLI.getDataLayout()->
6815       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6816     unsigned OrigAlign = LN0->getAlignment();
6817
6818     if (Align <= OrigAlign) {
6819       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6820                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6821                                  LN0->isVolatile(), LN0->isNonTemporal(),
6822                                  LN0->isInvariant(), OrigAlign,
6823                                  LN0->getAAInfo());
6824       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6825       return Load;
6826     }
6827   }
6828
6829   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6830   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6831   // This often reduces constant pool loads.
6832   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6833        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6834       N0.getNode()->hasOneUse() && VT.isInteger() &&
6835       !VT.isVector() && !N0.getValueType().isVector()) {
6836     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6837                                   N0.getOperand(0));
6838     AddToWorklist(NewConv.getNode());
6839
6840     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6841     if (N0.getOpcode() == ISD::FNEG)
6842       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6843                          NewConv, DAG.getConstant(SignBit, VT));
6844     assert(N0.getOpcode() == ISD::FABS);
6845     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6846                        NewConv, DAG.getConstant(~SignBit, VT));
6847   }
6848
6849   // fold (bitconvert (fcopysign cst, x)) ->
6850   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6851   // Note that we don't handle (copysign x, cst) because this can always be
6852   // folded to an fneg or fabs.
6853   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6854       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6855       VT.isInteger() && !VT.isVector()) {
6856     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6857     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6858     if (isTypeLegal(IntXVT)) {
6859       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6860                               IntXVT, N0.getOperand(1));
6861       AddToWorklist(X.getNode());
6862
6863       // If X has a different width than the result/lhs, sext it or truncate it.
6864       unsigned VTWidth = VT.getSizeInBits();
6865       if (OrigXWidth < VTWidth) {
6866         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6867         AddToWorklist(X.getNode());
6868       } else if (OrigXWidth > VTWidth) {
6869         // To get the sign bit in the right place, we have to shift it right
6870         // before truncating.
6871         X = DAG.getNode(ISD::SRL, SDLoc(X),
6872                         X.getValueType(), X,
6873                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6874         AddToWorklist(X.getNode());
6875         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6876         AddToWorklist(X.getNode());
6877       }
6878
6879       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6880       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6881                       X, DAG.getConstant(SignBit, VT));
6882       AddToWorklist(X.getNode());
6883
6884       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6885                                 VT, N0.getOperand(0));
6886       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6887                         Cst, DAG.getConstant(~SignBit, VT));
6888       AddToWorklist(Cst.getNode());
6889
6890       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6891     }
6892   }
6893
6894   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6895   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6896     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6897     if (CombineLD.getNode())
6898       return CombineLD;
6899   }
6900
6901   return SDValue();
6902 }
6903
6904 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6905   EVT VT = N->getValueType(0);
6906   return CombineConsecutiveLoads(N, VT);
6907 }
6908
6909 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6910 /// operands. DstEltVT indicates the destination element value type.
6911 SDValue DAGCombiner::
6912 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6913   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6914
6915   // If this is already the right type, we're done.
6916   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6917
6918   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6919   unsigned DstBitSize = DstEltVT.getSizeInBits();
6920
6921   // If this is a conversion of N elements of one type to N elements of another
6922   // type, convert each element.  This handles FP<->INT cases.
6923   if (SrcBitSize == DstBitSize) {
6924     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6925                               BV->getValueType(0).getVectorNumElements());
6926
6927     // Due to the FP element handling below calling this routine recursively,
6928     // we can end up with a scalar-to-vector node here.
6929     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6930       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6931                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6932                                      DstEltVT, BV->getOperand(0)));
6933
6934     SmallVector<SDValue, 8> Ops;
6935     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6936       SDValue Op = BV->getOperand(i);
6937       // If the vector element type is not legal, the BUILD_VECTOR operands
6938       // are promoted and implicitly truncated.  Make that explicit here.
6939       if (Op.getValueType() != SrcEltVT)
6940         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6941       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6942                                 DstEltVT, Op));
6943       AddToWorklist(Ops.back().getNode());
6944     }
6945     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6946   }
6947
6948   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6949   // handle annoying details of growing/shrinking FP values, we convert them to
6950   // int first.
6951   if (SrcEltVT.isFloatingPoint()) {
6952     // Convert the input float vector to a int vector where the elements are the
6953     // same sizes.
6954     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6955     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6956     SrcEltVT = IntVT;
6957   }
6958
6959   // Now we know the input is an integer vector.  If the output is a FP type,
6960   // convert to integer first, then to FP of the right size.
6961   if (DstEltVT.isFloatingPoint()) {
6962     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6963     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6964
6965     // Next, convert to FP elements of the same size.
6966     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6967   }
6968
6969   // Okay, we know the src/dst types are both integers of differing types.
6970   // Handling growing first.
6971   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6972   if (SrcBitSize < DstBitSize) {
6973     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6974
6975     SmallVector<SDValue, 8> Ops;
6976     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6977          i += NumInputsPerOutput) {
6978       bool isLE = TLI.isLittleEndian();
6979       APInt NewBits = APInt(DstBitSize, 0);
6980       bool EltIsUndef = true;
6981       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6982         // Shift the previously computed bits over.
6983         NewBits <<= SrcBitSize;
6984         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6985         if (Op.getOpcode() == ISD::UNDEF) continue;
6986         EltIsUndef = false;
6987
6988         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6989                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6990       }
6991
6992       if (EltIsUndef)
6993         Ops.push_back(DAG.getUNDEF(DstEltVT));
6994       else
6995         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6996     }
6997
6998     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6999     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7000   }
7001
7002   // Finally, this must be the case where we are shrinking elements: each input
7003   // turns into multiple outputs.
7004   bool isS2V = ISD::isScalarToVector(BV);
7005   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7006   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7007                             NumOutputsPerInput*BV->getNumOperands());
7008   SmallVector<SDValue, 8> Ops;
7009
7010   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7011     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7012       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7013       continue;
7014     }
7015
7016     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7017                   getAPIntValue().zextOrTrunc(SrcBitSize);
7018
7019     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7020       APInt ThisVal = OpVal.trunc(DstBitSize);
7021       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
7022       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
7023         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
7024         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7025                            Ops[0]);
7026       OpVal = OpVal.lshr(DstBitSize);
7027     }
7028
7029     // For big endian targets, swap the order of the pieces of each element.
7030     if (TLI.isBigEndian())
7031       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7032   }
7033
7034   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7035 }
7036
7037 // Attempt different variants of (fadd (fmul a, b), c) -> fma or fmad
7038 static SDValue performFaddFmulCombines(unsigned FusedOpcode,
7039                                        bool Aggressive,
7040                                        SDNode *N,
7041                                        const TargetLowering &TLI,
7042                                        SelectionDAG &DAG) {
7043   SDValue N0 = N->getOperand(0);
7044   SDValue N1 = N->getOperand(1);
7045   EVT VT = N->getValueType(0);
7046
7047   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7048   if (N0.getOpcode() == ISD::FMUL &&
7049       (Aggressive || N0->hasOneUse())) {
7050     return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7051                        N0.getOperand(0), N0.getOperand(1), N1);
7052   }
7053
7054   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7055   // Note: Commutes FADD operands.
7056   if (N1.getOpcode() == ISD::FMUL &&
7057       (Aggressive || N1->hasOneUse())) {
7058     return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7059                        N1.getOperand(0), N1.getOperand(1), N0);
7060   }
7061
7062   // More folding opportunities when target permits.
7063   if (Aggressive) {
7064     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7065     if (N0.getOpcode() == ISD::FMA &&
7066         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7067       return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7068                          N0.getOperand(0), N0.getOperand(1),
7069                          DAG.getNode(FusedOpcode, SDLoc(N), VT,
7070                                      N0.getOperand(2).getOperand(0),
7071                                      N0.getOperand(2).getOperand(1),
7072                                      N1));
7073     }
7074
7075     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7076     if (N1->getOpcode() == ISD::FMA &&
7077         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7078       return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7079                          N1.getOperand(0), N1.getOperand(1),
7080                          DAG.getNode(FusedOpcode, SDLoc(N), VT,
7081                                      N1.getOperand(2).getOperand(0),
7082                                      N1.getOperand(2).getOperand(1),
7083                                      N0));
7084     }
7085   }
7086
7087   return SDValue();
7088 }
7089
7090 static SDValue performFsubFmulCombines(unsigned FusedOpcode,
7091                                        bool Aggressive,
7092                                        SDNode *N,
7093                                        const TargetLowering &TLI,
7094                                        SelectionDAG &DAG) {
7095   SDValue N0 = N->getOperand(0);
7096   SDValue N1 = N->getOperand(1);
7097   EVT VT = N->getValueType(0);
7098
7099   SDLoc SL(N);
7100
7101   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7102   if (N0.getOpcode() == ISD::FMUL &&
7103       (Aggressive || N0->hasOneUse())) {
7104     return DAG.getNode(FusedOpcode, SL, VT,
7105                        N0.getOperand(0), N0.getOperand(1),
7106                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7107   }
7108
7109   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7110   // Note: Commutes FSUB operands.
7111   if (N1.getOpcode() == ISD::FMUL &&
7112       (Aggressive || N1->hasOneUse()))
7113     return DAG.getNode(FusedOpcode, SL, VT,
7114                        DAG.getNode(ISD::FNEG, SL, VT,
7115                                    N1.getOperand(0)),
7116                        N1.getOperand(1), N0);
7117
7118   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7119   if (N0.getOpcode() == ISD::FNEG &&
7120       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7121       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7122     SDValue N00 = N0.getOperand(0).getOperand(0);
7123     SDValue N01 = N0.getOperand(0).getOperand(1);
7124     return DAG.getNode(FusedOpcode, SL, VT,
7125                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7126                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7127   }
7128
7129   // More folding opportunities when target permits.
7130   if (Aggressive) {
7131     // fold (fsub (fma x, y, (fmul u, v)), z)
7132     //   -> (fma x, y (fma u, v, (fneg z)))
7133     if (N0.getOpcode() == FusedOpcode &&
7134         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7135       return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7136                          N0.getOperand(0), N0.getOperand(1),
7137                          DAG.getNode(FusedOpcode, SDLoc(N), VT,
7138                                      N0.getOperand(2).getOperand(0),
7139                                      N0.getOperand(2).getOperand(1),
7140                                      DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7141                                                  N1)));
7142     }
7143
7144     // fold (fsub x, (fma y, z, (fmul u, v)))
7145     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7146     if (N1.getOpcode() == FusedOpcode &&
7147         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7148       SDValue N20 = N1.getOperand(2).getOperand(0);
7149       SDValue N21 = N1.getOperand(2).getOperand(1);
7150       return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7151                          DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7152                                      N1.getOperand(0)),
7153                          N1.getOperand(1),
7154                          DAG.getNode(FusedOpcode, SDLoc(N), VT,
7155                                      DAG.getNode(ISD::FNEG, SDLoc(N),  VT,
7156                                                  N20),
7157                                      N21, N0));
7158     }
7159   }
7160
7161   return SDValue();
7162 }
7163
7164 SDValue DAGCombiner::visitFADD(SDNode *N) {
7165   SDValue N0 = N->getOperand(0);
7166   SDValue N1 = N->getOperand(1);
7167   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7168   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7169   EVT VT = N->getValueType(0);
7170   const TargetOptions &Options = DAG.getTarget().Options;
7171
7172   // fold vector ops
7173   if (VT.isVector()) {
7174     SDValue FoldedVOp = SimplifyVBinOp(N);
7175     if (FoldedVOp.getNode()) return FoldedVOp;
7176   }
7177
7178   // fold (fadd c1, c2) -> c1 + c2
7179   if (N0CFP && N1CFP)
7180     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
7181
7182   // canonicalize constant to RHS
7183   if (N0CFP && !N1CFP)
7184     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
7185
7186   // fold (fadd A, (fneg B)) -> (fsub A, B)
7187   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7188       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7189     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
7190                        GetNegatedExpression(N1, DAG, LegalOperations));
7191
7192   // fold (fadd (fneg A), B) -> (fsub B, A)
7193   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7194       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7195     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
7196                        GetNegatedExpression(N0, DAG, LegalOperations));
7197
7198   // If 'unsafe math' is enabled, fold lots of things.
7199   if (Options.UnsafeFPMath) {
7200     // No FP constant should be created after legalization as Instruction
7201     // Selection pass has a hard time dealing with FP constants.
7202     bool AllowNewConst = (Level < AfterLegalizeDAG);
7203
7204     // fold (fadd A, 0) -> A
7205     if (N1CFP && N1CFP->getValueAPF().isZero())
7206       return N0;
7207
7208     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7209     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7210         isa<ConstantFPSDNode>(N0.getOperand(1)))
7211       return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
7212                          DAG.getNode(ISD::FADD, SDLoc(N), VT,
7213                                      N0.getOperand(1), N1));
7214
7215     // If allowed, fold (fadd (fneg x), x) -> 0.0
7216     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7217       return DAG.getConstantFP(0.0, VT);
7218
7219     // If allowed, fold (fadd x, (fneg x)) -> 0.0
7220     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7221       return DAG.getConstantFP(0.0, VT);
7222
7223     // We can fold chains of FADD's of the same value into multiplications.
7224     // This transform is not safe in general because we are reducing the number
7225     // of rounding steps.
7226     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7227       if (N0.getOpcode() == ISD::FMUL) {
7228         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7229         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7230
7231         // (fadd (fmul x, c), x) -> (fmul x, c+1)
7232         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7233           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7234                                        SDValue(CFP01, 0),
7235                                        DAG.getConstantFP(1.0, VT));
7236           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
7237         }
7238
7239         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7240         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7241             N1.getOperand(0) == N1.getOperand(1) &&
7242             N0.getOperand(0) == N1.getOperand(0)) {
7243           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7244                                        SDValue(CFP01, 0),
7245                                        DAG.getConstantFP(2.0, VT));
7246           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7247                              N0.getOperand(0), NewCFP);
7248         }
7249       }
7250
7251       if (N1.getOpcode() == ISD::FMUL) {
7252         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7253         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7254
7255         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7256         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7257           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7258                                        SDValue(CFP11, 0),
7259                                        DAG.getConstantFP(1.0, VT));
7260           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
7261         }
7262
7263         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7264         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7265             N0.getOperand(0) == N0.getOperand(1) &&
7266             N1.getOperand(0) == N0.getOperand(0)) {
7267           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7268                                        SDValue(CFP11, 0),
7269                                        DAG.getConstantFP(2.0, VT));
7270           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
7271         }
7272       }
7273
7274       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7275         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7276         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7277         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7278             (N0.getOperand(0) == N1))
7279           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7280                              N1, DAG.getConstantFP(3.0, VT));
7281       }
7282
7283       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7284         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7285         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7286         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7287             N1.getOperand(0) == N0)
7288           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7289                              N0, DAG.getConstantFP(3.0, VT));
7290       }
7291
7292       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7293       if (AllowNewConst &&
7294           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7295           N0.getOperand(0) == N0.getOperand(1) &&
7296           N1.getOperand(0) == N1.getOperand(1) &&
7297           N0.getOperand(0) == N1.getOperand(0))
7298         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7299                            N0.getOperand(0), DAG.getConstantFP(4.0, VT));
7300     }
7301   } // enable-unsafe-fp-math
7302
7303   if (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)) {
7304     // Assume if there is an fmad instruction that it should be aggressively
7305     // used.
7306     if (SDValue Fused = performFaddFmulCombines(ISD::FMAD, true, N, TLI, DAG))
7307       return Fused;
7308   }
7309
7310   // FADD -> FMA combines:
7311   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
7312       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7313       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
7314
7315     if (!TLI.isOperationLegal(ISD::FMAD, VT)) {
7316       // Don't form FMA if we are preferring FMAD.
7317       if (SDValue Fused
7318           = performFaddFmulCombines(ISD::FMA,
7319                                     TLI.enableAggressiveFMAFusion(VT),
7320                                     N, TLI, DAG)) {
7321         return Fused;
7322       }
7323     }
7324
7325     // When FP_EXTEND nodes are free on the target, and there is an opportunity
7326     // to combine into FMA, arrange such nodes accordingly.
7327     if (TLI.isFPExtFree(VT)) {
7328
7329       // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7330       if (N0.getOpcode() == ISD::FP_EXTEND) {
7331         SDValue N00 = N0.getOperand(0);
7332         if (N00.getOpcode() == ISD::FMUL)
7333           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7334                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7335                                          N00.getOperand(0)),
7336                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7337                                          N00.getOperand(1)), N1);
7338       }
7339
7340       // fold (fadd x, (fpext (fmul y, z)), z) -> (fma (fpext y), (fpext z), x)
7341       // Note: Commutes FADD operands.
7342       if (N1.getOpcode() == ISD::FP_EXTEND) {
7343         SDValue N10 = N1.getOperand(0);
7344         if (N10.getOpcode() == ISD::FMUL)
7345           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7346                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7347                                          N10.getOperand(0)),
7348                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7349                                          N10.getOperand(1)), N0);
7350       }
7351     }
7352   }
7353
7354   return SDValue();
7355 }
7356
7357 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7358   SDValue N0 = N->getOperand(0);
7359   SDValue N1 = N->getOperand(1);
7360   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7361   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7362   EVT VT = N->getValueType(0);
7363   SDLoc dl(N);
7364   const TargetOptions &Options = DAG.getTarget().Options;
7365
7366   // fold vector ops
7367   if (VT.isVector()) {
7368     SDValue FoldedVOp = SimplifyVBinOp(N);
7369     if (FoldedVOp.getNode()) return FoldedVOp;
7370   }
7371
7372   // fold (fsub c1, c2) -> c1-c2
7373   if (N0CFP && N1CFP)
7374     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
7375
7376   // fold (fsub A, (fneg B)) -> (fadd A, B)
7377   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7378     return DAG.getNode(ISD::FADD, dl, VT, N0,
7379                        GetNegatedExpression(N1, DAG, LegalOperations));
7380
7381   // If 'unsafe math' is enabled, fold lots of things.
7382   if (Options.UnsafeFPMath) {
7383     // (fsub A, 0) -> A
7384     if (N1CFP && N1CFP->getValueAPF().isZero())
7385       return N0;
7386
7387     // (fsub 0, B) -> -B
7388     if (N0CFP && N0CFP->getValueAPF().isZero()) {
7389       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7390         return GetNegatedExpression(N1, DAG, LegalOperations);
7391       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7392         return DAG.getNode(ISD::FNEG, dl, VT, N1);
7393     }
7394
7395     // (fsub x, x) -> 0.0
7396     if (N0 == N1)
7397       return DAG.getConstantFP(0.0f, VT);
7398
7399     // (fsub x, (fadd x, y)) -> (fneg y)
7400     // (fsub x, (fadd y, x)) -> (fneg y)
7401     if (N1.getOpcode() == ISD::FADD) {
7402       SDValue N10 = N1->getOperand(0);
7403       SDValue N11 = N1->getOperand(1);
7404
7405       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7406         return GetNegatedExpression(N11, DAG, LegalOperations);
7407
7408       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7409         return GetNegatedExpression(N10, DAG, LegalOperations);
7410     }
7411   }
7412
7413   if (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)) {
7414     // Assume if there is an fmad instruction that it should be aggressively
7415     // used.
7416     if (SDValue Fused = performFsubFmulCombines(ISD::FMAD, true, N, TLI, DAG))
7417       return Fused;
7418   }
7419
7420   // FSUB -> FMA combines:
7421   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
7422       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7423       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
7424
7425     if (!TLI.isOperationLegal(ISD::FMAD, VT)) {
7426       // Don't form FMA if we are preferring FMAD.
7427
7428       if (SDValue Fused
7429           = performFsubFmulCombines(ISD::FMA,
7430                                     TLI.enableAggressiveFMAFusion(VT),
7431                                     N, TLI, DAG)) {
7432         return Fused;
7433       }
7434     }
7435
7436     // When FP_EXTEND nodes are free on the target, and there is an opportunity
7437     // to combine into FMA, arrange such nodes accordingly.
7438     if (TLI.isFPExtFree(VT)) {
7439       // fold (fsub (fpext (fmul x, y)), z)
7440       //   -> (fma (fpext x), (fpext y), (fneg z))
7441       if (N0.getOpcode() == ISD::FP_EXTEND) {
7442         SDValue N00 = N0.getOperand(0);
7443         if (N00.getOpcode() == ISD::FMUL)
7444           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7445                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7446                                          N00.getOperand(0)),
7447                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7448                                          N00.getOperand(1)),
7449                              DAG.getNode(ISD::FNEG, SDLoc(N), VT, N1));
7450       }
7451
7452       // fold (fsub x, (fpext (fmul y, z)))
7453       //   -> (fma (fneg (fpext y)), (fpext z), x)
7454       // Note: Commutes FSUB operands.
7455       if (N1.getOpcode() == ISD::FP_EXTEND) {
7456         SDValue N10 = N1.getOperand(0);
7457         if (N10.getOpcode() == ISD::FMUL)
7458           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7459                              DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7460                                          DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7461                                                      VT, N10.getOperand(0))),
7462                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7463                                          N10.getOperand(1)),
7464                              N0);
7465       }
7466
7467       // fold (fsub (fpext (fneg (fmul, x, y))), z)
7468       //   -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7469       if (N0.getOpcode() == ISD::FP_EXTEND) {
7470         SDValue N00 = N0.getOperand(0);
7471         if (N00.getOpcode() == ISD::FNEG) {
7472           SDValue N000 = N00.getOperand(0);
7473           if (N000.getOpcode() == ISD::FMUL) {
7474             return DAG.getNode(ISD::FMA, dl, VT,
7475                                DAG.getNode(ISD::FNEG, dl, VT,
7476                                            DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7477                                                        VT, N000.getOperand(0))),
7478                                DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7479                                            N000.getOperand(1)),
7480                                DAG.getNode(ISD::FNEG, dl, VT, N1));
7481           }
7482         }
7483       }
7484
7485       // fold (fsub (fneg (fpext (fmul, x, y))), z)
7486       //   -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7487       if (N0.getOpcode() == ISD::FNEG) {
7488         SDValue N00 = N0.getOperand(0);
7489         if (N00.getOpcode() == ISD::FP_EXTEND) {
7490           SDValue N000 = N00.getOperand(0);
7491           if (N000.getOpcode() == ISD::FMUL) {
7492             return DAG.getNode(ISD::FMA, dl, VT,
7493                                DAG.getNode(ISD::FNEG, dl, VT,
7494                                            DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7495                                            VT, N000.getOperand(0))),
7496                                DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7497                                            N000.getOperand(1)),
7498                                DAG.getNode(ISD::FNEG, dl, VT, N1));
7499           }
7500         }
7501       }
7502     }
7503   }
7504
7505   return SDValue();
7506 }
7507
7508 SDValue DAGCombiner::visitFMUL(SDNode *N) {
7509   SDValue N0 = N->getOperand(0);
7510   SDValue N1 = N->getOperand(1);
7511   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7512   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7513   EVT VT = N->getValueType(0);
7514   const TargetOptions &Options = DAG.getTarget().Options;
7515
7516   // fold vector ops
7517   if (VT.isVector()) {
7518     // This just handles C1 * C2 for vectors. Other vector folds are below.
7519     SDValue FoldedVOp = SimplifyVBinOp(N);
7520     if (FoldedVOp.getNode())
7521       return FoldedVOp;
7522     // Canonicalize vector constant to RHS.
7523     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
7524         N1.getOpcode() != ISD::BUILD_VECTOR)
7525       if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
7526         if (BV0->isConstant())
7527           return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
7528   }
7529
7530   // fold (fmul c1, c2) -> c1*c2
7531   if (N0CFP && N1CFP)
7532     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
7533
7534   // canonicalize constant to RHS
7535   if (N0CFP && !N1CFP)
7536     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
7537
7538   // fold (fmul A, 1.0) -> A
7539   if (N1CFP && N1CFP->isExactlyValue(1.0))
7540     return N0;
7541
7542   if (Options.UnsafeFPMath) {
7543     // fold (fmul A, 0) -> 0
7544     if (N1CFP && N1CFP->getValueAPF().isZero())
7545       return N1;
7546
7547     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7548     if (N0.getOpcode() == ISD::FMUL) {
7549       // Fold scalars or any vector constants (not just splats).
7550       // This fold is done in general by InstCombine, but extra fmul insts
7551       // may have been generated during lowering.
7552       SDValue N00 = N0.getOperand(0);
7553       SDValue N01 = N0.getOperand(1);
7554       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7555       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
7556       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7557       
7558       // Check 1: Make sure that the first operand of the inner multiply is NOT
7559       // a constant. Otherwise, we may induce infinite looping.
7560       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
7561         // Check 2: Make sure that the second operand of the inner multiply and
7562         // the second operand of the outer multiply are constants.
7563         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7564             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7565           SDLoc SL(N);
7566           SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7567           return DAG.getNode(ISD::FMUL, SL, VT, N00, MulConsts);
7568         }
7569       }
7570     }
7571
7572     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7573     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7574     // during an early run of DAGCombiner can prevent folding with fmuls
7575     // inserted during lowering.
7576     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7577       SDLoc SL(N);
7578       const SDValue Two = DAG.getConstantFP(2.0, VT);
7579       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7580       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7581     }
7582   }
7583
7584   // fold (fmul X, 2.0) -> (fadd X, X)
7585   if (N1CFP && N1CFP->isExactlyValue(+2.0))
7586     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
7587
7588   // fold (fmul X, -1.0) -> (fneg X)
7589   if (N1CFP && N1CFP->isExactlyValue(-1.0))
7590     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7591       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
7592
7593   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7594   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7595     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7596       // Both can be negated for free, check to see if at least one is cheaper
7597       // negated.
7598       if (LHSNeg == 2 || RHSNeg == 2)
7599         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7600                            GetNegatedExpression(N0, DAG, LegalOperations),
7601                            GetNegatedExpression(N1, DAG, LegalOperations));
7602     }
7603   }
7604
7605   return SDValue();
7606 }
7607
7608 SDValue DAGCombiner::visitFMA(SDNode *N) {
7609   SDValue N0 = N->getOperand(0);
7610   SDValue N1 = N->getOperand(1);
7611   SDValue N2 = N->getOperand(2);
7612   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7613   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7614   EVT VT = N->getValueType(0);
7615   SDLoc dl(N);
7616   const TargetOptions &Options = DAG.getTarget().Options;
7617
7618   // Constant fold FMA.
7619   if (isa<ConstantFPSDNode>(N0) &&
7620       isa<ConstantFPSDNode>(N1) &&
7621       isa<ConstantFPSDNode>(N2)) {
7622     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7623   }
7624
7625   if (Options.UnsafeFPMath) {
7626     if (N0CFP && N0CFP->isZero())
7627       return N2;
7628     if (N1CFP && N1CFP->isZero())
7629       return N2;
7630   }
7631   if (N0CFP && N0CFP->isExactlyValue(1.0))
7632     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
7633   if (N1CFP && N1CFP->isExactlyValue(1.0))
7634     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
7635
7636   // Canonicalize (fma c, x, y) -> (fma x, c, y)
7637   if (N0CFP && !N1CFP)
7638     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
7639
7640   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
7641   if (Options.UnsafeFPMath && N1CFP &&
7642       N2.getOpcode() == ISD::FMUL &&
7643       N0 == N2.getOperand(0) &&
7644       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7645     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7646                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7647   }
7648
7649
7650   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
7651   if (Options.UnsafeFPMath &&
7652       N0.getOpcode() == ISD::FMUL && N1CFP &&
7653       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7654     return DAG.getNode(ISD::FMA, dl, VT,
7655                        N0.getOperand(0),
7656                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7657                        N2);
7658   }
7659
7660   // (fma x, 1, y) -> (fadd x, y)
7661   // (fma x, -1, y) -> (fadd (fneg x), y)
7662   if (N1CFP) {
7663     if (N1CFP->isExactlyValue(1.0))
7664       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7665
7666     if (N1CFP->isExactlyValue(-1.0) &&
7667         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7668       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
7669       AddToWorklist(RHSNeg.getNode());
7670       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7671     }
7672   }
7673
7674   // (fma x, c, x) -> (fmul x, (c+1))
7675   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
7676     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7677                        DAG.getNode(ISD::FADD, dl, VT,
7678                                    N1, DAG.getConstantFP(1.0, VT)));
7679
7680   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
7681   if (Options.UnsafeFPMath && N1CFP &&
7682       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7683     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7684                        DAG.getNode(ISD::FADD, dl, VT,
7685                                    N1, DAG.getConstantFP(-1.0, VT)));
7686
7687
7688   return SDValue();
7689 }
7690
7691 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7692   SDValue N0 = N->getOperand(0);
7693   SDValue N1 = N->getOperand(1);
7694   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7695   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7696   EVT VT = N->getValueType(0);
7697   SDLoc DL(N);
7698   const TargetOptions &Options = DAG.getTarget().Options;
7699
7700   // fold vector ops
7701   if (VT.isVector()) {
7702     SDValue FoldedVOp = SimplifyVBinOp(N);
7703     if (FoldedVOp.getNode()) return FoldedVOp;
7704   }
7705
7706   // fold (fdiv c1, c2) -> c1/c2
7707   if (N0CFP && N1CFP)
7708     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7709
7710   if (Options.UnsafeFPMath) {
7711     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7712     if (N1CFP) {
7713       // Compute the reciprocal 1.0 / c2.
7714       APFloat N1APF = N1CFP->getValueAPF();
7715       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7716       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7717       // Only do the transform if the reciprocal is a legal fp immediate that
7718       // isn't too nasty (eg NaN, denormal, ...).
7719       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7720           (!LegalOperations ||
7721            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7722            // backend)... we should handle this gracefully after Legalize.
7723            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7724            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7725            TLI.isFPImmLegal(Recip, VT)))
7726         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7727                            DAG.getConstantFP(Recip, VT));
7728     }
7729
7730     // If this FDIV is part of a reciprocal square root, it may be folded
7731     // into a target-specific square root estimate instruction.
7732     if (N1.getOpcode() == ISD::FSQRT) {
7733       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7734         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7735       }
7736     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7737                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7738       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7739         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7740         AddToWorklist(RV.getNode());
7741         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7742       }
7743     } else if (N1.getOpcode() == ISD::FP_ROUND &&
7744                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7745       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7746         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7747         AddToWorklist(RV.getNode());
7748         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7749       }
7750     } else if (N1.getOpcode() == ISD::FMUL) {
7751       // Look through an FMUL. Even though this won't remove the FDIV directly,
7752       // it's still worthwhile to get rid of the FSQRT if possible.
7753       SDValue SqrtOp;
7754       SDValue OtherOp;
7755       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7756         SqrtOp = N1.getOperand(0);
7757         OtherOp = N1.getOperand(1);
7758       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7759         SqrtOp = N1.getOperand(1);
7760         OtherOp = N1.getOperand(0);
7761       }
7762       if (SqrtOp.getNode()) {
7763         // We found a FSQRT, so try to make this fold:
7764         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7765         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7766           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7767           AddToWorklist(RV.getNode());
7768           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7769         }
7770       }
7771     }
7772
7773     // Fold into a reciprocal estimate and multiply instead of a real divide.
7774     if (SDValue RV = BuildReciprocalEstimate(N1)) {
7775       AddToWorklist(RV.getNode());
7776       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7777     }
7778   }
7779
7780   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7781   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7782     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7783       // Both can be negated for free, check to see if at least one is cheaper
7784       // negated.
7785       if (LHSNeg == 2 || RHSNeg == 2)
7786         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7787                            GetNegatedExpression(N0, DAG, LegalOperations),
7788                            GetNegatedExpression(N1, DAG, LegalOperations));
7789     }
7790   }
7791
7792   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7793   // reciprocal.
7794   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
7795   // Notice that this is not always beneficial. One reason is different target
7796   // may have different costs for FDIV and FMUL, so sometimes the cost of two
7797   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
7798   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
7799   if (Options.UnsafeFPMath) {
7800     // Skip if current node is a reciprocal.
7801     if (N0CFP && N0CFP->isExactlyValue(1.0))
7802       return SDValue();
7803
7804     SmallVector<SDNode *, 4> Users;
7805     // Find all FDIV users of the same divisor.
7806     for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
7807                               UE = N1.getNode()->use_end();
7808          UI != UE; ++UI) {
7809       SDNode *User = UI.getUse().getUser();
7810       if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
7811         Users.push_back(User);
7812     }
7813
7814     if (TLI.combineRepeatedFPDivisors(Users.size())) {
7815       SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
7816       SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
7817
7818       // Dividend / Divisor -> Dividend * Reciprocal
7819       for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
7820         if ((*I)->getOperand(0) != FPOne) {
7821           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
7822                                         (*I)->getOperand(0), Reciprocal);
7823           DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
7824         }
7825       }
7826       return SDValue();
7827     }
7828   }
7829
7830   return SDValue();
7831 }
7832
7833 SDValue DAGCombiner::visitFREM(SDNode *N) {
7834   SDValue N0 = N->getOperand(0);
7835   SDValue N1 = N->getOperand(1);
7836   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7837   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7838   EVT VT = N->getValueType(0);
7839
7840   // fold (frem c1, c2) -> fmod(c1,c2)
7841   if (N0CFP && N1CFP)
7842     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7843
7844   return SDValue();
7845 }
7846
7847 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7848   if (DAG.getTarget().Options.UnsafeFPMath &&
7849       !TLI.isFsqrtCheap()) {
7850     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
7851     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7852       EVT VT = RV.getValueType();
7853       RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7854       AddToWorklist(RV.getNode());
7855
7856       // Unfortunately, RV is now NaN if the input was exactly 0.
7857       // Select out this case and force the answer to 0.
7858       SDValue Zero = DAG.getConstantFP(0.0, VT);
7859       SDValue ZeroCmp =
7860         DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7861                      N->getOperand(0), Zero, ISD::SETEQ);
7862       AddToWorklist(ZeroCmp.getNode());
7863       AddToWorklist(RV.getNode());
7864
7865       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7866                        SDLoc(N), VT, ZeroCmp, Zero, RV);
7867       return RV;
7868     }
7869   }
7870   return SDValue();
7871 }
7872
7873 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7874   SDValue N0 = N->getOperand(0);
7875   SDValue N1 = N->getOperand(1);
7876   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7877   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7878   EVT VT = N->getValueType(0);
7879
7880   if (N0CFP && N1CFP)  // Constant fold
7881     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7882
7883   if (N1CFP) {
7884     const APFloat& V = N1CFP->getValueAPF();
7885     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7886     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7887     if (!V.isNegative()) {
7888       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7889         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7890     } else {
7891       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7892         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7893                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7894     }
7895   }
7896
7897   // copysign(fabs(x), y) -> copysign(x, y)
7898   // copysign(fneg(x), y) -> copysign(x, y)
7899   // copysign(copysign(x,z), y) -> copysign(x, y)
7900   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7901       N0.getOpcode() == ISD::FCOPYSIGN)
7902     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7903                        N0.getOperand(0), N1);
7904
7905   // copysign(x, abs(y)) -> abs(x)
7906   if (N1.getOpcode() == ISD::FABS)
7907     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7908
7909   // copysign(x, copysign(y,z)) -> copysign(x, z)
7910   if (N1.getOpcode() == ISD::FCOPYSIGN)
7911     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7912                        N0, N1.getOperand(1));
7913
7914   // copysign(x, fp_extend(y)) -> copysign(x, y)
7915   // copysign(x, fp_round(y)) -> copysign(x, y)
7916   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7917     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7918                        N0, N1.getOperand(0));
7919
7920   return SDValue();
7921 }
7922
7923 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7924   SDValue N0 = N->getOperand(0);
7925   EVT VT = N->getValueType(0);
7926   EVT OpVT = N0.getValueType();
7927
7928   // fold (sint_to_fp c1) -> c1fp
7929   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7930   if (N0C &&
7931       // ...but only if the target supports immediate floating-point values
7932       (!LegalOperations ||
7933        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7934     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7935
7936   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7937   // but UINT_TO_FP is legal on this target, try to convert.
7938   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7939       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7940     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7941     if (DAG.SignBitIsZero(N0))
7942       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7943   }
7944
7945   // The next optimizations are desirable only if SELECT_CC can be lowered.
7946   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7947     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7948     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7949         !VT.isVector() &&
7950         (!LegalOperations ||
7951          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7952       SDValue Ops[] =
7953         { N0.getOperand(0), N0.getOperand(1),
7954           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7955           N0.getOperand(2) };
7956       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7957     }
7958
7959     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7960     //      (select_cc x, y, 1.0, 0.0,, cc)
7961     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7962         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7963         (!LegalOperations ||
7964          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7965       SDValue Ops[] =
7966         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7967           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7968           N0.getOperand(0).getOperand(2) };
7969       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7970     }
7971   }
7972
7973   return SDValue();
7974 }
7975
7976 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7977   SDValue N0 = N->getOperand(0);
7978   EVT VT = N->getValueType(0);
7979   EVT OpVT = N0.getValueType();
7980
7981   // fold (uint_to_fp c1) -> c1fp
7982   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7983   if (N0C &&
7984       // ...but only if the target supports immediate floating-point values
7985       (!LegalOperations ||
7986        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7987     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7988
7989   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7990   // but SINT_TO_FP is legal on this target, try to convert.
7991   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7992       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7993     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7994     if (DAG.SignBitIsZero(N0))
7995       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7996   }
7997
7998   // The next optimizations are desirable only if SELECT_CC can be lowered.
7999   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8000     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8001
8002     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8003         (!LegalOperations ||
8004          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8005       SDValue Ops[] =
8006         { N0.getOperand(0), N0.getOperand(1),
8007           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
8008           N0.getOperand(2) };
8009       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
8010     }
8011   }
8012
8013   return SDValue();
8014 }
8015
8016 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8017 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8018   SDValue N0 = N->getOperand(0);
8019   EVT VT = N->getValueType(0);
8020
8021   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8022     return SDValue();
8023
8024   SDValue Src = N0.getOperand(0);
8025   EVT SrcVT = Src.getValueType();
8026   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8027   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8028
8029   // We can safely assume the conversion won't overflow the output range,
8030   // because (for example) (uint8_t)18293.f is undefined behavior.
8031
8032   // Since we can assume the conversion won't overflow, our decision as to
8033   // whether the input will fit in the float should depend on the minimum
8034   // of the input range and output range.
8035
8036   // This means this is also safe for a signed input and unsigned output, since
8037   // a negative input would lead to undefined behavior.
8038   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8039   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8040   unsigned ActualSize = std::min(InputSize, OutputSize);
8041   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8042
8043   // We can only fold away the float conversion if the input range can be
8044   // represented exactly in the float range.
8045   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8046     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8047       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8048                                                        : ISD::ZERO_EXTEND;
8049       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8050     }
8051     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8052       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8053     if (SrcVT == VT)
8054       return Src;
8055     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8056   }
8057   return SDValue();
8058 }
8059
8060 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8061   SDValue N0 = N->getOperand(0);
8062   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8063   EVT VT = N->getValueType(0);
8064
8065   // fold (fp_to_sint c1fp) -> c1
8066   if (N0CFP)
8067     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8068
8069   return FoldIntToFPToInt(N, DAG);
8070 }
8071
8072 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8073   SDValue N0 = N->getOperand(0);
8074   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8075   EVT VT = N->getValueType(0);
8076
8077   // fold (fp_to_uint c1fp) -> c1
8078   if (N0CFP)
8079     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8080
8081   return FoldIntToFPToInt(N, DAG);
8082 }
8083
8084 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8085   SDValue N0 = N->getOperand(0);
8086   SDValue N1 = N->getOperand(1);
8087   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8088   EVT VT = N->getValueType(0);
8089
8090   // fold (fp_round c1fp) -> c1fp
8091   if (N0CFP)
8092     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8093
8094   // fold (fp_round (fp_extend x)) -> x
8095   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8096     return N0.getOperand(0);
8097
8098   // fold (fp_round (fp_round x)) -> (fp_round x)
8099   if (N0.getOpcode() == ISD::FP_ROUND) {
8100     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8101     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8102     // If the first fp_round isn't a value preserving truncation, it might
8103     // introduce a tie in the second fp_round, that wouldn't occur in the
8104     // single-step fp_round we want to fold to.
8105     // In other words, double rounding isn't the same as rounding.
8106     // Also, this is a value preserving truncation iff both fp_round's are.
8107     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc)
8108       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
8109                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc));
8110   }
8111
8112   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8113   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8114     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8115                               N0.getOperand(0), N1);
8116     AddToWorklist(Tmp.getNode());
8117     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8118                        Tmp, N0.getOperand(1));
8119   }
8120
8121   return SDValue();
8122 }
8123
8124 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8125   SDValue N0 = N->getOperand(0);
8126   EVT VT = N->getValueType(0);
8127   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8128   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8129
8130   // fold (fp_round_inreg c1fp) -> c1fp
8131   if (N0CFP && isTypeLegal(EVT)) {
8132     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
8133     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
8134   }
8135
8136   return SDValue();
8137 }
8138
8139 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8140   SDValue N0 = N->getOperand(0);
8141   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8142   EVT VT = N->getValueType(0);
8143
8144   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8145   if (N->hasOneUse() &&
8146       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8147     return SDValue();
8148
8149   // fold (fp_extend c1fp) -> c1fp
8150   if (N0CFP)
8151     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8152
8153   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8154   // value of X.
8155   if (N0.getOpcode() == ISD::FP_ROUND
8156       && N0.getNode()->getConstantOperandVal(1) == 1) {
8157     SDValue In = N0.getOperand(0);
8158     if (In.getValueType() == VT) return In;
8159     if (VT.bitsLT(In.getValueType()))
8160       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8161                          In, N0.getOperand(1));
8162     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8163   }
8164
8165   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8166   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8167        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8168     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8169     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8170                                      LN0->getChain(),
8171                                      LN0->getBasePtr(), N0.getValueType(),
8172                                      LN0->getMemOperand());
8173     CombineTo(N, ExtLoad);
8174     CombineTo(N0.getNode(),
8175               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8176                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
8177               ExtLoad.getValue(1));
8178     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8179   }
8180
8181   return SDValue();
8182 }
8183
8184 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8185   SDValue N0 = N->getOperand(0);
8186   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8187   EVT VT = N->getValueType(0);
8188
8189   // fold (fceil c1) -> fceil(c1)
8190   if (N0CFP)
8191     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8192
8193   return SDValue();
8194 }
8195
8196 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8197   SDValue N0 = N->getOperand(0);
8198   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8199   EVT VT = N->getValueType(0);
8200
8201   // fold (ftrunc c1) -> ftrunc(c1)
8202   if (N0CFP)
8203     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8204
8205   return SDValue();
8206 }
8207
8208 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8209   SDValue N0 = N->getOperand(0);
8210   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8211   EVT VT = N->getValueType(0);
8212
8213   // fold (ffloor c1) -> ffloor(c1)
8214   if (N0CFP)
8215     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8216
8217   return SDValue();
8218 }
8219
8220 // FIXME: FNEG and FABS have a lot in common; refactor.
8221 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8222   SDValue N0 = N->getOperand(0);
8223   EVT VT = N->getValueType(0);
8224
8225   if (VT.isVector()) {
8226     SDValue FoldedVOp = SimplifyVUnaryOp(N);
8227     if (FoldedVOp.getNode()) return FoldedVOp;
8228   }
8229
8230   // Constant fold FNEG.
8231   if (isa<ConstantFPSDNode>(N0))
8232     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
8233
8234   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8235                          &DAG.getTarget().Options))
8236     return GetNegatedExpression(N0, DAG, LegalOperations);
8237
8238   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8239   // constant pool values.
8240   if (!TLI.isFNegFree(VT) &&
8241       N0.getOpcode() == ISD::BITCAST &&
8242       N0.getNode()->hasOneUse()) {
8243     SDValue Int = N0.getOperand(0);
8244     EVT IntVT = Int.getValueType();
8245     if (IntVT.isInteger() && !IntVT.isVector()) {
8246       APInt SignMask;
8247       if (N0.getValueType().isVector()) {
8248         // For a vector, get a mask such as 0x80... per scalar element
8249         // and splat it.
8250         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8251         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8252       } else {
8253         // For a scalar, just generate 0x80...
8254         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8255       }
8256       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
8257                         DAG.getConstant(SignMask, IntVT));
8258       AddToWorklist(Int.getNode());
8259       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8260     }
8261   }
8262
8263   // (fneg (fmul c, x)) -> (fmul -c, x)
8264   if (N0.getOpcode() == ISD::FMUL) {
8265     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8266     if (CFP1) {
8267       APFloat CVal = CFP1->getValueAPF();
8268       CVal.changeSign();
8269       if (Level >= AfterLegalizeDAG &&
8270           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8271            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8272         return DAG.getNode(
8273             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8274             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8275     }
8276   }
8277
8278   return SDValue();
8279 }
8280
8281 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8282   SDValue N0 = N->getOperand(0);
8283   SDValue N1 = N->getOperand(1);
8284   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8285   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8286
8287   if (N0CFP && N1CFP) {
8288     const APFloat &C0 = N0CFP->getValueAPF();
8289     const APFloat &C1 = N1CFP->getValueAPF();
8290     return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
8291   }
8292
8293   if (N0CFP) {
8294     EVT VT = N->getValueType(0);
8295     // Canonicalize to constant on RHS.
8296     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8297   }
8298
8299   return SDValue();
8300 }
8301
8302 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8303   SDValue N0 = N->getOperand(0);
8304   SDValue N1 = N->getOperand(1);
8305   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8306   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8307
8308   if (N0CFP && N1CFP) {
8309     const APFloat &C0 = N0CFP->getValueAPF();
8310     const APFloat &C1 = N1CFP->getValueAPF();
8311     return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
8312   }
8313
8314   if (N0CFP) {
8315     EVT VT = N->getValueType(0);
8316     // Canonicalize to constant on RHS.
8317     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8318   }
8319
8320   return SDValue();
8321 }
8322
8323 SDValue DAGCombiner::visitFABS(SDNode *N) {
8324   SDValue N0 = N->getOperand(0);
8325   EVT VT = N->getValueType(0);
8326
8327   if (VT.isVector()) {
8328     SDValue FoldedVOp = SimplifyVUnaryOp(N);
8329     if (FoldedVOp.getNode()) return FoldedVOp;
8330   }
8331
8332   // fold (fabs c1) -> fabs(c1)
8333   if (isa<ConstantFPSDNode>(N0))
8334     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8335
8336   // fold (fabs (fabs x)) -> (fabs x)
8337   if (N0.getOpcode() == ISD::FABS)
8338     return N->getOperand(0);
8339
8340   // fold (fabs (fneg x)) -> (fabs x)
8341   // fold (fabs (fcopysign x, y)) -> (fabs x)
8342   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8343     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8344
8345   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8346   // constant pool values.
8347   if (!TLI.isFAbsFree(VT) &&
8348       N0.getOpcode() == ISD::BITCAST &&
8349       N0.getNode()->hasOneUse()) {
8350     SDValue Int = N0.getOperand(0);
8351     EVT IntVT = Int.getValueType();
8352     if (IntVT.isInteger() && !IntVT.isVector()) {
8353       APInt SignMask;
8354       if (N0.getValueType().isVector()) {
8355         // For a vector, get a mask such as 0x7f... per scalar element
8356         // and splat it.
8357         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8358         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8359       } else {
8360         // For a scalar, just generate 0x7f...
8361         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8362       }
8363       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
8364                         DAG.getConstant(SignMask, IntVT));
8365       AddToWorklist(Int.getNode());
8366       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8367     }
8368   }
8369
8370   return SDValue();
8371 }
8372
8373 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8374   SDValue Chain = N->getOperand(0);
8375   SDValue N1 = N->getOperand(1);
8376   SDValue N2 = N->getOperand(2);
8377
8378   // If N is a constant we could fold this into a fallthrough or unconditional
8379   // branch. However that doesn't happen very often in normal code, because
8380   // Instcombine/SimplifyCFG should have handled the available opportunities.
8381   // If we did this folding here, it would be necessary to update the
8382   // MachineBasicBlock CFG, which is awkward.
8383
8384   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8385   // on the target.
8386   if (N1.getOpcode() == ISD::SETCC &&
8387       TLI.isOperationLegalOrCustom(ISD::BR_CC,
8388                                    N1.getOperand(0).getValueType())) {
8389     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8390                        Chain, N1.getOperand(2),
8391                        N1.getOperand(0), N1.getOperand(1), N2);
8392   }
8393
8394   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8395       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8396        (N1.getOperand(0).hasOneUse() &&
8397         N1.getOperand(0).getOpcode() == ISD::SRL))) {
8398     SDNode *Trunc = nullptr;
8399     if (N1.getOpcode() == ISD::TRUNCATE) {
8400       // Look pass the truncate.
8401       Trunc = N1.getNode();
8402       N1 = N1.getOperand(0);
8403     }
8404
8405     // Match this pattern so that we can generate simpler code:
8406     //
8407     //   %a = ...
8408     //   %b = and i32 %a, 2
8409     //   %c = srl i32 %b, 1
8410     //   brcond i32 %c ...
8411     //
8412     // into
8413     //
8414     //   %a = ...
8415     //   %b = and i32 %a, 2
8416     //   %c = setcc eq %b, 0
8417     //   brcond %c ...
8418     //
8419     // This applies only when the AND constant value has one bit set and the
8420     // SRL constant is equal to the log2 of the AND constant. The back-end is
8421     // smart enough to convert the result into a TEST/JMP sequence.
8422     SDValue Op0 = N1.getOperand(0);
8423     SDValue Op1 = N1.getOperand(1);
8424
8425     if (Op0.getOpcode() == ISD::AND &&
8426         Op1.getOpcode() == ISD::Constant) {
8427       SDValue AndOp1 = Op0.getOperand(1);
8428
8429       if (AndOp1.getOpcode() == ISD::Constant) {
8430         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8431
8432         if (AndConst.isPowerOf2() &&
8433             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8434           SDValue SetCC =
8435             DAG.getSetCC(SDLoc(N),
8436                          getSetCCResultType(Op0.getValueType()),
8437                          Op0, DAG.getConstant(0, Op0.getValueType()),
8438                          ISD::SETNE);
8439
8440           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
8441                                           MVT::Other, Chain, SetCC, N2);
8442           // Don't add the new BRCond into the worklist or else SimplifySelectCC
8443           // will convert it back to (X & C1) >> C2.
8444           CombineTo(N, NewBRCond, false);
8445           // Truncate is dead.
8446           if (Trunc)
8447             deleteAndRecombine(Trunc);
8448           // Replace the uses of SRL with SETCC
8449           WorklistRemover DeadNodes(*this);
8450           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8451           deleteAndRecombine(N1.getNode());
8452           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8453         }
8454       }
8455     }
8456
8457     if (Trunc)
8458       // Restore N1 if the above transformation doesn't match.
8459       N1 = N->getOperand(1);
8460   }
8461
8462   // Transform br(xor(x, y)) -> br(x != y)
8463   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8464   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8465     SDNode *TheXor = N1.getNode();
8466     SDValue Op0 = TheXor->getOperand(0);
8467     SDValue Op1 = TheXor->getOperand(1);
8468     if (Op0.getOpcode() == Op1.getOpcode()) {
8469       // Avoid missing important xor optimizations.
8470       SDValue Tmp = visitXOR(TheXor);
8471       if (Tmp.getNode()) {
8472         if (Tmp.getNode() != TheXor) {
8473           DEBUG(dbgs() << "\nReplacing.8 ";
8474                 TheXor->dump(&DAG);
8475                 dbgs() << "\nWith: ";
8476                 Tmp.getNode()->dump(&DAG);
8477                 dbgs() << '\n');
8478           WorklistRemover DeadNodes(*this);
8479           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8480           deleteAndRecombine(TheXor);
8481           return DAG.getNode(ISD::BRCOND, SDLoc(N),
8482                              MVT::Other, Chain, Tmp, N2);
8483         }
8484
8485         // visitXOR has changed XOR's operands or replaced the XOR completely,
8486         // bail out.
8487         return SDValue(N, 0);
8488       }
8489     }
8490
8491     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8492       bool Equal = false;
8493       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8494         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8495             Op0.getOpcode() == ISD::XOR) {
8496           TheXor = Op0.getNode();
8497           Equal = true;
8498         }
8499
8500       EVT SetCCVT = N1.getValueType();
8501       if (LegalTypes)
8502         SetCCVT = getSetCCResultType(SetCCVT);
8503       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8504                                    SetCCVT,
8505                                    Op0, Op1,
8506                                    Equal ? ISD::SETEQ : ISD::SETNE);
8507       // Replace the uses of XOR with SETCC
8508       WorklistRemover DeadNodes(*this);
8509       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8510       deleteAndRecombine(N1.getNode());
8511       return DAG.getNode(ISD::BRCOND, SDLoc(N),
8512                          MVT::Other, Chain, SetCC, N2);
8513     }
8514   }
8515
8516   return SDValue();
8517 }
8518
8519 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8520 //
8521 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
8522   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
8523   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
8524
8525   // If N is a constant we could fold this into a fallthrough or unconditional
8526   // branch. However that doesn't happen very often in normal code, because
8527   // Instcombine/SimplifyCFG should have handled the available opportunities.
8528   // If we did this folding here, it would be necessary to update the
8529   // MachineBasicBlock CFG, which is awkward.
8530
8531   // Use SimplifySetCC to simplify SETCC's.
8532   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
8533                                CondLHS, CondRHS, CC->get(), SDLoc(N),
8534                                false);
8535   if (Simp.getNode()) AddToWorklist(Simp.getNode());
8536
8537   // fold to a simpler setcc
8538   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
8539     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8540                        N->getOperand(0), Simp.getOperand(2),
8541                        Simp.getOperand(0), Simp.getOperand(1),
8542                        N->getOperand(4));
8543
8544   return SDValue();
8545 }
8546
8547 /// Return true if 'Use' is a load or a store that uses N as its base pointer
8548 /// and that N may be folded in the load / store addressing mode.
8549 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8550                                     SelectionDAG &DAG,
8551                                     const TargetLowering &TLI) {
8552   EVT VT;
8553   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
8554     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8555       return false;
8556     VT = Use->getValueType(0);
8557   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
8558     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8559       return false;
8560     VT = ST->getValue().getValueType();
8561   } else
8562     return false;
8563
8564   TargetLowering::AddrMode AM;
8565   if (N->getOpcode() == ISD::ADD) {
8566     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8567     if (Offset)
8568       // [reg +/- imm]
8569       AM.BaseOffs = Offset->getSExtValue();
8570     else
8571       // [reg +/- reg]
8572       AM.Scale = 1;
8573   } else if (N->getOpcode() == ISD::SUB) {
8574     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8575     if (Offset)
8576       // [reg +/- imm]
8577       AM.BaseOffs = -Offset->getSExtValue();
8578     else
8579       // [reg +/- reg]
8580       AM.Scale = 1;
8581   } else
8582     return false;
8583
8584   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8585 }
8586
8587 /// Try turning a load/store into a pre-indexed load/store when the base
8588 /// pointer is an add or subtract and it has other uses besides the load/store.
8589 /// After the transformation, the new indexed load/store has effectively folded
8590 /// the add/subtract in and all of its other uses are redirected to the
8591 /// new load/store.
8592 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8593   if (Level < AfterLegalizeDAG)
8594     return false;
8595
8596   bool isLoad = true;
8597   SDValue Ptr;
8598   EVT VT;
8599   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8600     if (LD->isIndexed())
8601       return false;
8602     VT = LD->getMemoryVT();
8603     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8604         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8605       return false;
8606     Ptr = LD->getBasePtr();
8607   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8608     if (ST->isIndexed())
8609       return false;
8610     VT = ST->getMemoryVT();
8611     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8612         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8613       return false;
8614     Ptr = ST->getBasePtr();
8615     isLoad = false;
8616   } else {
8617     return false;
8618   }
8619
8620   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8621   // out.  There is no reason to make this a preinc/predec.
8622   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
8623       Ptr.getNode()->hasOneUse())
8624     return false;
8625
8626   // Ask the target to do addressing mode selection.
8627   SDValue BasePtr;
8628   SDValue Offset;
8629   ISD::MemIndexedMode AM = ISD::UNINDEXED;
8630   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8631     return false;
8632
8633   // Backends without true r+i pre-indexed forms may need to pass a
8634   // constant base with a variable offset so that constant coercion
8635   // will work with the patterns in canonical form.
8636   bool Swapped = false;
8637   if (isa<ConstantSDNode>(BasePtr)) {
8638     std::swap(BasePtr, Offset);
8639     Swapped = true;
8640   }
8641
8642   // Don't create a indexed load / store with zero offset.
8643   if (isa<ConstantSDNode>(Offset) &&
8644       cast<ConstantSDNode>(Offset)->isNullValue())
8645     return false;
8646
8647   // Try turning it into a pre-indexed load / store except when:
8648   // 1) The new base ptr is a frame index.
8649   // 2) If N is a store and the new base ptr is either the same as or is a
8650   //    predecessor of the value being stored.
8651   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
8652   //    that would create a cycle.
8653   // 4) All uses are load / store ops that use it as old base ptr.
8654
8655   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
8656   // (plus the implicit offset) to a register to preinc anyway.
8657   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8658     return false;
8659
8660   // Check #2.
8661   if (!isLoad) {
8662     SDValue Val = cast<StoreSDNode>(N)->getValue();
8663     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
8664       return false;
8665   }
8666
8667   // If the offset is a constant, there may be other adds of constants that
8668   // can be folded with this one. We should do this to avoid having to keep
8669   // a copy of the original base pointer.
8670   SmallVector<SDNode *, 16> OtherUses;
8671   if (isa<ConstantSDNode>(Offset))
8672     for (SDNode *Use : BasePtr.getNode()->uses()) {
8673       if (Use == Ptr.getNode())
8674         continue;
8675
8676       if (Use->isPredecessorOf(N))
8677         continue;
8678
8679       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8680         OtherUses.clear();
8681         break;
8682       }
8683
8684       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8685       if (Op1.getNode() == BasePtr.getNode())
8686         std::swap(Op0, Op1);
8687       assert(Op0.getNode() == BasePtr.getNode() &&
8688              "Use of ADD/SUB but not an operand");
8689
8690       if (!isa<ConstantSDNode>(Op1)) {
8691         OtherUses.clear();
8692         break;
8693       }
8694
8695       // FIXME: In some cases, we can be smarter about this.
8696       if (Op1.getValueType() != Offset.getValueType()) {
8697         OtherUses.clear();
8698         break;
8699       }
8700
8701       OtherUses.push_back(Use);
8702     }
8703
8704   if (Swapped)
8705     std::swap(BasePtr, Offset);
8706
8707   // Now check for #3 and #4.
8708   bool RealUse = false;
8709
8710   // Caches for hasPredecessorHelper
8711   SmallPtrSet<const SDNode *, 32> Visited;
8712   SmallVector<const SDNode *, 16> Worklist;
8713
8714   for (SDNode *Use : Ptr.getNode()->uses()) {
8715     if (Use == N)
8716       continue;
8717     if (N->hasPredecessorHelper(Use, Visited, Worklist))
8718       return false;
8719
8720     // If Ptr may be folded in addressing mode of other use, then it's
8721     // not profitable to do this transformation.
8722     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
8723       RealUse = true;
8724   }
8725
8726   if (!RealUse)
8727     return false;
8728
8729   SDValue Result;
8730   if (isLoad)
8731     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8732                                 BasePtr, Offset, AM);
8733   else
8734     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8735                                  BasePtr, Offset, AM);
8736   ++PreIndexedNodes;
8737   ++NodesCombined;
8738   DEBUG(dbgs() << "\nReplacing.4 ";
8739         N->dump(&DAG);
8740         dbgs() << "\nWith: ";
8741         Result.getNode()->dump(&DAG);
8742         dbgs() << '\n');
8743   WorklistRemover DeadNodes(*this);
8744   if (isLoad) {
8745     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8746     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8747   } else {
8748     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8749   }
8750
8751   // Finally, since the node is now dead, remove it from the graph.
8752   deleteAndRecombine(N);
8753
8754   if (Swapped)
8755     std::swap(BasePtr, Offset);
8756
8757   // Replace other uses of BasePtr that can be updated to use Ptr
8758   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8759     unsigned OffsetIdx = 1;
8760     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8761       OffsetIdx = 0;
8762     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8763            BasePtr.getNode() && "Expected BasePtr operand");
8764
8765     // We need to replace ptr0 in the following expression:
8766     //   x0 * offset0 + y0 * ptr0 = t0
8767     // knowing that
8768     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
8769     //
8770     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8771     // indexed load/store and the expresion that needs to be re-written.
8772     //
8773     // Therefore, we have:
8774     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
8775
8776     ConstantSDNode *CN =
8777       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
8778     int X0, X1, Y0, Y1;
8779     APInt Offset0 = CN->getAPIntValue();
8780     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8781
8782     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8783     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8784     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8785     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8786
8787     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8788
8789     APInt CNV = Offset0;
8790     if (X0 < 0) CNV = -CNV;
8791     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8792     else CNV = CNV - Offset1;
8793
8794     // We can now generate the new expression.
8795     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8796     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8797
8798     SDValue NewUse = DAG.getNode(Opcode,
8799                                  SDLoc(OtherUses[i]),
8800                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8801     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8802     deleteAndRecombine(OtherUses[i]);
8803   }
8804
8805   // Replace the uses of Ptr with uses of the updated base value.
8806   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8807   deleteAndRecombine(Ptr.getNode());
8808
8809   return true;
8810 }
8811
8812 /// Try to combine a load/store with a add/sub of the base pointer node into a
8813 /// post-indexed load/store. The transformation folded the add/subtract into the
8814 /// new indexed load/store effectively and all of its uses are redirected to the
8815 /// new load/store.
8816 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
8817   if (Level < AfterLegalizeDAG)
8818     return false;
8819
8820   bool isLoad = true;
8821   SDValue Ptr;
8822   EVT VT;
8823   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8824     if (LD->isIndexed())
8825       return false;
8826     VT = LD->getMemoryVT();
8827     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8828         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8829       return false;
8830     Ptr = LD->getBasePtr();
8831   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8832     if (ST->isIndexed())
8833       return false;
8834     VT = ST->getMemoryVT();
8835     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8836         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8837       return false;
8838     Ptr = ST->getBasePtr();
8839     isLoad = false;
8840   } else {
8841     return false;
8842   }
8843
8844   if (Ptr.getNode()->hasOneUse())
8845     return false;
8846
8847   for (SDNode *Op : Ptr.getNode()->uses()) {
8848     if (Op == N ||
8849         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8850       continue;
8851
8852     SDValue BasePtr;
8853     SDValue Offset;
8854     ISD::MemIndexedMode AM = ISD::UNINDEXED;
8855     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8856       // Don't create a indexed load / store with zero offset.
8857       if (isa<ConstantSDNode>(Offset) &&
8858           cast<ConstantSDNode>(Offset)->isNullValue())
8859         continue;
8860
8861       // Try turning it into a post-indexed load / store except when
8862       // 1) All uses are load / store ops that use it as base ptr (and
8863       //    it may be folded as addressing mmode).
8864       // 2) Op must be independent of N, i.e. Op is neither a predecessor
8865       //    nor a successor of N. Otherwise, if Op is folded that would
8866       //    create a cycle.
8867
8868       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8869         continue;
8870
8871       // Check for #1.
8872       bool TryNext = false;
8873       for (SDNode *Use : BasePtr.getNode()->uses()) {
8874         if (Use == Ptr.getNode())
8875           continue;
8876
8877         // If all the uses are load / store addresses, then don't do the
8878         // transformation.
8879         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8880           bool RealUse = false;
8881           for (SDNode *UseUse : Use->uses()) {
8882             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8883               RealUse = true;
8884           }
8885
8886           if (!RealUse) {
8887             TryNext = true;
8888             break;
8889           }
8890         }
8891       }
8892
8893       if (TryNext)
8894         continue;
8895
8896       // Check for #2
8897       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8898         SDValue Result = isLoad
8899           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8900                                BasePtr, Offset, AM)
8901           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8902                                 BasePtr, Offset, AM);
8903         ++PostIndexedNodes;
8904         ++NodesCombined;
8905         DEBUG(dbgs() << "\nReplacing.5 ";
8906               N->dump(&DAG);
8907               dbgs() << "\nWith: ";
8908               Result.getNode()->dump(&DAG);
8909               dbgs() << '\n');
8910         WorklistRemover DeadNodes(*this);
8911         if (isLoad) {
8912           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8913           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8914         } else {
8915           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8916         }
8917
8918         // Finally, since the node is now dead, remove it from the graph.
8919         deleteAndRecombine(N);
8920
8921         // Replace the uses of Use with uses of the updated base value.
8922         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8923                                       Result.getValue(isLoad ? 1 : 0));
8924         deleteAndRecombine(Op);
8925         return true;
8926       }
8927     }
8928   }
8929
8930   return false;
8931 }
8932
8933 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8934 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8935   ISD::MemIndexedMode AM = LD->getAddressingMode();
8936   assert(AM != ISD::UNINDEXED);
8937   SDValue BP = LD->getOperand(1);
8938   SDValue Inc = LD->getOperand(2);
8939
8940   // Some backends use TargetConstants for load offsets, but don't expect
8941   // TargetConstants in general ADD nodes. We can convert these constants into
8942   // regular Constants (if the constant is not opaque).
8943   assert((Inc.getOpcode() != ISD::TargetConstant ||
8944           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8945          "Cannot split out indexing using opaque target constants");
8946   if (Inc.getOpcode() == ISD::TargetConstant) {
8947     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8948     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8949                           ConstInc->getValueType(0));
8950   }
8951
8952   unsigned Opc =
8953       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8954   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8955 }
8956
8957 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8958   LoadSDNode *LD  = cast<LoadSDNode>(N);
8959   SDValue Chain = LD->getChain();
8960   SDValue Ptr   = LD->getBasePtr();
8961
8962   // If load is not volatile and there are no uses of the loaded value (and
8963   // the updated indexed value in case of indexed loads), change uses of the
8964   // chain value into uses of the chain input (i.e. delete the dead load).
8965   if (!LD->isVolatile()) {
8966     if (N->getValueType(1) == MVT::Other) {
8967       // Unindexed loads.
8968       if (!N->hasAnyUseOfValue(0)) {
8969         // It's not safe to use the two value CombineTo variant here. e.g.
8970         // v1, chain2 = load chain1, loc
8971         // v2, chain3 = load chain2, loc
8972         // v3         = add v2, c
8973         // Now we replace use of chain2 with chain1.  This makes the second load
8974         // isomorphic to the one we are deleting, and thus makes this load live.
8975         DEBUG(dbgs() << "\nReplacing.6 ";
8976               N->dump(&DAG);
8977               dbgs() << "\nWith chain: ";
8978               Chain.getNode()->dump(&DAG);
8979               dbgs() << "\n");
8980         WorklistRemover DeadNodes(*this);
8981         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8982
8983         if (N->use_empty())
8984           deleteAndRecombine(N);
8985
8986         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8987       }
8988     } else {
8989       // Indexed loads.
8990       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8991
8992       // If this load has an opaque TargetConstant offset, then we cannot split
8993       // the indexing into an add/sub directly (that TargetConstant may not be
8994       // valid for a different type of node, and we cannot convert an opaque
8995       // target constant into a regular constant).
8996       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8997                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8998
8999       if (!N->hasAnyUseOfValue(0) &&
9000           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9001         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9002         SDValue Index;
9003         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9004           Index = SplitIndexingFromLoad(LD);
9005           // Try to fold the base pointer arithmetic into subsequent loads and
9006           // stores.
9007           AddUsersToWorklist(N);
9008         } else
9009           Index = DAG.getUNDEF(N->getValueType(1));
9010         DEBUG(dbgs() << "\nReplacing.7 ";
9011               N->dump(&DAG);
9012               dbgs() << "\nWith: ";
9013               Undef.getNode()->dump(&DAG);
9014               dbgs() << " and 2 other values\n");
9015         WorklistRemover DeadNodes(*this);
9016         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9017         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9018         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9019         deleteAndRecombine(N);
9020         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9021       }
9022     }
9023   }
9024
9025   // If this load is directly stored, replace the load value with the stored
9026   // value.
9027   // TODO: Handle store large -> read small portion.
9028   // TODO: Handle TRUNCSTORE/LOADEXT
9029   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9030     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9031       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9032       if (PrevST->getBasePtr() == Ptr &&
9033           PrevST->getValue().getValueType() == N->getValueType(0))
9034       return CombineTo(N, Chain.getOperand(1), Chain);
9035     }
9036   }
9037
9038   // Try to infer better alignment information than the load already has.
9039   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9040     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9041       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9042         SDValue NewLoad =
9043                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9044                               LD->getValueType(0),
9045                               Chain, Ptr, LD->getPointerInfo(),
9046                               LD->getMemoryVT(),
9047                               LD->isVolatile(), LD->isNonTemporal(),
9048                               LD->isInvariant(), Align, LD->getAAInfo());
9049         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9050       }
9051     }
9052   }
9053
9054   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9055                                                   : DAG.getSubtarget().useAA();
9056 #ifndef NDEBUG
9057   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9058       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9059     UseAA = false;
9060 #endif
9061   if (UseAA && LD->isUnindexed()) {
9062     // Walk up chain skipping non-aliasing memory nodes.
9063     SDValue BetterChain = FindBetterChain(N, Chain);
9064
9065     // If there is a better chain.
9066     if (Chain != BetterChain) {
9067       SDValue ReplLoad;
9068
9069       // Replace the chain to void dependency.
9070       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9071         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9072                                BetterChain, Ptr, LD->getMemOperand());
9073       } else {
9074         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9075                                   LD->getValueType(0),
9076                                   BetterChain, Ptr, LD->getMemoryVT(),
9077                                   LD->getMemOperand());
9078       }
9079
9080       // Create token factor to keep old chain connected.
9081       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9082                                   MVT::Other, Chain, ReplLoad.getValue(1));
9083
9084       // Make sure the new and old chains are cleaned up.
9085       AddToWorklist(Token.getNode());
9086
9087       // Replace uses with load result and token factor. Don't add users
9088       // to work list.
9089       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9090     }
9091   }
9092
9093   // Try transforming N to an indexed load.
9094   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9095     return SDValue(N, 0);
9096
9097   // Try to slice up N to more direct loads if the slices are mapped to
9098   // different register banks or pairing can take place.
9099   if (SliceUpLoad(N))
9100     return SDValue(N, 0);
9101
9102   return SDValue();
9103 }
9104
9105 namespace {
9106 /// \brief Helper structure used to slice a load in smaller loads.
9107 /// Basically a slice is obtained from the following sequence:
9108 /// Origin = load Ty1, Base
9109 /// Shift = srl Ty1 Origin, CstTy Amount
9110 /// Inst = trunc Shift to Ty2
9111 ///
9112 /// Then, it will be rewriten into:
9113 /// Slice = load SliceTy, Base + SliceOffset
9114 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9115 ///
9116 /// SliceTy is deduced from the number of bits that are actually used to
9117 /// build Inst.
9118 struct LoadedSlice {
9119   /// \brief Helper structure used to compute the cost of a slice.
9120   struct Cost {
9121     /// Are we optimizing for code size.
9122     bool ForCodeSize;
9123     /// Various cost.
9124     unsigned Loads;
9125     unsigned Truncates;
9126     unsigned CrossRegisterBanksCopies;
9127     unsigned ZExts;
9128     unsigned Shift;
9129
9130     Cost(bool ForCodeSize = false)
9131         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9132           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9133
9134     /// \brief Get the cost of one isolated slice.
9135     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9136         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9137           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9138       EVT TruncType = LS.Inst->getValueType(0);
9139       EVT LoadedType = LS.getLoadedType();
9140       if (TruncType != LoadedType &&
9141           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9142         ZExts = 1;
9143     }
9144
9145     /// \brief Account for slicing gain in the current cost.
9146     /// Slicing provide a few gains like removing a shift or a
9147     /// truncate. This method allows to grow the cost of the original
9148     /// load with the gain from this slice.
9149     void addSliceGain(const LoadedSlice &LS) {
9150       // Each slice saves a truncate.
9151       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9152       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9153                               LS.Inst->getOperand(0).getValueType()))
9154         ++Truncates;
9155       // If there is a shift amount, this slice gets rid of it.
9156       if (LS.Shift)
9157         ++Shift;
9158       // If this slice can merge a cross register bank copy, account for it.
9159       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9160         ++CrossRegisterBanksCopies;
9161     }
9162
9163     Cost &operator+=(const Cost &RHS) {
9164       Loads += RHS.Loads;
9165       Truncates += RHS.Truncates;
9166       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9167       ZExts += RHS.ZExts;
9168       Shift += RHS.Shift;
9169       return *this;
9170     }
9171
9172     bool operator==(const Cost &RHS) const {
9173       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9174              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9175              ZExts == RHS.ZExts && Shift == RHS.Shift;
9176     }
9177
9178     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9179
9180     bool operator<(const Cost &RHS) const {
9181       // Assume cross register banks copies are as expensive as loads.
9182       // FIXME: Do we want some more target hooks?
9183       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9184       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9185       // Unless we are optimizing for code size, consider the
9186       // expensive operation first.
9187       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9188         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9189       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9190              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9191     }
9192
9193     bool operator>(const Cost &RHS) const { return RHS < *this; }
9194
9195     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9196
9197     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9198   };
9199   // The last instruction that represent the slice. This should be a
9200   // truncate instruction.
9201   SDNode *Inst;
9202   // The original load instruction.
9203   LoadSDNode *Origin;
9204   // The right shift amount in bits from the original load.
9205   unsigned Shift;
9206   // The DAG from which Origin came from.
9207   // This is used to get some contextual information about legal types, etc.
9208   SelectionDAG *DAG;
9209
9210   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9211               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9212       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9213
9214   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9215   /// \return Result is \p BitWidth and has used bits set to 1 and
9216   ///         not used bits set to 0.
9217   APInt getUsedBits() const {
9218     // Reproduce the trunc(lshr) sequence:
9219     // - Start from the truncated value.
9220     // - Zero extend to the desired bit width.
9221     // - Shift left.
9222     assert(Origin && "No original load to compare against.");
9223     unsigned BitWidth = Origin->getValueSizeInBits(0);
9224     assert(Inst && "This slice is not bound to an instruction");
9225     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9226            "Extracted slice is bigger than the whole type!");
9227     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9228     UsedBits.setAllBits();
9229     UsedBits = UsedBits.zext(BitWidth);
9230     UsedBits <<= Shift;
9231     return UsedBits;
9232   }
9233
9234   /// \brief Get the size of the slice to be loaded in bytes.
9235   unsigned getLoadedSize() const {
9236     unsigned SliceSize = getUsedBits().countPopulation();
9237     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9238     return SliceSize / 8;
9239   }
9240
9241   /// \brief Get the type that will be loaded for this slice.
9242   /// Note: This may not be the final type for the slice.
9243   EVT getLoadedType() const {
9244     assert(DAG && "Missing context");
9245     LLVMContext &Ctxt = *DAG->getContext();
9246     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9247   }
9248
9249   /// \brief Get the alignment of the load used for this slice.
9250   unsigned getAlignment() const {
9251     unsigned Alignment = Origin->getAlignment();
9252     unsigned Offset = getOffsetFromBase();
9253     if (Offset != 0)
9254       Alignment = MinAlign(Alignment, Alignment + Offset);
9255     return Alignment;
9256   }
9257
9258   /// \brief Check if this slice can be rewritten with legal operations.
9259   bool isLegal() const {
9260     // An invalid slice is not legal.
9261     if (!Origin || !Inst || !DAG)
9262       return false;
9263
9264     // Offsets are for indexed load only, we do not handle that.
9265     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9266       return false;
9267
9268     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9269
9270     // Check that the type is legal.
9271     EVT SliceType = getLoadedType();
9272     if (!TLI.isTypeLegal(SliceType))
9273       return false;
9274
9275     // Check that the load is legal for this type.
9276     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9277       return false;
9278
9279     // Check that the offset can be computed.
9280     // 1. Check its type.
9281     EVT PtrType = Origin->getBasePtr().getValueType();
9282     if (PtrType == MVT::Untyped || PtrType.isExtended())
9283       return false;
9284
9285     // 2. Check that it fits in the immediate.
9286     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9287       return false;
9288
9289     // 3. Check that the computation is legal.
9290     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9291       return false;
9292
9293     // Check that the zext is legal if it needs one.
9294     EVT TruncateType = Inst->getValueType(0);
9295     if (TruncateType != SliceType &&
9296         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9297       return false;
9298
9299     return true;
9300   }
9301
9302   /// \brief Get the offset in bytes of this slice in the original chunk of
9303   /// bits.
9304   /// \pre DAG != nullptr.
9305   uint64_t getOffsetFromBase() const {
9306     assert(DAG && "Missing context.");
9307     bool IsBigEndian =
9308         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9309     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9310     uint64_t Offset = Shift / 8;
9311     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9312     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9313            "The size of the original loaded type is not a multiple of a"
9314            " byte.");
9315     // If Offset is bigger than TySizeInBytes, it means we are loading all
9316     // zeros. This should have been optimized before in the process.
9317     assert(TySizeInBytes > Offset &&
9318            "Invalid shift amount for given loaded size");
9319     if (IsBigEndian)
9320       Offset = TySizeInBytes - Offset - getLoadedSize();
9321     return Offset;
9322   }
9323
9324   /// \brief Generate the sequence of instructions to load the slice
9325   /// represented by this object and redirect the uses of this slice to
9326   /// this new sequence of instructions.
9327   /// \pre this->Inst && this->Origin are valid Instructions and this
9328   /// object passed the legal check: LoadedSlice::isLegal returned true.
9329   /// \return The last instruction of the sequence used to load the slice.
9330   SDValue loadSlice() const {
9331     assert(Inst && Origin && "Unable to replace a non-existing slice.");
9332     const SDValue &OldBaseAddr = Origin->getBasePtr();
9333     SDValue BaseAddr = OldBaseAddr;
9334     // Get the offset in that chunk of bytes w.r.t. the endianess.
9335     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9336     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9337     if (Offset) {
9338       // BaseAddr = BaseAddr + Offset.
9339       EVT ArithType = BaseAddr.getValueType();
9340       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
9341                               DAG->getConstant(Offset, ArithType));
9342     }
9343
9344     // Create the type of the loaded slice according to its size.
9345     EVT SliceType = getLoadedType();
9346
9347     // Create the load for the slice.
9348     SDValue LastInst = DAG->getLoad(
9349         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9350         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9351         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9352     // If the final type is not the same as the loaded type, this means that
9353     // we have to pad with zero. Create a zero extend for that.
9354     EVT FinalType = Inst->getValueType(0);
9355     if (SliceType != FinalType)
9356       LastInst =
9357           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9358     return LastInst;
9359   }
9360
9361   /// \brief Check if this slice can be merged with an expensive cross register
9362   /// bank copy. E.g.,
9363   /// i = load i32
9364   /// f = bitcast i32 i to float
9365   bool canMergeExpensiveCrossRegisterBankCopy() const {
9366     if (!Inst || !Inst->hasOneUse())
9367       return false;
9368     SDNode *Use = *Inst->use_begin();
9369     if (Use->getOpcode() != ISD::BITCAST)
9370       return false;
9371     assert(DAG && "Missing context");
9372     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9373     EVT ResVT = Use->getValueType(0);
9374     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9375     const TargetRegisterClass *ArgRC =
9376         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9377     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9378       return false;
9379
9380     // At this point, we know that we perform a cross-register-bank copy.
9381     // Check if it is expensive.
9382     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9383     // Assume bitcasts are cheap, unless both register classes do not
9384     // explicitly share a common sub class.
9385     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9386       return false;
9387
9388     // Check if it will be merged with the load.
9389     // 1. Check the alignment constraint.
9390     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9391         ResVT.getTypeForEVT(*DAG->getContext()));
9392
9393     if (RequiredAlignment > getAlignment())
9394       return false;
9395
9396     // 2. Check that the load is a legal operation for that type.
9397     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9398       return false;
9399
9400     // 3. Check that we do not have a zext in the way.
9401     if (Inst->getValueType(0) != getLoadedType())
9402       return false;
9403
9404     return true;
9405   }
9406 };
9407 }
9408
9409 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9410 /// \p UsedBits looks like 0..0 1..1 0..0.
9411 static bool areUsedBitsDense(const APInt &UsedBits) {
9412   // If all the bits are one, this is dense!
9413   if (UsedBits.isAllOnesValue())
9414     return true;
9415
9416   // Get rid of the unused bits on the right.
9417   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9418   // Get rid of the unused bits on the left.
9419   if (NarrowedUsedBits.countLeadingZeros())
9420     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9421   // Check that the chunk of bits is completely used.
9422   return NarrowedUsedBits.isAllOnesValue();
9423 }
9424
9425 /// \brief Check whether or not \p First and \p Second are next to each other
9426 /// in memory. This means that there is no hole between the bits loaded
9427 /// by \p First and the bits loaded by \p Second.
9428 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9429                                      const LoadedSlice &Second) {
9430   assert(First.Origin == Second.Origin && First.Origin &&
9431          "Unable to match different memory origins.");
9432   APInt UsedBits = First.getUsedBits();
9433   assert((UsedBits & Second.getUsedBits()) == 0 &&
9434          "Slices are not supposed to overlap.");
9435   UsedBits |= Second.getUsedBits();
9436   return areUsedBitsDense(UsedBits);
9437 }
9438
9439 /// \brief Adjust the \p GlobalLSCost according to the target
9440 /// paring capabilities and the layout of the slices.
9441 /// \pre \p GlobalLSCost should account for at least as many loads as
9442 /// there is in the slices in \p LoadedSlices.
9443 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9444                                  LoadedSlice::Cost &GlobalLSCost) {
9445   unsigned NumberOfSlices = LoadedSlices.size();
9446   // If there is less than 2 elements, no pairing is possible.
9447   if (NumberOfSlices < 2)
9448     return;
9449
9450   // Sort the slices so that elements that are likely to be next to each
9451   // other in memory are next to each other in the list.
9452   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9453             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9454     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9455     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9456   });
9457   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9458   // First (resp. Second) is the first (resp. Second) potentially candidate
9459   // to be placed in a paired load.
9460   const LoadedSlice *First = nullptr;
9461   const LoadedSlice *Second = nullptr;
9462   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9463                 // Set the beginning of the pair.
9464                                                            First = Second) {
9465
9466     Second = &LoadedSlices[CurrSlice];
9467
9468     // If First is NULL, it means we start a new pair.
9469     // Get to the next slice.
9470     if (!First)
9471       continue;
9472
9473     EVT LoadedType = First->getLoadedType();
9474
9475     // If the types of the slices are different, we cannot pair them.
9476     if (LoadedType != Second->getLoadedType())
9477       continue;
9478
9479     // Check if the target supplies paired loads for this type.
9480     unsigned RequiredAlignment = 0;
9481     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9482       // move to the next pair, this type is hopeless.
9483       Second = nullptr;
9484       continue;
9485     }
9486     // Check if we meet the alignment requirement.
9487     if (RequiredAlignment > First->getAlignment())
9488       continue;
9489
9490     // Check that both loads are next to each other in memory.
9491     if (!areSlicesNextToEachOther(*First, *Second))
9492       continue;
9493
9494     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9495     --GlobalLSCost.Loads;
9496     // Move to the next pair.
9497     Second = nullptr;
9498   }
9499 }
9500
9501 /// \brief Check the profitability of all involved LoadedSlice.
9502 /// Currently, it is considered profitable if there is exactly two
9503 /// involved slices (1) which are (2) next to each other in memory, and
9504 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9505 ///
9506 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9507 /// the elements themselves.
9508 ///
9509 /// FIXME: When the cost model will be mature enough, we can relax
9510 /// constraints (1) and (2).
9511 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9512                                 const APInt &UsedBits, bool ForCodeSize) {
9513   unsigned NumberOfSlices = LoadedSlices.size();
9514   if (StressLoadSlicing)
9515     return NumberOfSlices > 1;
9516
9517   // Check (1).
9518   if (NumberOfSlices != 2)
9519     return false;
9520
9521   // Check (2).
9522   if (!areUsedBitsDense(UsedBits))
9523     return false;
9524
9525   // Check (3).
9526   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9527   // The original code has one big load.
9528   OrigCost.Loads = 1;
9529   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9530     const LoadedSlice &LS = LoadedSlices[CurrSlice];
9531     // Accumulate the cost of all the slices.
9532     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9533     GlobalSlicingCost += SliceCost;
9534
9535     // Account as cost in the original configuration the gain obtained
9536     // with the current slices.
9537     OrigCost.addSliceGain(LS);
9538   }
9539
9540   // If the target supports paired load, adjust the cost accordingly.
9541   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9542   return OrigCost > GlobalSlicingCost;
9543 }
9544
9545 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9546 /// operations, split it in the various pieces being extracted.
9547 ///
9548 /// This sort of thing is introduced by SROA.
9549 /// This slicing takes care not to insert overlapping loads.
9550 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
9551 bool DAGCombiner::SliceUpLoad(SDNode *N) {
9552   if (Level < AfterLegalizeDAG)
9553     return false;
9554
9555   LoadSDNode *LD = cast<LoadSDNode>(N);
9556   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9557       !LD->getValueType(0).isInteger())
9558     return false;
9559
9560   // Keep track of already used bits to detect overlapping values.
9561   // In that case, we will just abort the transformation.
9562   APInt UsedBits(LD->getValueSizeInBits(0), 0);
9563
9564   SmallVector<LoadedSlice, 4> LoadedSlices;
9565
9566   // Check if this load is used as several smaller chunks of bits.
9567   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9568   // of computation for each trunc.
9569   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9570        UI != UIEnd; ++UI) {
9571     // Skip the uses of the chain.
9572     if (UI.getUse().getResNo() != 0)
9573       continue;
9574
9575     SDNode *User = *UI;
9576     unsigned Shift = 0;
9577
9578     // Check if this is a trunc(lshr).
9579     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9580         isa<ConstantSDNode>(User->getOperand(1))) {
9581       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9582       User = *User->use_begin();
9583     }
9584
9585     // At this point, User is a Truncate, iff we encountered, trunc or
9586     // trunc(lshr).
9587     if (User->getOpcode() != ISD::TRUNCATE)
9588       return false;
9589
9590     // The width of the type must be a power of 2 and greater than 8-bits.
9591     // Otherwise the load cannot be represented in LLVM IR.
9592     // Moreover, if we shifted with a non-8-bits multiple, the slice
9593     // will be across several bytes. We do not support that.
9594     unsigned Width = User->getValueSizeInBits(0);
9595     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9596       return 0;
9597
9598     // Build the slice for this chain of computations.
9599     LoadedSlice LS(User, LD, Shift, &DAG);
9600     APInt CurrentUsedBits = LS.getUsedBits();
9601
9602     // Check if this slice overlaps with another.
9603     if ((CurrentUsedBits & UsedBits) != 0)
9604       return false;
9605     // Update the bits used globally.
9606     UsedBits |= CurrentUsedBits;
9607
9608     // Check if the new slice would be legal.
9609     if (!LS.isLegal())
9610       return false;
9611
9612     // Record the slice.
9613     LoadedSlices.push_back(LS);
9614   }
9615
9616   // Abort slicing if it does not seem to be profitable.
9617   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9618     return false;
9619
9620   ++SlicedLoads;
9621
9622   // Rewrite each chain to use an independent load.
9623   // By construction, each chain can be represented by a unique load.
9624
9625   // Prepare the argument for the new token factor for all the slices.
9626   SmallVector<SDValue, 8> ArgChains;
9627   for (SmallVectorImpl<LoadedSlice>::const_iterator
9628            LSIt = LoadedSlices.begin(),
9629            LSItEnd = LoadedSlices.end();
9630        LSIt != LSItEnd; ++LSIt) {
9631     SDValue SliceInst = LSIt->loadSlice();
9632     CombineTo(LSIt->Inst, SliceInst, true);
9633     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9634       SliceInst = SliceInst.getOperand(0);
9635     assert(SliceInst->getOpcode() == ISD::LOAD &&
9636            "It takes more than a zext to get to the loaded slice!!");
9637     ArgChains.push_back(SliceInst.getValue(1));
9638   }
9639
9640   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
9641                               ArgChains);
9642   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9643   return true;
9644 }
9645
9646 /// Check to see if V is (and load (ptr), imm), where the load is having
9647 /// specific bytes cleared out.  If so, return the byte size being masked out
9648 /// and the shift amount.
9649 static std::pair<unsigned, unsigned>
9650 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9651   std::pair<unsigned, unsigned> Result(0, 0);
9652
9653   // Check for the structure we're looking for.
9654   if (V->getOpcode() != ISD::AND ||
9655       !isa<ConstantSDNode>(V->getOperand(1)) ||
9656       !ISD::isNormalLoad(V->getOperand(0).getNode()))
9657     return Result;
9658
9659   // Check the chain and pointer.
9660   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
9661   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
9662
9663   // The store should be chained directly to the load or be an operand of a
9664   // tokenfactor.
9665   if (LD == Chain.getNode())
9666     ; // ok.
9667   else if (Chain->getOpcode() != ISD::TokenFactor)
9668     return Result; // Fail.
9669   else {
9670     bool isOk = false;
9671     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9672       if (Chain->getOperand(i).getNode() == LD) {
9673         isOk = true;
9674         break;
9675       }
9676     if (!isOk) return Result;
9677   }
9678
9679   // This only handles simple types.
9680   if (V.getValueType() != MVT::i16 &&
9681       V.getValueType() != MVT::i32 &&
9682       V.getValueType() != MVT::i64)
9683     return Result;
9684
9685   // Check the constant mask.  Invert it so that the bits being masked out are
9686   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
9687   // follow the sign bit for uniformity.
9688   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
9689   unsigned NotMaskLZ = countLeadingZeros(NotMask);
9690   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
9691   unsigned NotMaskTZ = countTrailingZeros(NotMask);
9692   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
9693   if (NotMaskLZ == 64) return Result;  // All zero mask.
9694
9695   // See if we have a continuous run of bits.  If so, we have 0*1+0*
9696   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
9697     return Result;
9698
9699   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9700   if (V.getValueType() != MVT::i64 && NotMaskLZ)
9701     NotMaskLZ -= 64-V.getValueSizeInBits();
9702
9703   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9704   switch (MaskedBytes) {
9705   case 1:
9706   case 2:
9707   case 4: break;
9708   default: return Result; // All one mask, or 5-byte mask.
9709   }
9710
9711   // Verify that the first bit starts at a multiple of mask so that the access
9712   // is aligned the same as the access width.
9713   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
9714
9715   Result.first = MaskedBytes;
9716   Result.second = NotMaskTZ/8;
9717   return Result;
9718 }
9719
9720
9721 /// Check to see if IVal is something that provides a value as specified by
9722 /// MaskInfo. If so, replace the specified store with a narrower store of
9723 /// truncated IVal.
9724 static SDNode *
9725 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9726                                 SDValue IVal, StoreSDNode *St,
9727                                 DAGCombiner *DC) {
9728   unsigned NumBytes = MaskInfo.first;
9729   unsigned ByteShift = MaskInfo.second;
9730   SelectionDAG &DAG = DC->getDAG();
9731
9732   // Check to see if IVal is all zeros in the part being masked in by the 'or'
9733   // that uses this.  If not, this is not a replacement.
9734   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9735                                   ByteShift*8, (ByteShift+NumBytes)*8);
9736   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
9737
9738   // Check that it is legal on the target to do this.  It is legal if the new
9739   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9740   // legalization.
9741   MVT VT = MVT::getIntegerVT(NumBytes*8);
9742   if (!DC->isTypeLegal(VT))
9743     return nullptr;
9744
9745   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
9746   // shifted by ByteShift and truncated down to NumBytes.
9747   if (ByteShift)
9748     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
9749                        DAG.getConstant(ByteShift*8,
9750                                     DC->getShiftAmountTy(IVal.getValueType())));
9751
9752   // Figure out the offset for the store and the alignment of the access.
9753   unsigned StOffset;
9754   unsigned NewAlign = St->getAlignment();
9755
9756   if (DAG.getTargetLoweringInfo().isLittleEndian())
9757     StOffset = ByteShift;
9758   else
9759     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
9760
9761   SDValue Ptr = St->getBasePtr();
9762   if (StOffset) {
9763     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
9764                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9765     NewAlign = MinAlign(NewAlign, StOffset);
9766   }
9767
9768   // Truncate down to the new size.
9769   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
9770
9771   ++OpsNarrowed;
9772   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
9773                       St->getPointerInfo().getWithOffset(StOffset),
9774                       false, false, NewAlign).getNode();
9775 }
9776
9777
9778 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9779 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9780 /// narrowing the load and store if it would end up being a win for performance
9781 /// or code size.
9782 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9783   StoreSDNode *ST  = cast<StoreSDNode>(N);
9784   if (ST->isVolatile())
9785     return SDValue();
9786
9787   SDValue Chain = ST->getChain();
9788   SDValue Value = ST->getValue();
9789   SDValue Ptr   = ST->getBasePtr();
9790   EVT VT = Value.getValueType();
9791
9792   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9793     return SDValue();
9794
9795   unsigned Opc = Value.getOpcode();
9796
9797   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9798   // is a byte mask indicating a consecutive number of bytes, check to see if
9799   // Y is known to provide just those bytes.  If so, we try to replace the
9800   // load + replace + store sequence with a single (narrower) store, which makes
9801   // the load dead.
9802   if (Opc == ISD::OR) {
9803     std::pair<unsigned, unsigned> MaskedLoad;
9804     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9805     if (MaskedLoad.first)
9806       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9807                                                   Value.getOperand(1), ST,this))
9808         return SDValue(NewST, 0);
9809
9810     // Or is commutative, so try swapping X and Y.
9811     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9812     if (MaskedLoad.first)
9813       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9814                                                   Value.getOperand(0), ST,this))
9815         return SDValue(NewST, 0);
9816   }
9817
9818   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9819       Value.getOperand(1).getOpcode() != ISD::Constant)
9820     return SDValue();
9821
9822   SDValue N0 = Value.getOperand(0);
9823   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9824       Chain == SDValue(N0.getNode(), 1)) {
9825     LoadSDNode *LD = cast<LoadSDNode>(N0);
9826     if (LD->getBasePtr() != Ptr ||
9827         LD->getPointerInfo().getAddrSpace() !=
9828         ST->getPointerInfo().getAddrSpace())
9829       return SDValue();
9830
9831     // Find the type to narrow it the load / op / store to.
9832     SDValue N1 = Value.getOperand(1);
9833     unsigned BitWidth = N1.getValueSizeInBits();
9834     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9835     if (Opc == ISD::AND)
9836       Imm ^= APInt::getAllOnesValue(BitWidth);
9837     if (Imm == 0 || Imm.isAllOnesValue())
9838       return SDValue();
9839     unsigned ShAmt = Imm.countTrailingZeros();
9840     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9841     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9842     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9843     // The narrowing should be profitable, the load/store operation should be
9844     // legal (or custom) and the store size should be equal to the NewVT width.
9845     while (NewBW < BitWidth &&
9846            (NewVT.getStoreSizeInBits() != NewBW ||
9847             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
9848             !TLI.isNarrowingProfitable(VT, NewVT))) {
9849       NewBW = NextPowerOf2(NewBW);
9850       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9851     }
9852     if (NewBW >= BitWidth)
9853       return SDValue();
9854
9855     // If the lsb changed does not start at the type bitwidth boundary,
9856     // start at the previous one.
9857     if (ShAmt % NewBW)
9858       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9859     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9860                                    std::min(BitWidth, ShAmt + NewBW));
9861     if ((Imm & Mask) == Imm) {
9862       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9863       if (Opc == ISD::AND)
9864         NewImm ^= APInt::getAllOnesValue(NewBW);
9865       uint64_t PtrOff = ShAmt / 8;
9866       // For big endian targets, we need to adjust the offset to the pointer to
9867       // load the correct bytes.
9868       if (TLI.isBigEndian())
9869         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9870
9871       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9872       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9873       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9874         return SDValue();
9875
9876       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9877                                    Ptr.getValueType(), Ptr,
9878                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
9879       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9880                                   LD->getChain(), NewPtr,
9881                                   LD->getPointerInfo().getWithOffset(PtrOff),
9882                                   LD->isVolatile(), LD->isNonTemporal(),
9883                                   LD->isInvariant(), NewAlign,
9884                                   LD->getAAInfo());
9885       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9886                                    DAG.getConstant(NewImm, NewVT));
9887       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9888                                    NewVal, NewPtr,
9889                                    ST->getPointerInfo().getWithOffset(PtrOff),
9890                                    false, false, NewAlign);
9891
9892       AddToWorklist(NewPtr.getNode());
9893       AddToWorklist(NewLD.getNode());
9894       AddToWorklist(NewVal.getNode());
9895       WorklistRemover DeadNodes(*this);
9896       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9897       ++OpsNarrowed;
9898       return NewST;
9899     }
9900   }
9901
9902   return SDValue();
9903 }
9904
9905 /// For a given floating point load / store pair, if the load value isn't used
9906 /// by any other operations, then consider transforming the pair to integer
9907 /// load / store operations if the target deems the transformation profitable.
9908 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9909   StoreSDNode *ST  = cast<StoreSDNode>(N);
9910   SDValue Chain = ST->getChain();
9911   SDValue Value = ST->getValue();
9912   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9913       Value.hasOneUse() &&
9914       Chain == SDValue(Value.getNode(), 1)) {
9915     LoadSDNode *LD = cast<LoadSDNode>(Value);
9916     EVT VT = LD->getMemoryVT();
9917     if (!VT.isFloatingPoint() ||
9918         VT != ST->getMemoryVT() ||
9919         LD->isNonTemporal() ||
9920         ST->isNonTemporal() ||
9921         LD->getPointerInfo().getAddrSpace() != 0 ||
9922         ST->getPointerInfo().getAddrSpace() != 0)
9923       return SDValue();
9924
9925     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9926     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9927         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9928         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9929         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9930       return SDValue();
9931
9932     unsigned LDAlign = LD->getAlignment();
9933     unsigned STAlign = ST->getAlignment();
9934     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9935     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9936     if (LDAlign < ABIAlign || STAlign < ABIAlign)
9937       return SDValue();
9938
9939     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9940                                 LD->getChain(), LD->getBasePtr(),
9941                                 LD->getPointerInfo(),
9942                                 false, false, false, LDAlign);
9943
9944     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9945                                  NewLD, ST->getBasePtr(),
9946                                  ST->getPointerInfo(),
9947                                  false, false, STAlign);
9948
9949     AddToWorklist(NewLD.getNode());
9950     AddToWorklist(NewST.getNode());
9951     WorklistRemover DeadNodes(*this);
9952     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9953     ++LdStFP2Int;
9954     return NewST;
9955   }
9956
9957   return SDValue();
9958 }
9959
9960 /// Helper struct to parse and store a memory address as base + index + offset.
9961 /// We ignore sign extensions when it is safe to do so.
9962 /// The following two expressions are not equivalent. To differentiate we need
9963 /// to store whether there was a sign extension involved in the index
9964 /// computation.
9965 ///  (load (i64 add (i64 copyfromreg %c)
9966 ///                 (i64 signextend (add (i8 load %index)
9967 ///                                      (i8 1))))
9968 /// vs
9969 ///
9970 /// (load (i64 add (i64 copyfromreg %c)
9971 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
9972 ///                                         (i32 1)))))
9973 struct BaseIndexOffset {
9974   SDValue Base;
9975   SDValue Index;
9976   int64_t Offset;
9977   bool IsIndexSignExt;
9978
9979   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9980
9981   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9982                   bool IsIndexSignExt) :
9983     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9984
9985   bool equalBaseIndex(const BaseIndexOffset &Other) {
9986     return Other.Base == Base && Other.Index == Index &&
9987       Other.IsIndexSignExt == IsIndexSignExt;
9988   }
9989
9990   /// Parses tree in Ptr for base, index, offset addresses.
9991   static BaseIndexOffset match(SDValue Ptr) {
9992     bool IsIndexSignExt = false;
9993
9994     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9995     // instruction, then it could be just the BASE or everything else we don't
9996     // know how to handle. Just use Ptr as BASE and give up.
9997     if (Ptr->getOpcode() != ISD::ADD)
9998       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9999
10000     // We know that we have at least an ADD instruction. Try to pattern match
10001     // the simple case of BASE + OFFSET.
10002     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10003       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10004       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10005                               IsIndexSignExt);
10006     }
10007
10008     // Inside a loop the current BASE pointer is calculated using an ADD and a
10009     // MUL instruction. In this case Ptr is the actual BASE pointer.
10010     // (i64 add (i64 %array_ptr)
10011     //          (i64 mul (i64 %induction_var)
10012     //                   (i64 %element_size)))
10013     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10014       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10015
10016     // Look at Base + Index + Offset cases.
10017     SDValue Base = Ptr->getOperand(0);
10018     SDValue IndexOffset = Ptr->getOperand(1);
10019
10020     // Skip signextends.
10021     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10022       IndexOffset = IndexOffset->getOperand(0);
10023       IsIndexSignExt = true;
10024     }
10025
10026     // Either the case of Base + Index (no offset) or something else.
10027     if (IndexOffset->getOpcode() != ISD::ADD)
10028       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10029
10030     // Now we have the case of Base + Index + offset.
10031     SDValue Index = IndexOffset->getOperand(0);
10032     SDValue Offset = IndexOffset->getOperand(1);
10033
10034     if (!isa<ConstantSDNode>(Offset))
10035       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10036
10037     // Ignore signextends.
10038     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10039       Index = Index->getOperand(0);
10040       IsIndexSignExt = true;
10041     } else IsIndexSignExt = false;
10042
10043     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10044     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10045   }
10046 };
10047
10048 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10049                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10050                   unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10051   // Make sure we have something to merge.
10052   if (NumElem < 2)
10053     return false;
10054
10055   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10056   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10057   unsigned EarliestNodeUsed = 0;
10058
10059   for (unsigned i=0; i < NumElem; ++i) {
10060     // Find a chain for the new wide-store operand. Notice that some
10061     // of the store nodes that we found may not be selected for inclusion
10062     // in the wide store. The chain we use needs to be the chain of the
10063     // earliest store node which is *used* and replaced by the wide store.
10064     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
10065       EarliestNodeUsed = i;
10066   }
10067
10068   // The earliest Node in the DAG.
10069   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10070   SDLoc DL(StoreNodes[0].MemNode);
10071
10072   SDValue StoredVal;
10073   if (UseVector) {
10074     // Find a legal type for the vector store.
10075     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10076     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10077     if (IsConstantSrc) {
10078       // A vector store with a constant source implies that the constant is
10079       // zero; we only handle merging stores of constant zeros because the zero
10080       // can be materialized without a load.
10081       // It may be beneficial to loosen this restriction to allow non-zero
10082       // store merging.
10083       StoredVal = DAG.getConstant(0, Ty);
10084     } else {
10085       SmallVector<SDValue, 8> Ops;
10086       for (unsigned i = 0; i < NumElem ; ++i) {
10087         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10088         SDValue Val = St->getValue();
10089         // All of the operands of a BUILD_VECTOR must have the same type.
10090         if (Val.getValueType() != MemVT)
10091           return false;
10092         Ops.push_back(Val);
10093       }
10094
10095       // Build the extracted vector elements back into a vector.
10096       StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10097     }
10098   } else {
10099     // We should always use a vector store when merging extracted vector
10100     // elements, so this path implies a store of constants.
10101     assert(IsConstantSrc && "Merged vector elements should use vector store");
10102
10103     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10104     APInt StoreInt(StoreBW, 0);
10105
10106     // Construct a single integer constant which is made of the smaller
10107     // constant inputs.
10108     bool IsLE = TLI.isLittleEndian();
10109     for (unsigned i = 0; i < NumElem ; ++i) {
10110       unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10111       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10112       SDValue Val = St->getValue();
10113       StoreInt <<= ElementSizeBytes*8;
10114       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10115         StoreInt |= C->getAPIntValue().zext(StoreBW);
10116       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10117         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10118       } else {
10119         llvm_unreachable("Invalid constant element type");
10120       }
10121     }
10122
10123     // Create the new Load and Store operations.
10124     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10125     StoredVal = DAG.getConstant(StoreInt, StoreTy);
10126   }
10127
10128   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
10129                                   FirstInChain->getBasePtr(),
10130                                   FirstInChain->getPointerInfo(),
10131                                   false, false,
10132                                   FirstInChain->getAlignment());
10133
10134   // Replace the first store with the new store
10135   CombineTo(EarliestOp, NewStore);
10136   // Erase all other stores.
10137   for (unsigned i = 0; i < NumElem ; ++i) {
10138     if (StoreNodes[i].MemNode == EarliestOp)
10139       continue;
10140     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10141     // ReplaceAllUsesWith will replace all uses that existed when it was
10142     // called, but graph optimizations may cause new ones to appear. For
10143     // example, the case in pr14333 looks like
10144     //
10145     //  St's chain -> St -> another store -> X
10146     //
10147     // And the only difference from St to the other store is the chain.
10148     // When we change it's chain to be St's chain they become identical,
10149     // get CSEed and the net result is that X is now a use of St.
10150     // Since we know that St is redundant, just iterate.
10151     while (!St->use_empty())
10152       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10153     deleteAndRecombine(St);
10154   }
10155
10156   return true;
10157 }
10158
10159 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10160   if (OptLevel == CodeGenOpt::None)
10161     return false;
10162
10163   EVT MemVT = St->getMemoryVT();
10164   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10165   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10166       Attribute::NoImplicitFloat);
10167
10168   // Don't merge vectors into wider inputs.
10169   if (MemVT.isVector() || !MemVT.isSimple())
10170     return false;
10171
10172   // Perform an early exit check. Do not bother looking at stored values that
10173   // are not constants, loads, or extracted vector elements.
10174   SDValue StoredVal = St->getValue();
10175   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10176   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10177                        isa<ConstantFPSDNode>(StoredVal);
10178   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10179
10180   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10181     return false;
10182
10183   // Only look at ends of store sequences.
10184   SDValue Chain = SDValue(St, 0);
10185   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10186     return false;
10187
10188   // This holds the base pointer, index, and the offset in bytes from the base
10189   // pointer.
10190   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10191
10192   // We must have a base and an offset.
10193   if (!BasePtr.Base.getNode())
10194     return false;
10195
10196   // Do not handle stores to undef base pointers.
10197   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10198     return false;
10199
10200   // Save the LoadSDNodes that we find in the chain.
10201   // We need to make sure that these nodes do not interfere with
10202   // any of the store nodes.
10203   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10204
10205   // Save the StoreSDNodes that we find in the chain.
10206   SmallVector<MemOpLink, 8> StoreNodes;
10207
10208   // Walk up the chain and look for nodes with offsets from the same
10209   // base pointer. Stop when reaching an instruction with a different kind
10210   // or instruction which has a different base pointer.
10211   unsigned Seq = 0;
10212   StoreSDNode *Index = St;
10213   while (Index) {
10214     // If the chain has more than one use, then we can't reorder the mem ops.
10215     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10216       break;
10217
10218     // Find the base pointer and offset for this memory node.
10219     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10220
10221     // Check that the base pointer is the same as the original one.
10222     if (!Ptr.equalBaseIndex(BasePtr))
10223       break;
10224
10225     // Check that the alignment is the same.
10226     if (Index->getAlignment() != St->getAlignment())
10227       break;
10228
10229     // The memory operands must not be volatile.
10230     if (Index->isVolatile() || Index->isIndexed())
10231       break;
10232
10233     // No truncation.
10234     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10235       if (St->isTruncatingStore())
10236         break;
10237
10238     // The stored memory type must be the same.
10239     if (Index->getMemoryVT() != MemVT)
10240       break;
10241
10242     // We do not allow unaligned stores because we want to prevent overriding
10243     // stores.
10244     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
10245       break;
10246
10247     // We found a potential memory operand to merge.
10248     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10249
10250     // Find the next memory operand in the chain. If the next operand in the
10251     // chain is a store then move up and continue the scan with the next
10252     // memory operand. If the next operand is a load save it and use alias
10253     // information to check if it interferes with anything.
10254     SDNode *NextInChain = Index->getChain().getNode();
10255     while (1) {
10256       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10257         // We found a store node. Use it for the next iteration.
10258         Index = STn;
10259         break;
10260       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10261         if (Ldn->isVolatile()) {
10262           Index = nullptr;
10263           break;
10264         }
10265
10266         // Save the load node for later. Continue the scan.
10267         AliasLoadNodes.push_back(Ldn);
10268         NextInChain = Ldn->getChain().getNode();
10269         continue;
10270       } else {
10271         Index = nullptr;
10272         break;
10273       }
10274     }
10275   }
10276
10277   // Check if there is anything to merge.
10278   if (StoreNodes.size() < 2)
10279     return false;
10280
10281   // Sort the memory operands according to their distance from the base pointer.
10282   std::sort(StoreNodes.begin(), StoreNodes.end(),
10283             [](MemOpLink LHS, MemOpLink RHS) {
10284     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10285            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10286             LHS.SequenceNum > RHS.SequenceNum);
10287   });
10288
10289   // Scan the memory operations on the chain and find the first non-consecutive
10290   // store memory address.
10291   unsigned LastConsecutiveStore = 0;
10292   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10293   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10294
10295     // Check that the addresses are consecutive starting from the second
10296     // element in the list of stores.
10297     if (i > 0) {
10298       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10299       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10300         break;
10301     }
10302
10303     bool Alias = false;
10304     // Check if this store interferes with any of the loads that we found.
10305     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10306       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10307         Alias = true;
10308         break;
10309       }
10310     // We found a load that alias with this store. Stop the sequence.
10311     if (Alias)
10312       break;
10313
10314     // Mark this node as useful.
10315     LastConsecutiveStore = i;
10316   }
10317
10318   // The node with the lowest store address.
10319   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10320
10321   // Store the constants into memory as one consecutive store.
10322   if (IsConstantSrc) {
10323     unsigned LastLegalType = 0;
10324     unsigned LastLegalVectorType = 0;
10325     bool NonZero = false;
10326     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10327       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10328       SDValue StoredVal = St->getValue();
10329
10330       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10331         NonZero |= !C->isNullValue();
10332       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10333         NonZero |= !C->getConstantFPValue()->isNullValue();
10334       } else {
10335         // Non-constant.
10336         break;
10337       }
10338
10339       // Find a legal type for the constant store.
10340       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10341       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10342       if (TLI.isTypeLegal(StoreTy))
10343         LastLegalType = i+1;
10344       // Or check whether a truncstore is legal.
10345       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10346                TargetLowering::TypePromoteInteger) {
10347         EVT LegalizedStoredValueTy =
10348           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10349         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
10350           LastLegalType = i+1;
10351       }
10352
10353       // Find a legal type for the vector store.
10354       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10355       if (TLI.isTypeLegal(Ty))
10356         LastLegalVectorType = i + 1;
10357     }
10358
10359     // We only use vectors if the constant is known to be zero and the
10360     // function is not marked with the noimplicitfloat attribute.
10361     if (NonZero || NoVectors)
10362       LastLegalVectorType = 0;
10363
10364     // Check if we found a legal integer type to store.
10365     if (LastLegalType == 0 && LastLegalVectorType == 0)
10366       return false;
10367
10368     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10369     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10370
10371     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10372                                            true, UseVector);
10373   }
10374
10375   // When extracting multiple vector elements, try to store them
10376   // in one vector store rather than a sequence of scalar stores.
10377   if (IsExtractVecEltSrc) {
10378     unsigned NumElem = 0;
10379     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10380       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10381       SDValue StoredVal = St->getValue();
10382       // This restriction could be loosened.
10383       // Bail out if any stored values are not elements extracted from a vector.
10384       // It should be possible to handle mixed sources, but load sources need
10385       // more careful handling (see the block of code below that handles
10386       // consecutive loads).
10387       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10388         return false;
10389
10390       // Find a legal type for the vector store.
10391       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10392       if (TLI.isTypeLegal(Ty))
10393         NumElem = i + 1;
10394     }
10395
10396     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10397                                            false, true);
10398   }
10399
10400   // Below we handle the case of multiple consecutive stores that
10401   // come from multiple consecutive loads. We merge them into a single
10402   // wide load and a single wide store.
10403
10404   // Look for load nodes which are used by the stored values.
10405   SmallVector<MemOpLink, 8> LoadNodes;
10406
10407   // Find acceptable loads. Loads need to have the same chain (token factor),
10408   // must not be zext, volatile, indexed, and they must be consecutive.
10409   BaseIndexOffset LdBasePtr;
10410   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10411     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10412     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10413     if (!Ld) break;
10414
10415     // Loads must only have one use.
10416     if (!Ld->hasNUsesOfValue(1, 0))
10417       break;
10418
10419     // Check that the alignment is the same as the stores.
10420     if (Ld->getAlignment() != St->getAlignment())
10421       break;
10422
10423     // The memory operands must not be volatile.
10424     if (Ld->isVolatile() || Ld->isIndexed())
10425       break;
10426
10427     // We do not accept ext loads.
10428     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10429       break;
10430
10431     // The stored memory type must be the same.
10432     if (Ld->getMemoryVT() != MemVT)
10433       break;
10434
10435     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10436     // If this is not the first ptr that we check.
10437     if (LdBasePtr.Base.getNode()) {
10438       // The base ptr must be the same.
10439       if (!LdPtr.equalBaseIndex(LdBasePtr))
10440         break;
10441     } else {
10442       // Check that all other base pointers are the same as this one.
10443       LdBasePtr = LdPtr;
10444     }
10445
10446     // We found a potential memory operand to merge.
10447     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10448   }
10449
10450   if (LoadNodes.size() < 2)
10451     return false;
10452
10453   // If we have load/store pair instructions and we only have two values,
10454   // don't bother.
10455   unsigned RequiredAlignment;
10456   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10457       St->getAlignment() >= RequiredAlignment)
10458     return false;
10459
10460   // Scan the memory operations on the chain and find the first non-consecutive
10461   // load memory address. These variables hold the index in the store node
10462   // array.
10463   unsigned LastConsecutiveLoad = 0;
10464   // This variable refers to the size and not index in the array.
10465   unsigned LastLegalVectorType = 0;
10466   unsigned LastLegalIntegerType = 0;
10467   StartAddress = LoadNodes[0].OffsetFromBase;
10468   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10469   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10470     // All loads much share the same chain.
10471     if (LoadNodes[i].MemNode->getChain() != FirstChain)
10472       break;
10473
10474     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10475     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10476       break;
10477     LastConsecutiveLoad = i;
10478
10479     // Find a legal type for the vector store.
10480     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10481     if (TLI.isTypeLegal(StoreTy))
10482       LastLegalVectorType = i + 1;
10483
10484     // Find a legal type for the integer store.
10485     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10486     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10487     if (TLI.isTypeLegal(StoreTy))
10488       LastLegalIntegerType = i + 1;
10489     // Or check whether a truncstore and extload is legal.
10490     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10491              TargetLowering::TypePromoteInteger) {
10492       EVT LegalizedStoredValueTy =
10493         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10494       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10495           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10496           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10497           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
10498         LastLegalIntegerType = i+1;
10499     }
10500   }
10501
10502   // Only use vector types if the vector type is larger than the integer type.
10503   // If they are the same, use integers.
10504   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
10505   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10506
10507   // We add +1 here because the LastXXX variables refer to location while
10508   // the NumElem refers to array/index size.
10509   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10510   NumElem = std::min(LastLegalType, NumElem);
10511
10512   if (NumElem < 2)
10513     return false;
10514
10515   // The earliest Node in the DAG.
10516   unsigned EarliestNodeUsed = 0;
10517   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10518   for (unsigned i=1; i<NumElem; ++i) {
10519     // Find a chain for the new wide-store operand. Notice that some
10520     // of the store nodes that we found may not be selected for inclusion
10521     // in the wide store. The chain we use needs to be the chain of the
10522     // earliest store node which is *used* and replaced by the wide store.
10523     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
10524       EarliestNodeUsed = i;
10525   }
10526
10527   // Find if it is better to use vectors or integers to load and store
10528   // to memory.
10529   EVT JointMemOpVT;
10530   if (UseVectorTy) {
10531     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10532   } else {
10533     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10534     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10535   }
10536
10537   SDLoc LoadDL(LoadNodes[0].MemNode);
10538   SDLoc StoreDL(StoreNodes[0].MemNode);
10539
10540   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10541   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10542                                 FirstLoad->getChain(),
10543                                 FirstLoad->getBasePtr(),
10544                                 FirstLoad->getPointerInfo(),
10545                                 false, false, false,
10546                                 FirstLoad->getAlignment());
10547
10548   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
10549                                   FirstInChain->getBasePtr(),
10550                                   FirstInChain->getPointerInfo(), false, false,
10551                                   FirstInChain->getAlignment());
10552
10553   // Replace one of the loads with the new load.
10554   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10555   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10556                                 SDValue(NewLoad.getNode(), 1));
10557
10558   // Remove the rest of the load chains.
10559   for (unsigned i = 1; i < NumElem ; ++i) {
10560     // Replace all chain users of the old load nodes with the chain of the new
10561     // load node.
10562     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
10563     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10564   }
10565
10566   // Replace the first store with the new store.
10567   CombineTo(EarliestOp, NewStore);
10568   // Erase all other stores.
10569   for (unsigned i = 0; i < NumElem ; ++i) {
10570     // Remove all Store nodes.
10571     if (StoreNodes[i].MemNode == EarliestOp)
10572       continue;
10573     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10574     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
10575     deleteAndRecombine(St);
10576   }
10577
10578   return true;
10579 }
10580
10581 SDValue DAGCombiner::visitSTORE(SDNode *N) {
10582   StoreSDNode *ST  = cast<StoreSDNode>(N);
10583   SDValue Chain = ST->getChain();
10584   SDValue Value = ST->getValue();
10585   SDValue Ptr   = ST->getBasePtr();
10586
10587   // If this is a store of a bit convert, store the input value if the
10588   // resultant store does not need a higher alignment than the original.
10589   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
10590       ST->isUnindexed()) {
10591     unsigned OrigAlign = ST->getAlignment();
10592     EVT SVT = Value.getOperand(0).getValueType();
10593     unsigned Align = TLI.getDataLayout()->
10594       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
10595     if (Align <= OrigAlign &&
10596         ((!LegalOperations && !ST->isVolatile()) ||
10597          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
10598       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
10599                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
10600                           ST->isNonTemporal(), OrigAlign,
10601                           ST->getAAInfo());
10602   }
10603
10604   // Turn 'store undef, Ptr' -> nothing.
10605   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10606     return Chain;
10607
10608   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
10609   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
10610     // NOTE: If the original store is volatile, this transform must not increase
10611     // the number of stores.  For example, on x86-32 an f64 can be stored in one
10612     // processor operation but an i64 (which is not legal) requires two.  So the
10613     // transform should not be done in this case.
10614     if (Value.getOpcode() != ISD::TargetConstantFP) {
10615       SDValue Tmp;
10616       switch (CFP->getSimpleValueType(0).SimpleTy) {
10617       default: llvm_unreachable("Unknown FP type");
10618       case MVT::f16:    // We don't do this for these yet.
10619       case MVT::f80:
10620       case MVT::f128:
10621       case MVT::ppcf128:
10622         break;
10623       case MVT::f32:
10624         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
10625             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10626           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
10627                               bitcastToAPInt().getZExtValue(), MVT::i32);
10628           return DAG.getStore(Chain, SDLoc(N), Tmp,
10629                               Ptr, ST->getMemOperand());
10630         }
10631         break;
10632       case MVT::f64:
10633         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
10634              !ST->isVolatile()) ||
10635             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
10636           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
10637                                 getZExtValue(), MVT::i64);
10638           return DAG.getStore(Chain, SDLoc(N), Tmp,
10639                               Ptr, ST->getMemOperand());
10640         }
10641
10642         if (!ST->isVolatile() &&
10643             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10644           // Many FP stores are not made apparent until after legalize, e.g. for
10645           // argument passing.  Since this is so common, custom legalize the
10646           // 64-bit integer store into two 32-bit stores.
10647           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
10648           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10649           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
10650           if (TLI.isBigEndian()) std::swap(Lo, Hi);
10651
10652           unsigned Alignment = ST->getAlignment();
10653           bool isVolatile = ST->isVolatile();
10654           bool isNonTemporal = ST->isNonTemporal();
10655           AAMDNodes AAInfo = ST->getAAInfo();
10656
10657           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
10658                                      Ptr, ST->getPointerInfo(),
10659                                      isVolatile, isNonTemporal,
10660                                      ST->getAlignment(), AAInfo);
10661           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
10662                             DAG.getConstant(4, Ptr.getValueType()));
10663           Alignment = MinAlign(Alignment, 4U);
10664           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
10665                                      Ptr, ST->getPointerInfo().getWithOffset(4),
10666                                      isVolatile, isNonTemporal,
10667                                      Alignment, AAInfo);
10668           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10669                              St0, St1);
10670         }
10671
10672         break;
10673       }
10674     }
10675   }
10676
10677   // Try to infer better alignment information than the store already has.
10678   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
10679     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10680       if (Align > ST->getAlignment())
10681         return DAG.getTruncStore(Chain, SDLoc(N), Value,
10682                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
10683                                  ST->isVolatile(), ST->isNonTemporal(), Align,
10684                                  ST->getAAInfo());
10685     }
10686   }
10687
10688   // Try transforming a pair floating point load / store ops to integer
10689   // load / store ops.
10690   SDValue NewST = TransformFPLoadStorePair(N);
10691   if (NewST.getNode())
10692     return NewST;
10693
10694   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10695                                                   : DAG.getSubtarget().useAA();
10696 #ifndef NDEBUG
10697   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10698       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10699     UseAA = false;
10700 #endif
10701   if (UseAA && ST->isUnindexed()) {
10702     // Walk up chain skipping non-aliasing memory nodes.
10703     SDValue BetterChain = FindBetterChain(N, Chain);
10704
10705     // If there is a better chain.
10706     if (Chain != BetterChain) {
10707       SDValue ReplStore;
10708
10709       // Replace the chain to avoid dependency.
10710       if (ST->isTruncatingStore()) {
10711         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
10712                                       ST->getMemoryVT(), ST->getMemOperand());
10713       } else {
10714         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
10715                                  ST->getMemOperand());
10716       }
10717
10718       // Create token to keep both nodes around.
10719       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10720                                   MVT::Other, Chain, ReplStore);
10721
10722       // Make sure the new and old chains are cleaned up.
10723       AddToWorklist(Token.getNode());
10724
10725       // Don't add users to work list.
10726       return CombineTo(N, Token, false);
10727     }
10728   }
10729
10730   // Try transforming N to an indexed store.
10731   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10732     return SDValue(N, 0);
10733
10734   // FIXME: is there such a thing as a truncating indexed store?
10735   if (ST->isTruncatingStore() && ST->isUnindexed() &&
10736       Value.getValueType().isInteger()) {
10737     // See if we can simplify the input to this truncstore with knowledge that
10738     // only the low bits are being used.  For example:
10739     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
10740     SDValue Shorter =
10741       GetDemandedBits(Value,
10742                       APInt::getLowBitsSet(
10743                         Value.getValueType().getScalarType().getSizeInBits(),
10744                         ST->getMemoryVT().getScalarType().getSizeInBits()));
10745     AddToWorklist(Value.getNode());
10746     if (Shorter.getNode())
10747       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
10748                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
10749
10750     // Otherwise, see if we can simplify the operation with
10751     // SimplifyDemandedBits, which only works if the value has a single use.
10752     if (SimplifyDemandedBits(Value,
10753                         APInt::getLowBitsSet(
10754                           Value.getValueType().getScalarType().getSizeInBits(),
10755                           ST->getMemoryVT().getScalarType().getSizeInBits())))
10756       return SDValue(N, 0);
10757   }
10758
10759   // If this is a load followed by a store to the same location, then the store
10760   // is dead/noop.
10761   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
10762     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
10763         ST->isUnindexed() && !ST->isVolatile() &&
10764         // There can't be any side effects between the load and store, such as
10765         // a call or store.
10766         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
10767       // The store is dead, remove it.
10768       return Chain;
10769     }
10770   }
10771
10772   // If this is a store followed by a store with the same value to the same
10773   // location, then the store is dead/noop.
10774   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
10775     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
10776         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
10777         ST1->isUnindexed() && !ST1->isVolatile()) {
10778       // The store is dead, remove it.
10779       return Chain;
10780     }
10781   }
10782
10783   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
10784   // truncating store.  We can do this even if this is already a truncstore.
10785   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
10786       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
10787       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
10788                             ST->getMemoryVT())) {
10789     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
10790                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
10791   }
10792
10793   // Only perform this optimization before the types are legal, because we
10794   // don't want to perform this optimization on every DAGCombine invocation.
10795   if (!LegalTypes) {
10796     bool EverChanged = false;
10797
10798     do {
10799       // There can be multiple store sequences on the same chain.
10800       // Keep trying to merge store sequences until we are unable to do so
10801       // or until we merge the last store on the chain.
10802       bool Changed = MergeConsecutiveStores(ST);
10803       EverChanged |= Changed;
10804       if (!Changed) break;
10805     } while (ST->getOpcode() != ISD::DELETED_NODE);
10806
10807     if (EverChanged)
10808       return SDValue(N, 0);
10809   }
10810
10811   return ReduceLoadOpStoreWidth(N);
10812 }
10813
10814 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
10815   SDValue InVec = N->getOperand(0);
10816   SDValue InVal = N->getOperand(1);
10817   SDValue EltNo = N->getOperand(2);
10818   SDLoc dl(N);
10819
10820   // If the inserted element is an UNDEF, just use the input vector.
10821   if (InVal.getOpcode() == ISD::UNDEF)
10822     return InVec;
10823
10824   EVT VT = InVec.getValueType();
10825
10826   // If we can't generate a legal BUILD_VECTOR, exit
10827   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10828     return SDValue();
10829
10830   // Check that we know which element is being inserted
10831   if (!isa<ConstantSDNode>(EltNo))
10832     return SDValue();
10833   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10834
10835   // Canonicalize insert_vector_elt dag nodes.
10836   // Example:
10837   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10838   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10839   //
10840   // Do this only if the child insert_vector node has one use; also
10841   // do this only if indices are both constants and Idx1 < Idx0.
10842   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10843       && isa<ConstantSDNode>(InVec.getOperand(2))) {
10844     unsigned OtherElt =
10845       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10846     if (Elt < OtherElt) {
10847       // Swap nodes.
10848       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10849                                   InVec.getOperand(0), InVal, EltNo);
10850       AddToWorklist(NewOp.getNode());
10851       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10852                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10853     }
10854   }
10855
10856   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10857   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
10858   // vector elements.
10859   SmallVector<SDValue, 8> Ops;
10860   // Do not combine these two vectors if the output vector will not replace
10861   // the input vector.
10862   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
10863     Ops.append(InVec.getNode()->op_begin(),
10864                InVec.getNode()->op_end());
10865   } else if (InVec.getOpcode() == ISD::UNDEF) {
10866     unsigned NElts = VT.getVectorNumElements();
10867     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10868   } else {
10869     return SDValue();
10870   }
10871
10872   // Insert the element
10873   if (Elt < Ops.size()) {
10874     // All the operands of BUILD_VECTOR must have the same type;
10875     // we enforce that here.
10876     EVT OpVT = Ops[0].getValueType();
10877     if (InVal.getValueType() != OpVT)
10878       InVal = OpVT.bitsGT(InVal.getValueType()) ?
10879                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10880                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10881     Ops[Elt] = InVal;
10882   }
10883
10884   // Return the new vector
10885   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
10886 }
10887
10888 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10889     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10890   EVT ResultVT = EVE->getValueType(0);
10891   EVT VecEltVT = InVecVT.getVectorElementType();
10892   unsigned Align = OriginalLoad->getAlignment();
10893   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10894       VecEltVT.getTypeForEVT(*DAG.getContext()));
10895
10896   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10897     return SDValue();
10898
10899   Align = NewAlign;
10900
10901   SDValue NewPtr = OriginalLoad->getBasePtr();
10902   SDValue Offset;
10903   EVT PtrType = NewPtr.getValueType();
10904   MachinePointerInfo MPI;
10905   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10906     int Elt = ConstEltNo->getZExtValue();
10907     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10908     if (TLI.isBigEndian())
10909       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10910     Offset = DAG.getConstant(PtrOff, PtrType);
10911     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10912   } else {
10913     Offset = DAG.getNode(
10914         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10915         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10916     if (TLI.isBigEndian())
10917       Offset = DAG.getNode(
10918           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10919           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10920     MPI = OriginalLoad->getPointerInfo();
10921   }
10922   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10923
10924   // The replacement we need to do here is a little tricky: we need to
10925   // replace an extractelement of a load with a load.
10926   // Use ReplaceAllUsesOfValuesWith to do the replacement.
10927   // Note that this replacement assumes that the extractvalue is the only
10928   // use of the load; that's okay because we don't want to perform this
10929   // transformation in other cases anyway.
10930   SDValue Load;
10931   SDValue Chain;
10932   if (ResultVT.bitsGT(VecEltVT)) {
10933     // If the result type of vextract is wider than the load, then issue an
10934     // extending load instead.
10935     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
10936                                                   VecEltVT)
10937                                    ? ISD::ZEXTLOAD
10938                                    : ISD::EXTLOAD;
10939     Load = DAG.getExtLoad(
10940         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10941         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10942         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10943     Chain = Load.getValue(1);
10944   } else {
10945     Load = DAG.getLoad(
10946         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10947         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10948         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10949     Chain = Load.getValue(1);
10950     if (ResultVT.bitsLT(VecEltVT))
10951       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10952     else
10953       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10954   }
10955   WorklistRemover DeadNodes(*this);
10956   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10957   SDValue To[] = { Load, Chain };
10958   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10959   // Since we're explicitly calling ReplaceAllUses, add the new node to the
10960   // worklist explicitly as well.
10961   AddToWorklist(Load.getNode());
10962   AddUsersToWorklist(Load.getNode()); // Add users too
10963   // Make sure to revisit this node to clean it up; it will usually be dead.
10964   AddToWorklist(EVE);
10965   ++OpsNarrowed;
10966   return SDValue(EVE, 0);
10967 }
10968
10969 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10970   // (vextract (scalar_to_vector val, 0) -> val
10971   SDValue InVec = N->getOperand(0);
10972   EVT VT = InVec.getValueType();
10973   EVT NVT = N->getValueType(0);
10974
10975   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10976     // Check if the result type doesn't match the inserted element type. A
10977     // SCALAR_TO_VECTOR may truncate the inserted element and the
10978     // EXTRACT_VECTOR_ELT may widen the extracted vector.
10979     SDValue InOp = InVec.getOperand(0);
10980     if (InOp.getValueType() != NVT) {
10981       assert(InOp.getValueType().isInteger() && NVT.isInteger());
10982       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10983     }
10984     return InOp;
10985   }
10986
10987   SDValue EltNo = N->getOperand(1);
10988   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10989
10990   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10991   // We only perform this optimization before the op legalization phase because
10992   // we may introduce new vector instructions which are not backed by TD
10993   // patterns. For example on AVX, extracting elements from a wide vector
10994   // without using extract_subvector. However, if we can find an underlying
10995   // scalar value, then we can always use that.
10996   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10997       && ConstEltNo) {
10998     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10999     int NumElem = VT.getVectorNumElements();
11000     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11001     // Find the new index to extract from.
11002     int OrigElt = SVOp->getMaskElt(Elt);
11003
11004     // Extracting an undef index is undef.
11005     if (OrigElt == -1)
11006       return DAG.getUNDEF(NVT);
11007
11008     // Select the right vector half to extract from.
11009     SDValue SVInVec;
11010     if (OrigElt < NumElem) {
11011       SVInVec = InVec->getOperand(0);
11012     } else {
11013       SVInVec = InVec->getOperand(1);
11014       OrigElt -= NumElem;
11015     }
11016
11017     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11018       SDValue InOp = SVInVec.getOperand(OrigElt);
11019       if (InOp.getValueType() != NVT) {
11020         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11021         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11022       }
11023
11024       return InOp;
11025     }
11026
11027     // FIXME: We should handle recursing on other vector shuffles and
11028     // scalar_to_vector here as well.
11029
11030     if (!LegalOperations) {
11031       EVT IndexTy = TLI.getVectorIdxTy();
11032       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
11033                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
11034     }
11035   }
11036
11037   bool BCNumEltsChanged = false;
11038   EVT ExtVT = VT.getVectorElementType();
11039   EVT LVT = ExtVT;
11040
11041   // If the result of load has to be truncated, then it's not necessarily
11042   // profitable.
11043   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11044     return SDValue();
11045
11046   if (InVec.getOpcode() == ISD::BITCAST) {
11047     // Don't duplicate a load with other uses.
11048     if (!InVec.hasOneUse())
11049       return SDValue();
11050
11051     EVT BCVT = InVec.getOperand(0).getValueType();
11052     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11053       return SDValue();
11054     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11055       BCNumEltsChanged = true;
11056     InVec = InVec.getOperand(0);
11057     ExtVT = BCVT.getVectorElementType();
11058   }
11059
11060   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11061   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11062       ISD::isNormalLoad(InVec.getNode()) &&
11063       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11064     SDValue Index = N->getOperand(1);
11065     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11066       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11067                                                            OrigLoad);
11068   }
11069
11070   // Perform only after legalization to ensure build_vector / vector_shuffle
11071   // optimizations have already been done.
11072   if (!LegalOperations) return SDValue();
11073
11074   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11075   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11076   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11077
11078   if (ConstEltNo) {
11079     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11080
11081     LoadSDNode *LN0 = nullptr;
11082     const ShuffleVectorSDNode *SVN = nullptr;
11083     if (ISD::isNormalLoad(InVec.getNode())) {
11084       LN0 = cast<LoadSDNode>(InVec);
11085     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11086                InVec.getOperand(0).getValueType() == ExtVT &&
11087                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11088       // Don't duplicate a load with other uses.
11089       if (!InVec.hasOneUse())
11090         return SDValue();
11091
11092       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11093     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11094       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11095       // =>
11096       // (load $addr+1*size)
11097
11098       // Don't duplicate a load with other uses.
11099       if (!InVec.hasOneUse())
11100         return SDValue();
11101
11102       // If the bit convert changed the number of elements, it is unsafe
11103       // to examine the mask.
11104       if (BCNumEltsChanged)
11105         return SDValue();
11106
11107       // Select the input vector, guarding against out of range extract vector.
11108       unsigned NumElems = VT.getVectorNumElements();
11109       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11110       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11111
11112       if (InVec.getOpcode() == ISD::BITCAST) {
11113         // Don't duplicate a load with other uses.
11114         if (!InVec.hasOneUse())
11115           return SDValue();
11116
11117         InVec = InVec.getOperand(0);
11118       }
11119       if (ISD::isNormalLoad(InVec.getNode())) {
11120         LN0 = cast<LoadSDNode>(InVec);
11121         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11122         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
11123       }
11124     }
11125
11126     // Make sure we found a non-volatile load and the extractelement is
11127     // the only use.
11128     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11129       return SDValue();
11130
11131     // If Idx was -1 above, Elt is going to be -1, so just return undef.
11132     if (Elt == -1)
11133       return DAG.getUNDEF(LVT);
11134
11135     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11136   }
11137
11138   return SDValue();
11139 }
11140
11141 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11142 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11143   // We perform this optimization post type-legalization because
11144   // the type-legalizer often scalarizes integer-promoted vectors.
11145   // Performing this optimization before may create bit-casts which
11146   // will be type-legalized to complex code sequences.
11147   // We perform this optimization only before the operation legalizer because we
11148   // may introduce illegal operations.
11149   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11150     return SDValue();
11151
11152   unsigned NumInScalars = N->getNumOperands();
11153   SDLoc dl(N);
11154   EVT VT = N->getValueType(0);
11155
11156   // Check to see if this is a BUILD_VECTOR of a bunch of values
11157   // which come from any_extend or zero_extend nodes. If so, we can create
11158   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11159   // optimizations. We do not handle sign-extend because we can't fill the sign
11160   // using shuffles.
11161   EVT SourceType = MVT::Other;
11162   bool AllAnyExt = true;
11163
11164   for (unsigned i = 0; i != NumInScalars; ++i) {
11165     SDValue In = N->getOperand(i);
11166     // Ignore undef inputs.
11167     if (In.getOpcode() == ISD::UNDEF) continue;
11168
11169     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
11170     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11171
11172     // Abort if the element is not an extension.
11173     if (!ZeroExt && !AnyExt) {
11174       SourceType = MVT::Other;
11175       break;
11176     }
11177
11178     // The input is a ZeroExt or AnyExt. Check the original type.
11179     EVT InTy = In.getOperand(0).getValueType();
11180
11181     // Check that all of the widened source types are the same.
11182     if (SourceType == MVT::Other)
11183       // First time.
11184       SourceType = InTy;
11185     else if (InTy != SourceType) {
11186       // Multiple income types. Abort.
11187       SourceType = MVT::Other;
11188       break;
11189     }
11190
11191     // Check if all of the extends are ANY_EXTENDs.
11192     AllAnyExt &= AnyExt;
11193   }
11194
11195   // In order to have valid types, all of the inputs must be extended from the
11196   // same source type and all of the inputs must be any or zero extend.
11197   // Scalar sizes must be a power of two.
11198   EVT OutScalarTy = VT.getScalarType();
11199   bool ValidTypes = SourceType != MVT::Other &&
11200                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11201                  isPowerOf2_32(SourceType.getSizeInBits());
11202
11203   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11204   // turn into a single shuffle instruction.
11205   if (!ValidTypes)
11206     return SDValue();
11207
11208   bool isLE = TLI.isLittleEndian();
11209   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11210   assert(ElemRatio > 1 && "Invalid element size ratio");
11211   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11212                                DAG.getConstant(0, SourceType);
11213
11214   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11215   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11216
11217   // Populate the new build_vector
11218   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11219     SDValue Cast = N->getOperand(i);
11220     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11221             Cast.getOpcode() == ISD::ZERO_EXTEND ||
11222             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11223     SDValue In;
11224     if (Cast.getOpcode() == ISD::UNDEF)
11225       In = DAG.getUNDEF(SourceType);
11226     else
11227       In = Cast->getOperand(0);
11228     unsigned Index = isLE ? (i * ElemRatio) :
11229                             (i * ElemRatio + (ElemRatio - 1));
11230
11231     assert(Index < Ops.size() && "Invalid index");
11232     Ops[Index] = In;
11233   }
11234
11235   // The type of the new BUILD_VECTOR node.
11236   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11237   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11238          "Invalid vector size");
11239   // Check if the new vector type is legal.
11240   if (!isTypeLegal(VecVT)) return SDValue();
11241
11242   // Make the new BUILD_VECTOR.
11243   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11244
11245   // The new BUILD_VECTOR node has the potential to be further optimized.
11246   AddToWorklist(BV.getNode());
11247   // Bitcast to the desired type.
11248   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11249 }
11250
11251 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11252   EVT VT = N->getValueType(0);
11253
11254   unsigned NumInScalars = N->getNumOperands();
11255   SDLoc dl(N);
11256
11257   EVT SrcVT = MVT::Other;
11258   unsigned Opcode = ISD::DELETED_NODE;
11259   unsigned NumDefs = 0;
11260
11261   for (unsigned i = 0; i != NumInScalars; ++i) {
11262     SDValue In = N->getOperand(i);
11263     unsigned Opc = In.getOpcode();
11264
11265     if (Opc == ISD::UNDEF)
11266       continue;
11267
11268     // If all scalar values are floats and converted from integers.
11269     if (Opcode == ISD::DELETED_NODE &&
11270         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11271       Opcode = Opc;
11272     }
11273
11274     if (Opc != Opcode)
11275       return SDValue();
11276
11277     EVT InVT = In.getOperand(0).getValueType();
11278
11279     // If all scalar values are typed differently, bail out. It's chosen to
11280     // simplify BUILD_VECTOR of integer types.
11281     if (SrcVT == MVT::Other)
11282       SrcVT = InVT;
11283     if (SrcVT != InVT)
11284       return SDValue();
11285     NumDefs++;
11286   }
11287
11288   // If the vector has just one element defined, it's not worth to fold it into
11289   // a vectorized one.
11290   if (NumDefs < 2)
11291     return SDValue();
11292
11293   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11294          && "Should only handle conversion from integer to float.");
11295   assert(SrcVT != MVT::Other && "Cannot determine source type!");
11296
11297   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11298
11299   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11300     return SDValue();
11301
11302   // Just because the floating-point vector type is legal does not necessarily
11303   // mean that the corresponding integer vector type is.
11304   if (!isTypeLegal(NVT))
11305     return SDValue();
11306
11307   SmallVector<SDValue, 8> Opnds;
11308   for (unsigned i = 0; i != NumInScalars; ++i) {
11309     SDValue In = N->getOperand(i);
11310
11311     if (In.getOpcode() == ISD::UNDEF)
11312       Opnds.push_back(DAG.getUNDEF(SrcVT));
11313     else
11314       Opnds.push_back(In.getOperand(0));
11315   }
11316   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11317   AddToWorklist(BV.getNode());
11318
11319   return DAG.getNode(Opcode, dl, VT, BV);
11320 }
11321
11322 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11323   unsigned NumInScalars = N->getNumOperands();
11324   SDLoc dl(N);
11325   EVT VT = N->getValueType(0);
11326
11327   // A vector built entirely of undefs is undef.
11328   if (ISD::allOperandsUndef(N))
11329     return DAG.getUNDEF(VT);
11330
11331   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11332     return V;
11333
11334   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11335     return V;
11336
11337   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11338   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11339   // at most two distinct vectors, turn this into a shuffle node.
11340
11341   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11342   if (!isTypeLegal(VT))
11343     return SDValue();
11344
11345   // May only combine to shuffle after legalize if shuffle is legal.
11346   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11347     return SDValue();
11348
11349   SDValue VecIn1, VecIn2;
11350   bool UsesZeroVector = false;
11351   for (unsigned i = 0; i != NumInScalars; ++i) {
11352     SDValue Op = N->getOperand(i);
11353     // Ignore undef inputs.
11354     if (Op.getOpcode() == ISD::UNDEF) continue;
11355
11356     // See if we can combine this build_vector into a blend with a zero vector.
11357     if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
11358         cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
11359         (Op.getOpcode() == ISD::ConstantFP &&
11360         cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11361       UsesZeroVector = true;
11362       continue;
11363     }
11364
11365     // If this input is something other than a EXTRACT_VECTOR_ELT with a
11366     // constant index, bail out.
11367     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11368         !isa<ConstantSDNode>(Op.getOperand(1))) {
11369       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11370       break;
11371     }
11372
11373     // We allow up to two distinct input vectors.
11374     SDValue ExtractedFromVec = Op.getOperand(0);
11375     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11376       continue;
11377
11378     if (!VecIn1.getNode()) {
11379       VecIn1 = ExtractedFromVec;
11380     } else if (!VecIn2.getNode() && !UsesZeroVector) {
11381       VecIn2 = ExtractedFromVec;
11382     } else {
11383       // Too many inputs.
11384       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11385       break;
11386     }
11387   }
11388
11389   // If everything is good, we can make a shuffle operation.
11390   if (VecIn1.getNode()) {
11391     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11392     SmallVector<int, 8> Mask;
11393     for (unsigned i = 0; i != NumInScalars; ++i) {
11394       unsigned Opcode = N->getOperand(i).getOpcode();
11395       if (Opcode == ISD::UNDEF) {
11396         Mask.push_back(-1);
11397         continue;
11398       }
11399
11400       // Operands can also be zero.
11401       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11402         assert(UsesZeroVector &&
11403                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11404                "Unexpected node found!");
11405         Mask.push_back(NumInScalars+i);
11406         continue;
11407       }
11408
11409       // If extracting from the first vector, just use the index directly.
11410       SDValue Extract = N->getOperand(i);
11411       SDValue ExtVal = Extract.getOperand(1);
11412       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11413       if (Extract.getOperand(0) == VecIn1) {
11414         Mask.push_back(ExtIndex);
11415         continue;
11416       }
11417
11418       // Otherwise, use InIdx + InputVecSize
11419       Mask.push_back(InNumElements + ExtIndex);
11420     }
11421
11422     // Avoid introducing illegal shuffles with zero.
11423     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11424       return SDValue();
11425
11426     // We can't generate a shuffle node with mismatched input and output types.
11427     // Attempt to transform a single input vector to the correct type.
11428     if ((VT != VecIn1.getValueType())) {
11429       // If the input vector type has a different base type to the output
11430       // vector type, bail out.
11431       EVT VTElemType = VT.getVectorElementType();
11432       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11433           (VecIn2.getNode() &&
11434            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11435         return SDValue();
11436
11437       // If the input vector is too small, widen it.
11438       // We only support widening of vectors which are half the size of the
11439       // output registers. For example XMM->YMM widening on X86 with AVX.
11440       EVT VecInT = VecIn1.getValueType();
11441       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11442         // If we only have one small input, widen it by adding undef values.
11443         if (!VecIn2.getNode())
11444           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11445                                DAG.getUNDEF(VecIn1.getValueType()));
11446         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11447           // If we have two small inputs of the same type, try to concat them.
11448           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11449           VecIn2 = SDValue(nullptr, 0);
11450         } else
11451           return SDValue();
11452       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11453         // If the input vector is too large, try to split it.
11454         // We don't support having two input vectors that are too large.
11455         // If the zero vector was used, we can not split the vector,
11456         // since we'd need 3 inputs.
11457         if (UsesZeroVector || VecIn2.getNode())
11458           return SDValue();
11459
11460         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11461           return SDValue();
11462
11463         // Try to replace VecIn1 with two extract_subvectors
11464         // No need to update the masks, they should still be correct.
11465         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11466           DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy()));
11467         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11468           DAG.getConstant(0, TLI.getVectorIdxTy()));
11469       } else
11470         return SDValue();
11471     }
11472
11473     if (UsesZeroVector)
11474       VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
11475                                 DAG.getConstantFP(0.0, VT);
11476     else
11477       // If VecIn2 is unused then change it to undef.
11478       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11479
11480     // Check that we were able to transform all incoming values to the same
11481     // type.
11482     if (VecIn2.getValueType() != VecIn1.getValueType() ||
11483         VecIn1.getValueType() != VT)
11484           return SDValue();
11485
11486     // Return the new VECTOR_SHUFFLE node.
11487     SDValue Ops[2];
11488     Ops[0] = VecIn1;
11489     Ops[1] = VecIn2;
11490     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
11491   }
11492
11493   return SDValue();
11494 }
11495
11496 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
11497   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11498   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
11499   // inputs come from at most two distinct vectors, turn this into a shuffle
11500   // node.
11501
11502   // If we only have one input vector, we don't need to do any concatenation.
11503   if (N->getNumOperands() == 1)
11504     return N->getOperand(0);
11505
11506   // Check if all of the operands are undefs.
11507   EVT VT = N->getValueType(0);
11508   if (ISD::allOperandsUndef(N))
11509     return DAG.getUNDEF(VT);
11510
11511   // Optimize concat_vectors where one of the vectors is undef.
11512   if (N->getNumOperands() == 2 &&
11513       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
11514     SDValue In = N->getOperand(0);
11515     assert(In.getValueType().isVector() && "Must concat vectors");
11516
11517     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11518     if (In->getOpcode() == ISD::BITCAST &&
11519         !In->getOperand(0)->getValueType(0).isVector()) {
11520       SDValue Scalar = In->getOperand(0);
11521       EVT SclTy = Scalar->getValueType(0);
11522
11523       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
11524         return SDValue();
11525
11526       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
11527                                  VT.getSizeInBits() / SclTy.getSizeInBits());
11528       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
11529         return SDValue();
11530
11531       SDLoc dl = SDLoc(N);
11532       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
11533       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
11534     }
11535   }
11536
11537   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
11538   // We have already tested above for an UNDEF only concatenation.
11539   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
11540   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
11541   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
11542     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
11543   };
11544   bool AllBuildVectorsOrUndefs =
11545       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
11546   if (AllBuildVectorsOrUndefs) {
11547     SmallVector<SDValue, 8> Opnds;
11548     EVT SVT = VT.getScalarType();
11549
11550     EVT MinVT = SVT;
11551     if (!SVT.isFloatingPoint()) {
11552       // If BUILD_VECTOR are from built from integer, they may have different
11553       // operand types. Get the smallest type and truncate all operands to it.
11554       bool FoundMinVT = false;
11555       for (const SDValue &Op : N->ops())
11556         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11557           EVT OpSVT = Op.getOperand(0)->getValueType(0);
11558           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
11559           FoundMinVT = true;
11560         }
11561       assert(FoundMinVT && "Concat vector type mismatch");
11562     }
11563
11564     for (const SDValue &Op : N->ops()) {
11565       EVT OpVT = Op.getValueType();
11566       unsigned NumElts = OpVT.getVectorNumElements();
11567
11568       if (ISD::UNDEF == Op.getOpcode())
11569         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
11570
11571       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11572         if (SVT.isFloatingPoint()) {
11573           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
11574           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
11575         } else {
11576           for (unsigned i = 0; i != NumElts; ++i)
11577             Opnds.push_back(
11578                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
11579         }
11580       }
11581     }
11582
11583     assert(VT.getVectorNumElements() == Opnds.size() &&
11584            "Concat vector type mismatch");
11585     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
11586   }
11587
11588   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
11589   // nodes often generate nop CONCAT_VECTOR nodes.
11590   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
11591   // place the incoming vectors at the exact same location.
11592   SDValue SingleSource = SDValue();
11593   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
11594
11595   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11596     SDValue Op = N->getOperand(i);
11597
11598     if (Op.getOpcode() == ISD::UNDEF)
11599       continue;
11600
11601     // Check if this is the identity extract:
11602     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
11603       return SDValue();
11604
11605     // Find the single incoming vector for the extract_subvector.
11606     if (SingleSource.getNode()) {
11607       if (Op.getOperand(0) != SingleSource)
11608         return SDValue();
11609     } else {
11610       SingleSource = Op.getOperand(0);
11611
11612       // Check the source type is the same as the type of the result.
11613       // If not, this concat may extend the vector, so we can not
11614       // optimize it away.
11615       if (SingleSource.getValueType() != N->getValueType(0))
11616         return SDValue();
11617     }
11618
11619     unsigned IdentityIndex = i * PartNumElem;
11620     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11621     // The extract index must be constant.
11622     if (!CS)
11623       return SDValue();
11624
11625     // Check that we are reading from the identity index.
11626     if (CS->getZExtValue() != IdentityIndex)
11627       return SDValue();
11628   }
11629
11630   if (SingleSource.getNode())
11631     return SingleSource;
11632
11633   return SDValue();
11634 }
11635
11636 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
11637   EVT NVT = N->getValueType(0);
11638   SDValue V = N->getOperand(0);
11639
11640   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
11641     // Combine:
11642     //    (extract_subvec (concat V1, V2, ...), i)
11643     // Into:
11644     //    Vi if possible
11645     // Only operand 0 is checked as 'concat' assumes all inputs of the same
11646     // type.
11647     if (V->getOperand(0).getValueType() != NVT)
11648       return SDValue();
11649     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11650     unsigned NumElems = NVT.getVectorNumElements();
11651     assert((Idx % NumElems) == 0 &&
11652            "IDX in concat is not a multiple of the result vector length.");
11653     return V->getOperand(Idx / NumElems);
11654   }
11655
11656   // Skip bitcasting
11657   if (V->getOpcode() == ISD::BITCAST)
11658     V = V.getOperand(0);
11659
11660   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
11661     SDLoc dl(N);
11662     // Handle only simple case where vector being inserted and vector
11663     // being extracted are of same type, and are half size of larger vectors.
11664     EVT BigVT = V->getOperand(0).getValueType();
11665     EVT SmallVT = V->getOperand(1).getValueType();
11666     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
11667       return SDValue();
11668
11669     // Only handle cases where both indexes are constants with the same type.
11670     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11671     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
11672
11673     if (InsIdx && ExtIdx &&
11674         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
11675         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
11676       // Combine:
11677       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
11678       // Into:
11679       //    indices are equal or bit offsets are equal => V1
11680       //    otherwise => (extract_subvec V1, ExtIdx)
11681       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
11682           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
11683         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
11684       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
11685                          DAG.getNode(ISD::BITCAST, dl,
11686                                      N->getOperand(0).getValueType(),
11687                                      V->getOperand(0)), N->getOperand(1));
11688     }
11689   }
11690
11691   return SDValue();
11692 }
11693
11694 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
11695                                                  SDValue V, SelectionDAG &DAG) {
11696   SDLoc DL(V);
11697   EVT VT = V.getValueType();
11698
11699   switch (V.getOpcode()) {
11700   default:
11701     return V;
11702
11703   case ISD::CONCAT_VECTORS: {
11704     EVT OpVT = V->getOperand(0).getValueType();
11705     int OpSize = OpVT.getVectorNumElements();
11706     SmallBitVector OpUsedElements(OpSize, false);
11707     bool FoundSimplification = false;
11708     SmallVector<SDValue, 4> NewOps;
11709     NewOps.reserve(V->getNumOperands());
11710     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
11711       SDValue Op = V->getOperand(i);
11712       bool OpUsed = false;
11713       for (int j = 0; j < OpSize; ++j)
11714         if (UsedElements[i * OpSize + j]) {
11715           OpUsedElements[j] = true;
11716           OpUsed = true;
11717         }
11718       NewOps.push_back(
11719           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
11720                  : DAG.getUNDEF(OpVT));
11721       FoundSimplification |= Op == NewOps.back();
11722       OpUsedElements.reset();
11723     }
11724     if (FoundSimplification)
11725       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
11726     return V;
11727   }
11728
11729   case ISD::INSERT_SUBVECTOR: {
11730     SDValue BaseV = V->getOperand(0);
11731     SDValue SubV = V->getOperand(1);
11732     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
11733     if (!IdxN)
11734       return V;
11735
11736     int SubSize = SubV.getValueType().getVectorNumElements();
11737     int Idx = IdxN->getZExtValue();
11738     bool SubVectorUsed = false;
11739     SmallBitVector SubUsedElements(SubSize, false);
11740     for (int i = 0; i < SubSize; ++i)
11741       if (UsedElements[i + Idx]) {
11742         SubVectorUsed = true;
11743         SubUsedElements[i] = true;
11744         UsedElements[i + Idx] = false;
11745       }
11746
11747     // Now recurse on both the base and sub vectors.
11748     SDValue SimplifiedSubV =
11749         SubVectorUsed
11750             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
11751             : DAG.getUNDEF(SubV.getValueType());
11752     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
11753     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
11754       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
11755                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
11756     return V;
11757   }
11758   }
11759 }
11760
11761 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
11762                                        SDValue N1, SelectionDAG &DAG) {
11763   EVT VT = SVN->getValueType(0);
11764   int NumElts = VT.getVectorNumElements();
11765   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
11766   for (int M : SVN->getMask())
11767     if (M >= 0 && M < NumElts)
11768       N0UsedElements[M] = true;
11769     else if (M >= NumElts)
11770       N1UsedElements[M - NumElts] = true;
11771
11772   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
11773   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
11774   if (S0 == N0 && S1 == N1)
11775     return SDValue();
11776
11777   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
11778 }
11779
11780 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
11781 // or turn a shuffle of a single concat into simpler shuffle then concat.
11782 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
11783   EVT VT = N->getValueType(0);
11784   unsigned NumElts = VT.getVectorNumElements();
11785
11786   SDValue N0 = N->getOperand(0);
11787   SDValue N1 = N->getOperand(1);
11788   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11789
11790   SmallVector<SDValue, 4> Ops;
11791   EVT ConcatVT = N0.getOperand(0).getValueType();
11792   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
11793   unsigned NumConcats = NumElts / NumElemsPerConcat;
11794
11795   // Special case: shuffle(concat(A,B)) can be more efficiently represented
11796   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
11797   // half vector elements.
11798   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
11799       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
11800                   SVN->getMask().end(), [](int i) { return i == -1; })) {
11801     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
11802                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
11803     N1 = DAG.getUNDEF(ConcatVT);
11804     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
11805   }
11806
11807   // Look at every vector that's inserted. We're looking for exact
11808   // subvector-sized copies from a concatenated vector
11809   for (unsigned I = 0; I != NumConcats; ++I) {
11810     // Make sure we're dealing with a copy.
11811     unsigned Begin = I * NumElemsPerConcat;
11812     bool AllUndef = true, NoUndef = true;
11813     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
11814       if (SVN->getMaskElt(J) >= 0)
11815         AllUndef = false;
11816       else
11817         NoUndef = false;
11818     }
11819
11820     if (NoUndef) {
11821       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
11822         return SDValue();
11823
11824       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
11825         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
11826           return SDValue();
11827
11828       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
11829       if (FirstElt < N0.getNumOperands())
11830         Ops.push_back(N0.getOperand(FirstElt));
11831       else
11832         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
11833
11834     } else if (AllUndef) {
11835       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
11836     } else { // Mixed with general masks and undefs, can't do optimization.
11837       return SDValue();
11838     }
11839   }
11840
11841   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
11842 }
11843
11844 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
11845   EVT VT = N->getValueType(0);
11846   unsigned NumElts = VT.getVectorNumElements();
11847
11848   SDValue N0 = N->getOperand(0);
11849   SDValue N1 = N->getOperand(1);
11850
11851   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
11852
11853   // Canonicalize shuffle undef, undef -> undef
11854   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
11855     return DAG.getUNDEF(VT);
11856
11857   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11858
11859   // Canonicalize shuffle v, v -> v, undef
11860   if (N0 == N1) {
11861     SmallVector<int, 8> NewMask;
11862     for (unsigned i = 0; i != NumElts; ++i) {
11863       int Idx = SVN->getMaskElt(i);
11864       if (Idx >= (int)NumElts) Idx -= NumElts;
11865       NewMask.push_back(Idx);
11866     }
11867     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
11868                                 &NewMask[0]);
11869   }
11870
11871   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
11872   if (N0.getOpcode() == ISD::UNDEF) {
11873     SmallVector<int, 8> NewMask;
11874     for (unsigned i = 0; i != NumElts; ++i) {
11875       int Idx = SVN->getMaskElt(i);
11876       if (Idx >= 0) {
11877         if (Idx >= (int)NumElts)
11878           Idx -= NumElts;
11879         else
11880           Idx = -1; // remove reference to lhs
11881       }
11882       NewMask.push_back(Idx);
11883     }
11884     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
11885                                 &NewMask[0]);
11886   }
11887
11888   // Remove references to rhs if it is undef
11889   if (N1.getOpcode() == ISD::UNDEF) {
11890     bool Changed = false;
11891     SmallVector<int, 8> NewMask;
11892     for (unsigned i = 0; i != NumElts; ++i) {
11893       int Idx = SVN->getMaskElt(i);
11894       if (Idx >= (int)NumElts) {
11895         Idx = -1;
11896         Changed = true;
11897       }
11898       NewMask.push_back(Idx);
11899     }
11900     if (Changed)
11901       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
11902   }
11903
11904   // If it is a splat, check if the argument vector is another splat or a
11905   // build_vector.
11906   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
11907     SDNode *V = N0.getNode();
11908
11909     // If this is a bit convert that changes the element type of the vector but
11910     // not the number of vector elements, look through it.  Be careful not to
11911     // look though conversions that change things like v4f32 to v2f64.
11912     if (V->getOpcode() == ISD::BITCAST) {
11913       SDValue ConvInput = V->getOperand(0);
11914       if (ConvInput.getValueType().isVector() &&
11915           ConvInput.getValueType().getVectorNumElements() == NumElts)
11916         V = ConvInput.getNode();
11917     }
11918
11919     if (V->getOpcode() == ISD::BUILD_VECTOR) {
11920       assert(V->getNumOperands() == NumElts &&
11921              "BUILD_VECTOR has wrong number of operands");
11922       SDValue Base;
11923       bool AllSame = true;
11924       for (unsigned i = 0; i != NumElts; ++i) {
11925         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11926           Base = V->getOperand(i);
11927           break;
11928         }
11929       }
11930       // Splat of <u, u, u, u>, return <u, u, u, u>
11931       if (!Base.getNode())
11932         return N0;
11933       for (unsigned i = 0; i != NumElts; ++i) {
11934         if (V->getOperand(i) != Base) {
11935           AllSame = false;
11936           break;
11937         }
11938       }
11939       // Splat of <x, x, x, x>, return <x, x, x, x>
11940       if (AllSame)
11941         return N0;
11942
11943       // Canonicalize any other splat as a build_vector.
11944       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
11945       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
11946       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
11947                                   V->getValueType(0), Ops);
11948
11949       // We may have jumped through bitcasts, so the type of the
11950       // BUILD_VECTOR may not match the type of the shuffle.
11951       if (V->getValueType(0) != VT)
11952           NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
11953       return NewBV;
11954     }
11955   }
11956
11957   // There are various patterns used to build up a vector from smaller vectors,
11958   // subvectors, or elements. Scan chains of these and replace unused insertions
11959   // or components with undef.
11960   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11961     return S;
11962
11963   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11964       Level < AfterLegalizeVectorOps &&
11965       (N1.getOpcode() == ISD::UNDEF ||
11966       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11967        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11968     SDValue V = partitionShuffleOfConcats(N, DAG);
11969
11970     if (V.getNode())
11971       return V;
11972   }
11973
11974   // If this shuffle only has a single input that is a bitcasted shuffle,
11975   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
11976   // back to their original types.
11977   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
11978       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
11979       TLI.isTypeLegal(VT)) {
11980
11981     // Peek through the bitcast only if there is one user.
11982     SDValue BC0 = N0;
11983     while (BC0.getOpcode() == ISD::BITCAST) {
11984       if (!BC0.hasOneUse())
11985         break;
11986       BC0 = BC0.getOperand(0);
11987     }
11988
11989     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
11990       if (Scale == 1)
11991         return SmallVector<int, 8>(Mask.begin(), Mask.end());
11992
11993       SmallVector<int, 8> NewMask;
11994       for (int M : Mask)
11995         for (int s = 0; s != Scale; ++s)
11996           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
11997       return NewMask;
11998     };
11999
12000     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12001       EVT SVT = VT.getScalarType();
12002       EVT InnerVT = BC0->getValueType(0);
12003       EVT InnerSVT = InnerVT.getScalarType();
12004
12005       // Determine which shuffle works with the smaller scalar type.
12006       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12007       EVT ScaleSVT = ScaleVT.getScalarType();
12008
12009       if (TLI.isTypeLegal(ScaleVT) &&
12010           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12011           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12012
12013         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12014         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12015
12016         // Scale the shuffle masks to the smaller scalar type.
12017         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12018         SmallVector<int, 8> InnerMask =
12019             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12020         SmallVector<int, 8> OuterMask =
12021             ScaleShuffleMask(SVN->getMask(), OuterScale);
12022
12023         // Merge the shuffle masks.
12024         SmallVector<int, 8> NewMask;
12025         for (int M : OuterMask)
12026           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12027
12028         // Test for shuffle mask legality over both commutations.
12029         SDValue SV0 = BC0->getOperand(0);
12030         SDValue SV1 = BC0->getOperand(1);
12031         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12032         if (!LegalMask) {
12033           for (int i = 0, e = (int)NewMask.size(); i != e; ++i) {
12034             int idx = NewMask[i];
12035             if (idx < 0)
12036               continue;
12037             else if (idx < e)
12038               NewMask[i] = idx + e;
12039             else
12040               NewMask[i] = idx - e;
12041           }
12042           std::swap(SV0, SV1);
12043           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12044         }
12045
12046         if (LegalMask) {
12047           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12048           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12049           return DAG.getNode(
12050               ISD::BITCAST, SDLoc(N), VT,
12051               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12052         }
12053       }
12054     }
12055   }
12056
12057   // Canonicalize shuffles according to rules:
12058   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12059   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12060   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12061   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12062       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12063       TLI.isTypeLegal(VT)) {
12064     // The incoming shuffle must be of the same type as the result of the
12065     // current shuffle.
12066     assert(N1->getOperand(0).getValueType() == VT &&
12067            "Shuffle types don't match");
12068
12069     SDValue SV0 = N1->getOperand(0);
12070     SDValue SV1 = N1->getOperand(1);
12071     bool HasSameOp0 = N0 == SV0;
12072     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12073     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12074       // Commute the operands of this shuffle so that next rule
12075       // will trigger.
12076       return DAG.getCommutedVectorShuffle(*SVN);
12077   }
12078
12079   // Try to fold according to rules:
12080   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12081   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12082   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12083   // Don't try to fold shuffles with illegal type.
12084   // Only fold if this shuffle is the only user of the other shuffle.
12085   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12086       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12087     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12088
12089     // The incoming shuffle must be of the same type as the result of the
12090     // current shuffle.
12091     assert(OtherSV->getOperand(0).getValueType() == VT &&
12092            "Shuffle types don't match");
12093
12094     SDValue SV0, SV1;
12095     SmallVector<int, 4> Mask;
12096     // Compute the combined shuffle mask for a shuffle with SV0 as the first
12097     // operand, and SV1 as the second operand.
12098     for (unsigned i = 0; i != NumElts; ++i) {
12099       int Idx = SVN->getMaskElt(i);
12100       if (Idx < 0) {
12101         // Propagate Undef.
12102         Mask.push_back(Idx);
12103         continue;
12104       }
12105
12106       SDValue CurrentVec;
12107       if (Idx < (int)NumElts) {
12108         // This shuffle index refers to the inner shuffle N0. Lookup the inner
12109         // shuffle mask to identify which vector is actually referenced.
12110         Idx = OtherSV->getMaskElt(Idx);
12111         if (Idx < 0) {
12112           // Propagate Undef.
12113           Mask.push_back(Idx);
12114           continue;
12115         }
12116
12117         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12118                                            : OtherSV->getOperand(1);
12119       } else {
12120         // This shuffle index references an element within N1.
12121         CurrentVec = N1;
12122       }
12123
12124       // Simple case where 'CurrentVec' is UNDEF.
12125       if (CurrentVec.getOpcode() == ISD::UNDEF) {
12126         Mask.push_back(-1);
12127         continue;
12128       }
12129
12130       // Canonicalize the shuffle index. We don't know yet if CurrentVec
12131       // will be the first or second operand of the combined shuffle.
12132       Idx = Idx % NumElts;
12133       if (!SV0.getNode() || SV0 == CurrentVec) {
12134         // Ok. CurrentVec is the left hand side.
12135         // Update the mask accordingly.
12136         SV0 = CurrentVec;
12137         Mask.push_back(Idx);
12138         continue;
12139       }
12140
12141       // Bail out if we cannot convert the shuffle pair into a single shuffle.
12142       if (SV1.getNode() && SV1 != CurrentVec)
12143         return SDValue();
12144
12145       // Ok. CurrentVec is the right hand side.
12146       // Update the mask accordingly.
12147       SV1 = CurrentVec;
12148       Mask.push_back(Idx + NumElts);
12149     }
12150
12151     // Check if all indices in Mask are Undef. In case, propagate Undef.
12152     bool isUndefMask = true;
12153     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12154       isUndefMask &= Mask[i] < 0;
12155
12156     if (isUndefMask)
12157       return DAG.getUNDEF(VT);
12158
12159     if (!SV0.getNode())
12160       SV0 = DAG.getUNDEF(VT);
12161     if (!SV1.getNode())
12162       SV1 = DAG.getUNDEF(VT);
12163
12164     // Avoid introducing shuffles with illegal mask.
12165     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12166       // Compute the commuted shuffle mask and test again.
12167       for (unsigned i = 0; i != NumElts; ++i) {
12168         int idx = Mask[i];
12169         if (idx < 0)
12170           continue;
12171         else if (idx < (int)NumElts)
12172           Mask[i] = idx + NumElts;
12173         else
12174           Mask[i] = idx - NumElts;
12175       }
12176
12177       if (!TLI.isShuffleMaskLegal(Mask, VT))
12178         return SDValue();
12179
12180       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12181       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12182       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12183       std::swap(SV0, SV1);
12184     }
12185
12186     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12187     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12188     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12189     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12190   }
12191
12192   return SDValue();
12193 }
12194
12195 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12196   SDValue InVal = N->getOperand(0);
12197   EVT VT = N->getValueType(0);
12198
12199   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12200   // with a VECTOR_SHUFFLE.
12201   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12202     SDValue InVec = InVal->getOperand(0);
12203     SDValue EltNo = InVal->getOperand(1);
12204
12205     // FIXME: We could support implicit truncation if the shuffle can be
12206     // scaled to a smaller vector scalar type.
12207     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12208     if (C0 && VT == InVec.getValueType() &&
12209         VT.getScalarType() == InVal.getValueType()) {
12210       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12211       int Elt = C0->getZExtValue();
12212       NewMask[0] = Elt;
12213
12214       if (TLI.isShuffleMaskLegal(NewMask, VT))
12215         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12216                                     NewMask);
12217     }
12218   }
12219
12220   return SDValue();
12221 }
12222
12223 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12224   SDValue N0 = N->getOperand(0);
12225   SDValue N2 = N->getOperand(2);
12226
12227   // If the input vector is a concatenation, and the insert replaces
12228   // one of the halves, we can optimize into a single concat_vectors.
12229   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12230       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12231     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12232     EVT VT = N->getValueType(0);
12233
12234     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12235     // (concat_vectors Z, Y)
12236     if (InsIdx == 0)
12237       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12238                          N->getOperand(1), N0.getOperand(1));
12239
12240     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12241     // (concat_vectors X, Z)
12242     if (InsIdx == VT.getVectorNumElements()/2)
12243       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12244                          N0.getOperand(0), N->getOperand(1));
12245   }
12246
12247   return SDValue();
12248 }
12249
12250 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12251 /// with the destination vector and a zero vector.
12252 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12253 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
12254 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12255   EVT VT = N->getValueType(0);
12256   SDLoc dl(N);
12257   SDValue LHS = N->getOperand(0);
12258   SDValue RHS = N->getOperand(1);
12259   if (N->getOpcode() == ISD::AND) {
12260     if (RHS.getOpcode() == ISD::BITCAST)
12261       RHS = RHS.getOperand(0);
12262     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12263       SmallVector<int, 8> Indices;
12264       unsigned NumElts = RHS.getNumOperands();
12265       for (unsigned i = 0; i != NumElts; ++i) {
12266         SDValue Elt = RHS.getOperand(i);
12267         if (!isa<ConstantSDNode>(Elt))
12268           return SDValue();
12269
12270         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
12271           Indices.push_back(i);
12272         else if (cast<ConstantSDNode>(Elt)->isNullValue())
12273           Indices.push_back(NumElts+i);
12274         else
12275           return SDValue();
12276       }
12277
12278       // Let's see if the target supports this vector_shuffle and make sure
12279       // we're not running after operation legalization where it may have
12280       // custom lowered the vector shuffles.
12281       EVT RVT = RHS.getValueType();
12282       if (LegalOperations || !TLI.isVectorClearMaskLegal(Indices, RVT))
12283         return SDValue();
12284
12285       // Return the new VECTOR_SHUFFLE node.
12286       EVT EltVT = RVT.getVectorElementType();
12287       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12288                                      DAG.getConstant(0, EltVT));
12289       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
12290       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12291       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12292       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12293     }
12294   }
12295
12296   return SDValue();
12297 }
12298
12299 /// Visit a binary vector operation, like ADD.
12300 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12301   assert(N->getValueType(0).isVector() &&
12302          "SimplifyVBinOp only works on vectors!");
12303
12304   SDValue LHS = N->getOperand(0);
12305   SDValue RHS = N->getOperand(1);
12306
12307   if (SDValue Shuffle = XformToShuffleWithZero(N))
12308     return Shuffle;
12309
12310   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12311   // this operation.
12312   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12313       RHS.getOpcode() == ISD::BUILD_VECTOR) {
12314     // Check if both vectors are constants. If not bail out.
12315     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12316           cast<BuildVectorSDNode>(RHS)->isConstant()))
12317       return SDValue();
12318
12319     SmallVector<SDValue, 8> Ops;
12320     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12321       SDValue LHSOp = LHS.getOperand(i);
12322       SDValue RHSOp = RHS.getOperand(i);
12323
12324       // Can't fold divide by zero.
12325       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12326           N->getOpcode() == ISD::FDIV) {
12327         if ((RHSOp.getOpcode() == ISD::Constant &&
12328              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
12329             (RHSOp.getOpcode() == ISD::ConstantFP &&
12330              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12331           break;
12332       }
12333
12334       EVT VT = LHSOp.getValueType();
12335       EVT RVT = RHSOp.getValueType();
12336       if (RVT != VT) {
12337         // Integer BUILD_VECTOR operands may have types larger than the element
12338         // size (e.g., when the element type is not legal).  Prior to type
12339         // legalization, the types may not match between the two BUILD_VECTORS.
12340         // Truncate one of the operands to make them match.
12341         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12342           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12343         } else {
12344           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12345           VT = RVT;
12346         }
12347       }
12348       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12349                                    LHSOp, RHSOp);
12350       if (FoldOp.getOpcode() != ISD::UNDEF &&
12351           FoldOp.getOpcode() != ISD::Constant &&
12352           FoldOp.getOpcode() != ISD::ConstantFP)
12353         break;
12354       Ops.push_back(FoldOp);
12355       AddToWorklist(FoldOp.getNode());
12356     }
12357
12358     if (Ops.size() == LHS.getNumOperands())
12359       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12360   }
12361
12362   // Type legalization might introduce new shuffles in the DAG.
12363   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12364   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
12365   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12366       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12367       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12368       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12369     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12370     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12371
12372     if (SVN0->getMask().equals(SVN1->getMask())) {
12373       EVT VT = N->getValueType(0);
12374       SDValue UndefVector = LHS.getOperand(1);
12375       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12376                                      LHS.getOperand(0), RHS.getOperand(0));
12377       AddUsersToWorklist(N);
12378       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
12379                                   &SVN0->getMask()[0]);
12380     }
12381   }
12382
12383   return SDValue();
12384 }
12385
12386 /// Visit a binary vector operation, like FABS/FNEG.
12387 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
12388   assert(N->getValueType(0).isVector() &&
12389          "SimplifyVUnaryOp only works on vectors!");
12390
12391   SDValue N0 = N->getOperand(0);
12392
12393   if (N0.getOpcode() != ISD::BUILD_VECTOR)
12394     return SDValue();
12395
12396   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
12397   SmallVector<SDValue, 8> Ops;
12398   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
12399     SDValue Op = N0.getOperand(i);
12400     if (Op.getOpcode() != ISD::UNDEF &&
12401         Op.getOpcode() != ISD::ConstantFP)
12402       break;
12403     EVT EltVT = Op.getValueType();
12404     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
12405     if (FoldOp.getOpcode() != ISD::UNDEF &&
12406         FoldOp.getOpcode() != ISD::ConstantFP)
12407       break;
12408     Ops.push_back(FoldOp);
12409     AddToWorklist(FoldOp.getNode());
12410   }
12411
12412   if (Ops.size() != N0.getNumOperands())
12413     return SDValue();
12414
12415   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
12416 }
12417
12418 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
12419                                     SDValue N1, SDValue N2){
12420   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
12421
12422   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
12423                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
12424
12425   // If we got a simplified select_cc node back from SimplifySelectCC, then
12426   // break it down into a new SETCC node, and a new SELECT node, and then return
12427   // the SELECT node, since we were called with a SELECT node.
12428   if (SCC.getNode()) {
12429     // Check to see if we got a select_cc back (to turn into setcc/select).
12430     // Otherwise, just return whatever node we got back, like fabs.
12431     if (SCC.getOpcode() == ISD::SELECT_CC) {
12432       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
12433                                   N0.getValueType(),
12434                                   SCC.getOperand(0), SCC.getOperand(1),
12435                                   SCC.getOperand(4));
12436       AddToWorklist(SETCC.getNode());
12437       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
12438                            SCC.getOperand(2), SCC.getOperand(3));
12439     }
12440
12441     return SCC;
12442   }
12443   return SDValue();
12444 }
12445
12446 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
12447 /// being selected between, see if we can simplify the select.  Callers of this
12448 /// should assume that TheSelect is deleted if this returns true.  As such, they
12449 /// should return the appropriate thing (e.g. the node) back to the top-level of
12450 /// the DAG combiner loop to avoid it being looked at.
12451 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
12452                                     SDValue RHS) {
12453
12454   // Cannot simplify select with vector condition
12455   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
12456
12457   // If this is a select from two identical things, try to pull the operation
12458   // through the select.
12459   if (LHS.getOpcode() != RHS.getOpcode() ||
12460       !LHS.hasOneUse() || !RHS.hasOneUse())
12461     return false;
12462
12463   // If this is a load and the token chain is identical, replace the select
12464   // of two loads with a load through a select of the address to load from.
12465   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
12466   // constants have been dropped into the constant pool.
12467   if (LHS.getOpcode() == ISD::LOAD) {
12468     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
12469     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
12470
12471     // Token chains must be identical.
12472     if (LHS.getOperand(0) != RHS.getOperand(0) ||
12473         // Do not let this transformation reduce the number of volatile loads.
12474         LLD->isVolatile() || RLD->isVolatile() ||
12475         // If this is an EXTLOAD, the VT's must match.
12476         LLD->getMemoryVT() != RLD->getMemoryVT() ||
12477         // If this is an EXTLOAD, the kind of extension must match.
12478         (LLD->getExtensionType() != RLD->getExtensionType() &&
12479          // The only exception is if one of the extensions is anyext.
12480          LLD->getExtensionType() != ISD::EXTLOAD &&
12481          RLD->getExtensionType() != ISD::EXTLOAD) ||
12482         // FIXME: this discards src value information.  This is
12483         // over-conservative. It would be beneficial to be able to remember
12484         // both potential memory locations.  Since we are discarding
12485         // src value info, don't do the transformation if the memory
12486         // locations are not in the default address space.
12487         LLD->getPointerInfo().getAddrSpace() != 0 ||
12488         RLD->getPointerInfo().getAddrSpace() != 0 ||
12489         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
12490                                       LLD->getBasePtr().getValueType()))
12491       return false;
12492
12493     // Check that the select condition doesn't reach either load.  If so,
12494     // folding this will induce a cycle into the DAG.  If not, this is safe to
12495     // xform, so create a select of the addresses.
12496     SDValue Addr;
12497     if (TheSelect->getOpcode() == ISD::SELECT) {
12498       SDNode *CondNode = TheSelect->getOperand(0).getNode();
12499       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
12500           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
12501         return false;
12502       // The loads must not depend on one another.
12503       if (LLD->isPredecessorOf(RLD) ||
12504           RLD->isPredecessorOf(LLD))
12505         return false;
12506       Addr = DAG.getSelect(SDLoc(TheSelect),
12507                            LLD->getBasePtr().getValueType(),
12508                            TheSelect->getOperand(0), LLD->getBasePtr(),
12509                            RLD->getBasePtr());
12510     } else {  // Otherwise SELECT_CC
12511       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
12512       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
12513
12514       if ((LLD->hasAnyUseOfValue(1) &&
12515            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
12516           (RLD->hasAnyUseOfValue(1) &&
12517            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
12518         return false;
12519
12520       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
12521                          LLD->getBasePtr().getValueType(),
12522                          TheSelect->getOperand(0),
12523                          TheSelect->getOperand(1),
12524                          LLD->getBasePtr(), RLD->getBasePtr(),
12525                          TheSelect->getOperand(4));
12526     }
12527
12528     SDValue Load;
12529     // It is safe to replace the two loads if they have different alignments,
12530     // but the new load must be the minimum (most restrictive) alignment of the
12531     // inputs.
12532     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
12533     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
12534     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
12535       Load = DAG.getLoad(TheSelect->getValueType(0),
12536                          SDLoc(TheSelect),
12537                          // FIXME: Discards pointer and AA info.
12538                          LLD->getChain(), Addr, MachinePointerInfo(),
12539                          LLD->isVolatile(), LLD->isNonTemporal(),
12540                          isInvariant, Alignment);
12541     } else {
12542       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
12543                             RLD->getExtensionType() : LLD->getExtensionType(),
12544                             SDLoc(TheSelect),
12545                             TheSelect->getValueType(0),
12546                             // FIXME: Discards pointer and AA info.
12547                             LLD->getChain(), Addr, MachinePointerInfo(),
12548                             LLD->getMemoryVT(), LLD->isVolatile(),
12549                             LLD->isNonTemporal(), isInvariant, Alignment);
12550     }
12551
12552     // Users of the select now use the result of the load.
12553     CombineTo(TheSelect, Load);
12554
12555     // Users of the old loads now use the new load's chain.  We know the
12556     // old-load value is dead now.
12557     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
12558     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
12559     return true;
12560   }
12561
12562   return false;
12563 }
12564
12565 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
12566 /// where 'cond' is the comparison specified by CC.
12567 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
12568                                       SDValue N2, SDValue N3,
12569                                       ISD::CondCode CC, bool NotExtCompare) {
12570   // (x ? y : y) -> y.
12571   if (N2 == N3) return N2;
12572
12573   EVT VT = N2.getValueType();
12574   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
12575   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
12576   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
12577
12578   // Determine if the condition we're dealing with is constant
12579   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
12580                               N0, N1, CC, DL, false);
12581   if (SCC.getNode()) AddToWorklist(SCC.getNode());
12582   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
12583
12584   // fold select_cc true, x, y -> x
12585   if (SCCC && !SCCC->isNullValue())
12586     return N2;
12587   // fold select_cc false, x, y -> y
12588   if (SCCC && SCCC->isNullValue())
12589     return N3;
12590
12591   // Check to see if we can simplify the select into an fabs node
12592   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
12593     // Allow either -0.0 or 0.0
12594     if (CFP->getValueAPF().isZero()) {
12595       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
12596       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
12597           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
12598           N2 == N3.getOperand(0))
12599         return DAG.getNode(ISD::FABS, DL, VT, N0);
12600
12601       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
12602       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
12603           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
12604           N2.getOperand(0) == N3)
12605         return DAG.getNode(ISD::FABS, DL, VT, N3);
12606     }
12607   }
12608
12609   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
12610   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
12611   // in it.  This is a win when the constant is not otherwise available because
12612   // it replaces two constant pool loads with one.  We only do this if the FP
12613   // type is known to be legal, because if it isn't, then we are before legalize
12614   // types an we want the other legalization to happen first (e.g. to avoid
12615   // messing with soft float) and if the ConstantFP is not legal, because if
12616   // it is legal, we may not need to store the FP constant in a constant pool.
12617   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
12618     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
12619       if (TLI.isTypeLegal(N2.getValueType()) &&
12620           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
12621                TargetLowering::Legal &&
12622            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
12623            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
12624           // If both constants have multiple uses, then we won't need to do an
12625           // extra load, they are likely around in registers for other users.
12626           (TV->hasOneUse() || FV->hasOneUse())) {
12627         Constant *Elts[] = {
12628           const_cast<ConstantFP*>(FV->getConstantFPValue()),
12629           const_cast<ConstantFP*>(TV->getConstantFPValue())
12630         };
12631         Type *FPTy = Elts[0]->getType();
12632         const DataLayout &TD = *TLI.getDataLayout();
12633
12634         // Create a ConstantArray of the two constants.
12635         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
12636         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
12637                                             TD.getPrefTypeAlignment(FPTy));
12638         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12639
12640         // Get the offsets to the 0 and 1 element of the array so that we can
12641         // select between them.
12642         SDValue Zero = DAG.getIntPtrConstant(0);
12643         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
12644         SDValue One = DAG.getIntPtrConstant(EltSize);
12645
12646         SDValue Cond = DAG.getSetCC(DL,
12647                                     getSetCCResultType(N0.getValueType()),
12648                                     N0, N1, CC);
12649         AddToWorklist(Cond.getNode());
12650         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
12651                                           Cond, One, Zero);
12652         AddToWorklist(CstOffset.getNode());
12653         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
12654                             CstOffset);
12655         AddToWorklist(CPIdx.getNode());
12656         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
12657                            MachinePointerInfo::getConstantPool(), false,
12658                            false, false, Alignment);
12659
12660       }
12661     }
12662
12663   // Check to see if we can perform the "gzip trick", transforming
12664   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
12665   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
12666       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
12667        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
12668     EVT XType = N0.getValueType();
12669     EVT AType = N2.getValueType();
12670     if (XType.bitsGE(AType)) {
12671       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
12672       // single-bit constant.
12673       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
12674         unsigned ShCtV = N2C->getAPIntValue().logBase2();
12675         ShCtV = XType.getSizeInBits()-ShCtV-1;
12676         SDValue ShCt = DAG.getConstant(ShCtV,
12677                                        getShiftAmountTy(N0.getValueType()));
12678         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
12679                                     XType, N0, ShCt);
12680         AddToWorklist(Shift.getNode());
12681
12682         if (XType.bitsGT(AType)) {
12683           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12684           AddToWorklist(Shift.getNode());
12685         }
12686
12687         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12688       }
12689
12690       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
12691                                   XType, N0,
12692                                   DAG.getConstant(XType.getSizeInBits()-1,
12693                                          getShiftAmountTy(N0.getValueType())));
12694       AddToWorklist(Shift.getNode());
12695
12696       if (XType.bitsGT(AType)) {
12697         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12698         AddToWorklist(Shift.getNode());
12699       }
12700
12701       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12702     }
12703   }
12704
12705   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
12706   // where y is has a single bit set.
12707   // A plaintext description would be, we can turn the SELECT_CC into an AND
12708   // when the condition can be materialized as an all-ones register.  Any
12709   // single bit-test can be materialized as an all-ones register with
12710   // shift-left and shift-right-arith.
12711   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
12712       N0->getValueType(0) == VT &&
12713       N1C && N1C->isNullValue() &&
12714       N2C && N2C->isNullValue()) {
12715     SDValue AndLHS = N0->getOperand(0);
12716     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12717     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
12718       // Shift the tested bit over the sign bit.
12719       APInt AndMask = ConstAndRHS->getAPIntValue();
12720       SDValue ShlAmt =
12721         DAG.getConstant(AndMask.countLeadingZeros(),
12722                         getShiftAmountTy(AndLHS.getValueType()));
12723       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
12724
12725       // Now arithmetic right shift it all the way over, so the result is either
12726       // all-ones, or zero.
12727       SDValue ShrAmt =
12728         DAG.getConstant(AndMask.getBitWidth()-1,
12729                         getShiftAmountTy(Shl.getValueType()));
12730       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
12731
12732       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
12733     }
12734   }
12735
12736   // fold select C, 16, 0 -> shl C, 4
12737   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
12738       TLI.getBooleanContents(N0.getValueType()) ==
12739           TargetLowering::ZeroOrOneBooleanContent) {
12740
12741     // If the caller doesn't want us to simplify this into a zext of a compare,
12742     // don't do it.
12743     if (NotExtCompare && N2C->getAPIntValue() == 1)
12744       return SDValue();
12745
12746     // Get a SetCC of the condition
12747     // NOTE: Don't create a SETCC if it's not legal on this target.
12748     if (!LegalOperations ||
12749         TLI.isOperationLegal(ISD::SETCC,
12750           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
12751       SDValue Temp, SCC;
12752       // cast from setcc result type to select result type
12753       if (LegalTypes) {
12754         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
12755                             N0, N1, CC);
12756         if (N2.getValueType().bitsLT(SCC.getValueType()))
12757           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
12758                                         N2.getValueType());
12759         else
12760           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12761                              N2.getValueType(), SCC);
12762       } else {
12763         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
12764         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12765                            N2.getValueType(), SCC);
12766       }
12767
12768       AddToWorklist(SCC.getNode());
12769       AddToWorklist(Temp.getNode());
12770
12771       if (N2C->getAPIntValue() == 1)
12772         return Temp;
12773
12774       // shl setcc result by log2 n2c
12775       return DAG.getNode(
12776           ISD::SHL, DL, N2.getValueType(), Temp,
12777           DAG.getConstant(N2C->getAPIntValue().logBase2(),
12778                           getShiftAmountTy(Temp.getValueType())));
12779     }
12780   }
12781
12782   // Check to see if this is the equivalent of setcc
12783   // FIXME: Turn all of these into setcc if setcc if setcc is legal
12784   // otherwise, go ahead with the folds.
12785   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
12786     EVT XType = N0.getValueType();
12787     if (!LegalOperations ||
12788         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
12789       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
12790       if (Res.getValueType() != VT)
12791         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
12792       return Res;
12793     }
12794
12795     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
12796     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
12797         (!LegalOperations ||
12798          TLI.isOperationLegal(ISD::CTLZ, XType))) {
12799       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
12800       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
12801                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
12802                                        getShiftAmountTy(Ctlz.getValueType())));
12803     }
12804     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
12805     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
12806       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
12807                                   XType, DAG.getConstant(0, XType), N0);
12808       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
12809       return DAG.getNode(ISD::SRL, DL, XType,
12810                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
12811                          DAG.getConstant(XType.getSizeInBits()-1,
12812                                          getShiftAmountTy(XType)));
12813     }
12814     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
12815     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
12816       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
12817                                  DAG.getConstant(XType.getSizeInBits()-1,
12818                                          getShiftAmountTy(N0.getValueType())));
12819       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
12820     }
12821   }
12822
12823   // Check to see if this is an integer abs.
12824   // select_cc setg[te] X,  0,  X, -X ->
12825   // select_cc setgt    X, -1,  X, -X ->
12826   // select_cc setl[te] X,  0, -X,  X ->
12827   // select_cc setlt    X,  1, -X,  X ->
12828   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
12829   if (N1C) {
12830     ConstantSDNode *SubC = nullptr;
12831     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
12832          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
12833         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
12834       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
12835     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
12836               (N1C->isOne() && CC == ISD::SETLT)) &&
12837              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
12838       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
12839
12840     EVT XType = N0.getValueType();
12841     if (SubC && SubC->isNullValue() && XType.isInteger()) {
12842       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
12843                                   N0,
12844                                   DAG.getConstant(XType.getSizeInBits()-1,
12845                                          getShiftAmountTy(N0.getValueType())));
12846       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
12847                                 XType, N0, Shift);
12848       AddToWorklist(Shift.getNode());
12849       AddToWorklist(Add.getNode());
12850       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
12851     }
12852   }
12853
12854   return SDValue();
12855 }
12856
12857 /// This is a stub for TargetLowering::SimplifySetCC.
12858 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
12859                                    SDValue N1, ISD::CondCode Cond,
12860                                    SDLoc DL, bool foldBooleans) {
12861   TargetLowering::DAGCombinerInfo
12862     DagCombineInfo(DAG, Level, false, this);
12863   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
12864 }
12865
12866 /// Given an ISD::SDIV node expressing a divide by constant, return
12867 /// a DAG expression to select that will generate the same value by multiplying
12868 /// by a magic number.
12869 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12870 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
12871   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12872   if (!C)
12873     return SDValue();
12874
12875   // Avoid division by zero.
12876   if (!C->getAPIntValue())
12877     return SDValue();
12878
12879   std::vector<SDNode*> Built;
12880   SDValue S =
12881       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12882
12883   for (SDNode *N : Built)
12884     AddToWorklist(N);
12885   return S;
12886 }
12887
12888 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
12889 /// DAG expression that will generate the same value by right shifting.
12890 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
12891   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12892   if (!C)
12893     return SDValue();
12894
12895   // Avoid division by zero.
12896   if (!C->getAPIntValue())
12897     return SDValue();
12898
12899   std::vector<SDNode *> Built;
12900   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
12901
12902   for (SDNode *N : Built)
12903     AddToWorklist(N);
12904   return S;
12905 }
12906
12907 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
12908 /// expression that will generate the same value by multiplying by a magic
12909 /// number.
12910 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12911 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
12912   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12913   if (!C)
12914     return SDValue();
12915
12916   // Avoid division by zero.
12917   if (!C->getAPIntValue())
12918     return SDValue();
12919
12920   std::vector<SDNode*> Built;
12921   SDValue S =
12922       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12923
12924   for (SDNode *N : Built)
12925     AddToWorklist(N);
12926   return S;
12927 }
12928
12929 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
12930   if (Level >= AfterLegalizeDAG)
12931     return SDValue();
12932
12933   // Expose the DAG combiner to the target combiner implementations.
12934   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12935
12936   unsigned Iterations = 0;
12937   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
12938     if (Iterations) {
12939       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12940       // For the reciprocal, we need to find the zero of the function:
12941       //   F(X) = A X - 1 [which has a zero at X = 1/A]
12942       //     =>
12943       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
12944       //     does not require additional intermediate precision]
12945       EVT VT = Op.getValueType();
12946       SDLoc DL(Op);
12947       SDValue FPOne = DAG.getConstantFP(1.0, VT);
12948
12949       AddToWorklist(Est.getNode());
12950
12951       // Newton iterations: Est = Est + Est (1 - Arg * Est)
12952       for (unsigned i = 0; i < Iterations; ++i) {
12953         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
12954         AddToWorklist(NewEst.getNode());
12955
12956         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
12957         AddToWorklist(NewEst.getNode());
12958
12959         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12960         AddToWorklist(NewEst.getNode());
12961
12962         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
12963         AddToWorklist(Est.getNode());
12964       }
12965     }
12966     return Est;
12967   }
12968
12969   return SDValue();
12970 }
12971
12972 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12973 /// For the reciprocal sqrt, we need to find the zero of the function:
12974 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12975 ///     =>
12976 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12977 /// As a result, we precompute A/2 prior to the iteration loop.
12978 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
12979                                           unsigned Iterations) {
12980   EVT VT = Arg.getValueType();
12981   SDLoc DL(Arg);
12982   SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
12983
12984   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12985   // this entire sequence requires only one FP constant.
12986   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12987   AddToWorklist(HalfArg.getNode());
12988
12989   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12990   AddToWorklist(HalfArg.getNode());
12991
12992   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12993   for (unsigned i = 0; i < Iterations; ++i) {
12994     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12995     AddToWorklist(NewEst.getNode());
12996
12997     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12998     AddToWorklist(NewEst.getNode());
12999
13000     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13001     AddToWorklist(NewEst.getNode());
13002
13003     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13004     AddToWorklist(Est.getNode());
13005   }
13006   return Est;
13007 }
13008
13009 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13010 /// For the reciprocal sqrt, we need to find the zero of the function:
13011 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13012 ///     =>
13013 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13014 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13015                                           unsigned Iterations) {
13016   EVT VT = Arg.getValueType();
13017   SDLoc DL(Arg);
13018   SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
13019   SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
13020
13021   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13022   for (unsigned i = 0; i < Iterations; ++i) {
13023     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13024     AddToWorklist(HalfEst.getNode());
13025
13026     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13027     AddToWorklist(Est.getNode());
13028
13029     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13030     AddToWorklist(Est.getNode());
13031
13032     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13033     AddToWorklist(Est.getNode());
13034
13035     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13036     AddToWorklist(Est.getNode());
13037   }
13038   return Est;
13039 }
13040
13041 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13042   if (Level >= AfterLegalizeDAG)
13043     return SDValue();
13044
13045   // Expose the DAG combiner to the target combiner implementations.
13046   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13047   unsigned Iterations = 0;
13048   bool UseOneConstNR = false;
13049   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13050     AddToWorklist(Est.getNode());
13051     if (Iterations) {
13052       Est = UseOneConstNR ?
13053         BuildRsqrtNROneConst(Op, Est, Iterations) :
13054         BuildRsqrtNRTwoConst(Op, Est, Iterations);
13055     }
13056     return Est;
13057   }
13058
13059   return SDValue();
13060 }
13061
13062 /// Return true if base is a frame index, which is known not to alias with
13063 /// anything but itself.  Provides base object and offset as results.
13064 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13065                            const GlobalValue *&GV, const void *&CV) {
13066   // Assume it is a primitive operation.
13067   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13068
13069   // If it's an adding a simple constant then integrate the offset.
13070   if (Base.getOpcode() == ISD::ADD) {
13071     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13072       Base = Base.getOperand(0);
13073       Offset += C->getZExtValue();
13074     }
13075   }
13076
13077   // Return the underlying GlobalValue, and update the Offset.  Return false
13078   // for GlobalAddressSDNode since the same GlobalAddress may be represented
13079   // by multiple nodes with different offsets.
13080   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13081     GV = G->getGlobal();
13082     Offset += G->getOffset();
13083     return false;
13084   }
13085
13086   // Return the underlying Constant value, and update the Offset.  Return false
13087   // for ConstantSDNodes since the same constant pool entry may be represented
13088   // by multiple nodes with different offsets.
13089   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13090     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13091                                          : (const void *)C->getConstVal();
13092     Offset += C->getOffset();
13093     return false;
13094   }
13095   // If it's any of the following then it can't alias with anything but itself.
13096   return isa<FrameIndexSDNode>(Base);
13097 }
13098
13099 /// Return true if there is any possibility that the two addresses overlap.
13100 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13101   // If they are the same then they must be aliases.
13102   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13103
13104   // If they are both volatile then they cannot be reordered.
13105   if (Op0->isVolatile() && Op1->isVolatile()) return true;
13106
13107   // Gather base node and offset information.
13108   SDValue Base1, Base2;
13109   int64_t Offset1, Offset2;
13110   const GlobalValue *GV1, *GV2;
13111   const void *CV1, *CV2;
13112   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13113                                       Base1, Offset1, GV1, CV1);
13114   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13115                                       Base2, Offset2, GV2, CV2);
13116
13117   // If they have a same base address then check to see if they overlap.
13118   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13119     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13120              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13121
13122   // It is possible for different frame indices to alias each other, mostly
13123   // when tail call optimization reuses return address slots for arguments.
13124   // To catch this case, look up the actual index of frame indices to compute
13125   // the real alias relationship.
13126   if (isFrameIndex1 && isFrameIndex2) {
13127     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13128     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13129     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13130     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13131              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13132   }
13133
13134   // Otherwise, if we know what the bases are, and they aren't identical, then
13135   // we know they cannot alias.
13136   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13137     return false;
13138
13139   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13140   // compared to the size and offset of the access, we may be able to prove they
13141   // do not alias.  This check is conservative for now to catch cases created by
13142   // splitting vector types.
13143   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13144       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13145       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13146        Op1->getMemoryVT().getSizeInBits() >> 3) &&
13147       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13148     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13149     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13150
13151     // There is no overlap between these relatively aligned accesses of similar
13152     // size, return no alias.
13153     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13154         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13155       return false;
13156   }
13157
13158   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13159                    ? CombinerGlobalAA
13160                    : DAG.getSubtarget().useAA();
13161 #ifndef NDEBUG
13162   if (CombinerAAOnlyFunc.getNumOccurrences() &&
13163       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13164     UseAA = false;
13165 #endif
13166   if (UseAA &&
13167       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13168     // Use alias analysis information.
13169     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13170                                  Op1->getSrcValueOffset());
13171     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13172         Op0->getSrcValueOffset() - MinOffset;
13173     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13174         Op1->getSrcValueOffset() - MinOffset;
13175     AliasAnalysis::AliasResult AAResult =
13176         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13177                                          Overlap1,
13178                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13179                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13180                                          Overlap2,
13181                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13182     if (AAResult == AliasAnalysis::NoAlias)
13183       return false;
13184   }
13185
13186   // Otherwise we have to assume they alias.
13187   return true;
13188 }
13189
13190 /// Walk up chain skipping non-aliasing memory nodes,
13191 /// looking for aliasing nodes and adding them to the Aliases vector.
13192 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13193                                    SmallVectorImpl<SDValue> &Aliases) {
13194   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
13195   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
13196
13197   // Get alias information for node.
13198   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13199
13200   // Starting off.
13201   Chains.push_back(OriginalChain);
13202   unsigned Depth = 0;
13203
13204   // Look at each chain and determine if it is an alias.  If so, add it to the
13205   // aliases list.  If not, then continue up the chain looking for the next
13206   // candidate.
13207   while (!Chains.empty()) {
13208     SDValue Chain = Chains.back();
13209     Chains.pop_back();
13210
13211     // For TokenFactor nodes, look at each operand and only continue up the
13212     // chain until we find two aliases.  If we've seen two aliases, assume we'll
13213     // find more and revert to original chain since the xform is unlikely to be
13214     // profitable.
13215     //
13216     // FIXME: The depth check could be made to return the last non-aliasing
13217     // chain we found before we hit a tokenfactor rather than the original
13218     // chain.
13219     if (Depth > 6 || Aliases.size() == 2) {
13220       Aliases.clear();
13221       Aliases.push_back(OriginalChain);
13222       return;
13223     }
13224
13225     // Don't bother if we've been before.
13226     if (!Visited.insert(Chain.getNode()).second)
13227       continue;
13228
13229     switch (Chain.getOpcode()) {
13230     case ISD::EntryToken:
13231       // Entry token is ideal chain operand, but handled in FindBetterChain.
13232       break;
13233
13234     case ISD::LOAD:
13235     case ISD::STORE: {
13236       // Get alias information for Chain.
13237       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13238           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13239
13240       // If chain is alias then stop here.
13241       if (!(IsLoad && IsOpLoad) &&
13242           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13243         Aliases.push_back(Chain);
13244       } else {
13245         // Look further up the chain.
13246         Chains.push_back(Chain.getOperand(0));
13247         ++Depth;
13248       }
13249       break;
13250     }
13251
13252     case ISD::TokenFactor:
13253       // We have to check each of the operands of the token factor for "small"
13254       // token factors, so we queue them up.  Adding the operands to the queue
13255       // (stack) in reverse order maintains the original order and increases the
13256       // likelihood that getNode will find a matching token factor (CSE.)
13257       if (Chain.getNumOperands() > 16) {
13258         Aliases.push_back(Chain);
13259         break;
13260       }
13261       for (unsigned n = Chain.getNumOperands(); n;)
13262         Chains.push_back(Chain.getOperand(--n));
13263       ++Depth;
13264       break;
13265
13266     default:
13267       // For all other instructions we will just have to take what we can get.
13268       Aliases.push_back(Chain);
13269       break;
13270     }
13271   }
13272
13273   // We need to be careful here to also search for aliases through the
13274   // value operand of a store, etc. Consider the following situation:
13275   //   Token1 = ...
13276   //   L1 = load Token1, %52
13277   //   S1 = store Token1, L1, %51
13278   //   L2 = load Token1, %52+8
13279   //   S2 = store Token1, L2, %51+8
13280   //   Token2 = Token(S1, S2)
13281   //   L3 = load Token2, %53
13282   //   S3 = store Token2, L3, %52
13283   //   L4 = load Token2, %53+8
13284   //   S4 = store Token2, L4, %52+8
13285   // If we search for aliases of S3 (which loads address %52), and we look
13286   // only through the chain, then we'll miss the trivial dependence on L1
13287   // (which also loads from %52). We then might change all loads and
13288   // stores to use Token1 as their chain operand, which could result in
13289   // copying %53 into %52 before copying %52 into %51 (which should
13290   // happen first).
13291   //
13292   // The problem is, however, that searching for such data dependencies
13293   // can become expensive, and the cost is not directly related to the
13294   // chain depth. Instead, we'll rule out such configurations here by
13295   // insisting that we've visited all chain users (except for users
13296   // of the original chain, which is not necessary). When doing this,
13297   // we need to look through nodes we don't care about (otherwise, things
13298   // like register copies will interfere with trivial cases).
13299
13300   SmallVector<const SDNode *, 16> Worklist;
13301   for (const SDNode *N : Visited)
13302     if (N != OriginalChain.getNode())
13303       Worklist.push_back(N);
13304
13305   while (!Worklist.empty()) {
13306     const SDNode *M = Worklist.pop_back_val();
13307
13308     // We have already visited M, and want to make sure we've visited any uses
13309     // of M that we care about. For uses that we've not visisted, and don't
13310     // care about, queue them to the worklist.
13311
13312     for (SDNode::use_iterator UI = M->use_begin(),
13313          UIE = M->use_end(); UI != UIE; ++UI)
13314       if (UI.getUse().getValueType() == MVT::Other &&
13315           Visited.insert(*UI).second) {
13316         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13317           // We've not visited this use, and we care about it (it could have an
13318           // ordering dependency with the original node).
13319           Aliases.clear();
13320           Aliases.push_back(OriginalChain);
13321           return;
13322         }
13323
13324         // We've not visited this use, but we don't care about it. Mark it as
13325         // visited and enqueue it to the worklist.
13326         Worklist.push_back(*UI);
13327       }
13328   }
13329 }
13330
13331 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13332 /// (aliasing node.)
13333 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13334   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
13335
13336   // Accumulate all the aliases to this node.
13337   GatherAllAliases(N, OldChain, Aliases);
13338
13339   // If no operands then chain to entry token.
13340   if (Aliases.size() == 0)
13341     return DAG.getEntryNode();
13342
13343   // If a single operand then chain to it.  We don't need to revisit it.
13344   if (Aliases.size() == 1)
13345     return Aliases[0];
13346
13347   // Construct a custom tailored token factor.
13348   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13349 }
13350
13351 /// This is the entry point for the file.
13352 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13353                            CodeGenOpt::Level OptLevel) {
13354   /// This is the main entry point to this class.
13355   DAGCombiner(*this, AA, OptLevel).Run(Level);
13356 }