]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - opencl/llvm.git/blob - lib/CodeGen/SelectionDAG/DAGCombiner.cpp
4a9ae200663e6a4d107535b7330ca68710e727b6
[opencl/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 //===----------------------------------------------------------------------===//
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;
43 #define DEBUG_TYPE "dagcombine"
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");
52 namespace {
53   static cl::opt<bool>
54     CombinerAA("combiner-alias-analysis", cl::Hidden,
55                cl::desc("Enable DAG combiner alias-analysis heuristics"));
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"));
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"));
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
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));
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"));
84 //------------------------------ DAGCombiner ---------------------------------//
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;
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;
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;
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;
117     // AA - Used for DAG load/store alias analysis.
118     AliasAnalysis &AA;
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     }
127     /// Call the node-specific routine that folds each particular type of node.
128     SDValue visit(SDNode *N);
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;
139       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140         Worklist.push_back(N);
141     }
143     /// Remove all instances of N from the worklist.
144     void removeFromWorklist(SDNode *N) {
145       CombinedNodes.erase(N);
147       auto It = WorklistMap.find(N);
148       if (It == WorklistMap.end())
149         return; // Not in the worklist.
151       // Null out the entry rather than erasing it to avoid a linear operation.
152       Worklist[It->second] = nullptr;
153       WorklistMap.erase(It);
154     }
156     void deleteAndRecombine(SDNode *N);
157     bool recursivelyDeleteUnusedNodes(SDNode *N);
159     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
160                       bool AddTo = true);
162     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163       return CombineTo(N, &Res, 1, AddTo);
164     }
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     }
172     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
174   private:
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     }
185     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
187     bool CombineToPreIndexedLoadStore(SDNode *N);
188     bool CombineToPostIndexedLoadStore(SDNode *N);
189     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190     bool SliceUpLoad(SDNode *N);
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);
211     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213                          ISD::NodeType ExtType);
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);
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 visitOR(SDNode *N);
250     SDValue visitXOR(SDNode *N);
251     SDValue SimplifyVBinOp(SDNode *N);
252     SDValue SimplifyVUnaryOp(SDNode *N);
253     SDValue visitSHL(SDNode *N);
254     SDValue visitSRA(SDNode *N);
255     SDValue visitSRL(SDNode *N);
256     SDValue visitRotate(SDNode *N);
257     SDValue visitCTLZ(SDNode *N);
258     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
259     SDValue visitCTTZ(SDNode *N);
260     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
261     SDValue visitCTPOP(SDNode *N);
262     SDValue visitSELECT(SDNode *N);
263     SDValue visitVSELECT(SDNode *N);
264     SDValue visitSELECT_CC(SDNode *N);
265     SDValue visitSETCC(SDNode *N);
266     SDValue visitSIGN_EXTEND(SDNode *N);
267     SDValue visitZERO_EXTEND(SDNode *N);
268     SDValue visitANY_EXTEND(SDNode *N);
269     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
270     SDValue visitTRUNCATE(SDNode *N);
271     SDValue visitBITCAST(SDNode *N);
272     SDValue visitBUILD_PAIR(SDNode *N);
273     SDValue visitFADD(SDNode *N);
274     SDValue visitFSUB(SDNode *N);
275     SDValue visitFMUL(SDNode *N);
276     SDValue visitFMA(SDNode *N);
277     SDValue visitFDIV(SDNode *N);
278     SDValue visitFREM(SDNode *N);
279     SDValue visitFSQRT(SDNode *N);
280     SDValue visitFCOPYSIGN(SDNode *N);
281     SDValue visitSINT_TO_FP(SDNode *N);
282     SDValue visitUINT_TO_FP(SDNode *N);
283     SDValue visitFP_TO_SINT(SDNode *N);
284     SDValue visitFP_TO_UINT(SDNode *N);
285     SDValue visitFP_ROUND(SDNode *N);
286     SDValue visitFP_ROUND_INREG(SDNode *N);
287     SDValue visitFP_EXTEND(SDNode *N);
288     SDValue visitFNEG(SDNode *N);
289     SDValue visitFABS(SDNode *N);
290     SDValue visitFCEIL(SDNode *N);
291     SDValue visitFTRUNC(SDNode *N);
292     SDValue visitFFLOOR(SDNode *N);
293     SDValue visitFMINNUM(SDNode *N);
294     SDValue visitFMAXNUM(SDNode *N);
295     SDValue visitBRCOND(SDNode *N);
296     SDValue visitBR_CC(SDNode *N);
297     SDValue visitLOAD(SDNode *N);
298     SDValue visitSTORE(SDNode *N);
299     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
300     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
301     SDValue visitBUILD_VECTOR(SDNode *N);
302     SDValue visitCONCAT_VECTORS(SDNode *N);
303     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
304     SDValue visitVECTOR_SHUFFLE(SDNode *N);
305     SDValue visitINSERT_SUBVECTOR(SDNode *N);
306     SDValue visitMLOAD(SDNode *N);
307     SDValue visitMSTORE(SDNode *N);
309     SDValue XformToShuffleWithZero(SDNode *N);
310     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
312     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
314     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
315     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
316     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
317     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
318                              SDValue N3, ISD::CondCode CC,
319                              bool NotExtCompare = false);
320     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
321                           SDLoc DL, bool foldBooleans = true);
323     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
324                            SDValue &CC) const;
325     bool isOneUseSetCC(SDValue N) const;
327     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
328                                          unsigned HiOp);
329     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
330     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
331     SDValue BuildSDIV(SDNode *N);
332     SDValue BuildSDIVPow2(SDNode *N);
333     SDValue BuildUDIV(SDNode *N);
334     SDValue BuildReciprocalEstimate(SDValue Op);
335     SDValue BuildRsqrtEstimate(SDValue Op);
336     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
337     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
338     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
339                                bool DemandHighBits = true);
340     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
341     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
342                               SDValue InnerPos, SDValue InnerNeg,
343                               unsigned PosOpcode, unsigned NegOpcode,
344                               SDLoc DL);
345     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
346     SDValue ReduceLoadWidth(SDNode *N);
347     SDValue ReduceLoadOpStoreWidth(SDNode *N);
348     SDValue TransformFPLoadStorePair(SDNode *N);
349     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
350     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
352     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
354     /// Walk up chain skipping non-aliasing memory nodes,
355     /// looking for aliasing nodes and adding them to the Aliases vector.
356     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
357                           SmallVectorImpl<SDValue> &Aliases);
359     /// Return true if there is any possibility that the two addresses overlap.
360     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
362     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
363     /// chain (aliasing node.)
364     SDValue FindBetterChain(SDNode *N, SDValue Chain);
366     /// Merge consecutive store operations into a wide store.
367     /// This optimization uses wide integers or vectors when possible.
368     /// \return True if some memory operations were changed.
369     bool MergeConsecutiveStores(StoreSDNode *N);
371     /// \brief Try to transform a truncation where C is a constant:
372     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
373     ///
374     /// \p N needs to be a truncation and its first operand an AND. Other
375     /// requirements are checked by the function (e.g. that trunc is
376     /// single-use) and if missed an empty SDValue is returned.
377     SDValue distributeTruncateThroughAnd(SDNode *N);
379   public:
380     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
381         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
382           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
383       AttributeSet FnAttrs =
384           DAG.getMachineFunction().getFunction()->getAttributes();
385       ForCodeSize =
386           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
387                                Attribute::OptimizeForSize) ||
388           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
389     }
391     /// Runs the dag combiner on all nodes in the work list
392     void Run(CombineLevel AtLevel);
394     SelectionDAG &getDAG() const { return DAG; }
396     /// Returns a type large enough to hold any valid shift amount - before type
397     /// legalization these can be huge.
398     EVT getShiftAmountTy(EVT LHSTy) {
399       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
400       if (LHSTy.isVector())
401         return LHSTy;
402       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
403                         : TLI.getPointerTy();
404     }
406     /// This method returns true if we are running before type legalization or
407     /// if the specified VT is legal.
408     bool isTypeLegal(const EVT &VT) {
409       if (!LegalTypes) return true;
410       return TLI.isTypeLegal(VT);
411     }
413     /// Convenience wrapper around TargetLowering::getSetCCResultType
414     EVT getSetCCResultType(EVT VT) const {
415       return TLI.getSetCCResultType(*DAG.getContext(), VT);
416     }
417   };
421 namespace {
422 /// This class is a DAGUpdateListener that removes any deleted
423 /// nodes from the worklist.
424 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
425   DAGCombiner &DC;
426 public:
427   explicit WorklistRemover(DAGCombiner &dc)
428     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
430   void NodeDeleted(SDNode *N, SDNode *E) override {
431     DC.removeFromWorklist(N);
432   }
433 };
436 //===----------------------------------------------------------------------===//
437 //  TargetLowering::DAGCombinerInfo implementation
438 //===----------------------------------------------------------------------===//
440 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
441   ((DAGCombiner*)DC)->AddToWorklist(N);
444 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
445   ((DAGCombiner*)DC)->removeFromWorklist(N);
448 SDValue TargetLowering::DAGCombinerInfo::
449 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
450   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
453 SDValue TargetLowering::DAGCombinerInfo::
454 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
455   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
459 SDValue TargetLowering::DAGCombinerInfo::
460 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
461   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
464 void TargetLowering::DAGCombinerInfo::
465 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
466   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
469 //===----------------------------------------------------------------------===//
470 // Helper Functions
471 //===----------------------------------------------------------------------===//
473 void DAGCombiner::deleteAndRecombine(SDNode *N) {
474   removeFromWorklist(N);
476   // If the operands of this node are only used by the node, they will now be
477   // dead. Make sure to re-visit them and recursively delete dead nodes.
478   for (const SDValue &Op : N->ops())
479     // For an operand generating multiple values, one of the values may
480     // become dead allowing further simplification (e.g. split index
481     // arithmetic from an indexed load).
482     if (Op->hasOneUse() || Op->getNumValues() > 1)
483       AddToWorklist(Op.getNode());
485   DAG.DeleteNode(N);
488 /// Return 1 if we can compute the negated form of the specified expression for
489 /// the same cost as the expression itself, or 2 if we can compute the negated
490 /// form more cheaply than the expression itself.
491 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
492                                const TargetLowering &TLI,
493                                const TargetOptions *Options,
494                                unsigned Depth = 0) {
495   // fneg is removable even if it has multiple uses.
496   if (Op.getOpcode() == ISD::FNEG) return 2;
498   // Don't allow anything with multiple uses.
499   if (!Op.hasOneUse()) return 0;
501   // Don't recurse exponentially.
502   if (Depth > 6) return 0;
504   switch (Op.getOpcode()) {
505   default: return false;
506   case ISD::ConstantFP:
507     // Don't invert constant FP values after legalize.  The negated constant
508     // isn't necessarily legal.
509     return LegalOperations ? 0 : 1;
510   case ISD::FADD:
511     // FIXME: determine better conditions for this xform.
512     if (!Options->UnsafeFPMath) return 0;
514     // After operation legalization, it might not be legal to create new FSUBs.
515     if (LegalOperations &&
516         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
517       return 0;
519     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
520     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
521                                     Options, Depth + 1))
522       return V;
523     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
524     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
525                               Depth + 1);
526   case ISD::FSUB:
527     // We can't turn -(A-B) into B-A when we honor signed zeros.
528     if (!Options->UnsafeFPMath) return 0;
530     // fold (fneg (fsub A, B)) -> (fsub B, A)
531     return 1;
533   case ISD::FMUL:
534   case ISD::FDIV:
535     if (Options->HonorSignDependentRoundingFPMath()) return 0;
537     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
538     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
539                                     Options, Depth + 1))
540       return V;
542     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
543                               Depth + 1);
545   case ISD::FP_EXTEND:
546   case ISD::FP_ROUND:
547   case ISD::FSIN:
548     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
549                               Depth + 1);
550   }
553 /// If isNegatibleForFree returns true, return the newly negated expression.
554 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
555                                     bool LegalOperations, unsigned Depth = 0) {
556   const TargetOptions &Options = DAG.getTarget().Options;
557   // fneg is removable even if it has multiple uses.
558   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
560   // Don't allow anything with multiple uses.
561   assert(Op.hasOneUse() && "Unknown reuse!");
563   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
564   switch (Op.getOpcode()) {
565   default: llvm_unreachable("Unknown code");
566   case ISD::ConstantFP: {
567     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
568     V.changeSign();
569     return DAG.getConstantFP(V, Op.getValueType());
570   }
571   case ISD::FADD:
572     // FIXME: determine better conditions for this xform.
573     assert(Options.UnsafeFPMath);
575     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
576     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
577                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
578       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
579                          GetNegatedExpression(Op.getOperand(0), DAG,
580                                               LegalOperations, Depth+1),
581                          Op.getOperand(1));
582     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
583     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
584                        GetNegatedExpression(Op.getOperand(1), DAG,
585                                             LegalOperations, Depth+1),
586                        Op.getOperand(0));
587   case ISD::FSUB:
588     // We can't turn -(A-B) into B-A when we honor signed zeros.
589     assert(Options.UnsafeFPMath);
591     // fold (fneg (fsub 0, B)) -> B
592     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
593       if (N0CFP->getValueAPF().isZero())
594         return Op.getOperand(1);
596     // fold (fneg (fsub A, B)) -> (fsub B, A)
597     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
598                        Op.getOperand(1), Op.getOperand(0));
600   case ISD::FMUL:
601   case ISD::FDIV:
602     assert(!Options.HonorSignDependentRoundingFPMath());
604     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
605     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
606                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
607       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
608                          GetNegatedExpression(Op.getOperand(0), DAG,
609                                               LegalOperations, Depth+1),
610                          Op.getOperand(1));
612     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
613     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
614                        Op.getOperand(0),
615                        GetNegatedExpression(Op.getOperand(1), DAG,
616                                             LegalOperations, Depth+1));
618   case ISD::FP_EXTEND:
619   case ISD::FSIN:
620     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
621                        GetNegatedExpression(Op.getOperand(0), DAG,
622                                             LegalOperations, Depth+1));
623   case ISD::FP_ROUND:
624       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
625                          GetNegatedExpression(Op.getOperand(0), DAG,
626                                               LegalOperations, Depth+1),
627                          Op.getOperand(1));
628   }
631 // Return true if this node is a setcc, or is a select_cc
632 // that selects between the target values used for true and false, making it
633 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
634 // the appropriate nodes based on the type of node we are checking. This
635 // simplifies life a bit for the callers.
636 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
637                                     SDValue &CC) const {
638   if (N.getOpcode() == ISD::SETCC) {
639     LHS = N.getOperand(0);
640     RHS = N.getOperand(1);
641     CC  = N.getOperand(2);
642     return true;
643   }
645   if (N.getOpcode() != ISD::SELECT_CC ||
646       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
647       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
648     return false;
650   if (TLI.getBooleanContents(N.getValueType()) ==
651       TargetLowering::UndefinedBooleanContent)
652     return false;
654   LHS = N.getOperand(0);
655   RHS = N.getOperand(1);
656   CC  = N.getOperand(4);
657   return true;
660 /// Return true if this is a SetCC-equivalent operation with only one use.
661 /// If this is true, it allows the users to invert the operation for free when
662 /// it is profitable to do so.
663 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
664   SDValue N0, N1, N2;
665   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
666     return true;
667   return false;
670 /// Returns true if N is a BUILD_VECTOR node whose
671 /// elements are all the same constant or undefined.
672 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
673   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
674   if (!C)
675     return false;
677   APInt SplatUndef;
678   unsigned SplatBitSize;
679   bool HasAnyUndefs;
680   EVT EltVT = N->getValueType(0).getVectorElementType();
681   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
682                              HasAnyUndefs) &&
683           EltVT.getSizeInBits() >= SplatBitSize);
686 // \brief Returns the SDNode if it is a constant BuildVector or constant.
687 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
688   if (isa<ConstantSDNode>(N))
689     return N.getNode();
690   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
691   if (BV && BV->isConstant())
692     return BV;
693   return nullptr;
696 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
697 // int.
698 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
699   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
700     return CN;
702   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
703     BitVector UndefElements;
704     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
706     // BuildVectors can truncate their operands. Ignore that case here.
707     // FIXME: We blindly ignore splats which include undef which is overly
708     // pessimistic.
709     if (CN && UndefElements.none() &&
710         CN->getValueType(0) == N.getValueType().getScalarType())
711       return CN;
712   }
714   return nullptr;
717 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
718 // float.
719 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
720   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
721     return CN;
723   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
724     BitVector UndefElements;
725     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
727     if (CN && UndefElements.none())
728       return CN;
729   }
731   return nullptr;
734 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
735                                     SDValue N0, SDValue N1) {
736   EVT VT = N0.getValueType();
737   if (N0.getOpcode() == Opc) {
738     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
739       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
740         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
741         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R))
742           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
743         return SDValue();
744       }
745       if (N0.hasOneUse()) {
746         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
747         // use
748         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
749         if (!OpNode.getNode())
750           return SDValue();
751         AddToWorklist(OpNode.getNode());
752         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
753       }
754     }
755   }
757   if (N1.getOpcode() == Opc) {
758     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
759       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
760         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
761         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L))
762           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
763         return SDValue();
764       }
765       if (N1.hasOneUse()) {
766         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
767         // use
768         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
769         if (!OpNode.getNode())
770           return SDValue();
771         AddToWorklist(OpNode.getNode());
772         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
773       }
774     }
775   }
777   return SDValue();
780 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
781                                bool AddTo) {
782   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
783   ++NodesCombined;
784   DEBUG(dbgs() << "\nReplacing.1 ";
785         N->dump(&DAG);
786         dbgs() << "\nWith: ";
787         To[0].getNode()->dump(&DAG);
788         dbgs() << " and " << NumTo-1 << " other values\n");
789   for (unsigned i = 0, e = NumTo; i != e; ++i)
790     assert((!To[i].getNode() ||
791             N->getValueType(i) == To[i].getValueType()) &&
792            "Cannot combine value to value of different type!");
794   WorklistRemover DeadNodes(*this);
795   DAG.ReplaceAllUsesWith(N, To);
796   if (AddTo) {
797     // Push the new nodes and any users onto the worklist
798     for (unsigned i = 0, e = NumTo; i != e; ++i) {
799       if (To[i].getNode()) {
800         AddToWorklist(To[i].getNode());
801         AddUsersToWorklist(To[i].getNode());
802       }
803     }
804   }
806   // Finally, if the node is now dead, remove it from the graph.  The node
807   // may not be dead if the replacement process recursively simplified to
808   // something else needing this node.
809   if (N->use_empty())
810     deleteAndRecombine(N);
811   return SDValue(N, 0);
814 void DAGCombiner::
815 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
816   // Replace all uses.  If any nodes become isomorphic to other nodes and
817   // are deleted, make sure to remove them from our worklist.
818   WorklistRemover DeadNodes(*this);
819   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
821   // Push the new node and any (possibly new) users onto the worklist.
822   AddToWorklist(TLO.New.getNode());
823   AddUsersToWorklist(TLO.New.getNode());
825   // Finally, if the node is now dead, remove it from the graph.  The node
826   // may not be dead if the replacement process recursively simplified to
827   // something else needing this node.
828   if (TLO.Old.getNode()->use_empty())
829     deleteAndRecombine(TLO.Old.getNode());
832 /// Check the specified integer node value to see if it can be simplified or if
833 /// things it uses can be simplified by bit propagation. If so, return true.
834 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
835   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
836   APInt KnownZero, KnownOne;
837   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
838     return false;
840   // Revisit the node.
841   AddToWorklist(Op.getNode());
843   // Replace the old value with the new one.
844   ++NodesCombined;
845   DEBUG(dbgs() << "\nReplacing.2 ";
846         TLO.Old.getNode()->dump(&DAG);
847         dbgs() << "\nWith: ";
848         TLO.New.getNode()->dump(&DAG);
849         dbgs() << '\n');
851   CommitTargetLoweringOpt(TLO);
852   return true;
855 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
856   SDLoc dl(Load);
857   EVT VT = Load->getValueType(0);
858   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
860   DEBUG(dbgs() << "\nReplacing.9 ";
861         Load->dump(&DAG);
862         dbgs() << "\nWith: ";
863         Trunc.getNode()->dump(&DAG);
864         dbgs() << '\n');
865   WorklistRemover DeadNodes(*this);
866   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
867   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
868   deleteAndRecombine(Load);
869   AddToWorklist(Trunc.getNode());
872 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
873   Replace = false;
874   SDLoc dl(Op);
875   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
876     EVT MemVT = LD->getMemoryVT();
877     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
878       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
879                                                        : ISD::EXTLOAD)
880       : LD->getExtensionType();
881     Replace = true;
882     return DAG.getExtLoad(ExtType, dl, PVT,
883                           LD->getChain(), LD->getBasePtr(),
884                           MemVT, LD->getMemOperand());
885   }
887   unsigned Opc = Op.getOpcode();
888   switch (Opc) {
889   default: break;
890   case ISD::AssertSext:
891     return DAG.getNode(ISD::AssertSext, dl, PVT,
892                        SExtPromoteOperand(Op.getOperand(0), PVT),
893                        Op.getOperand(1));
894   case ISD::AssertZext:
895     return DAG.getNode(ISD::AssertZext, dl, PVT,
896                        ZExtPromoteOperand(Op.getOperand(0), PVT),
897                        Op.getOperand(1));
898   case ISD::Constant: {
899     unsigned ExtOpc =
900       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
901     return DAG.getNode(ExtOpc, dl, PVT, Op);
902   }
903   }
905   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
906     return SDValue();
907   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
910 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
911   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
912     return SDValue();
913   EVT OldVT = Op.getValueType();
914   SDLoc dl(Op);
915   bool Replace = false;
916   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
917   if (!NewOp.getNode())
918     return SDValue();
919   AddToWorklist(NewOp.getNode());
921   if (Replace)
922     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
923   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
924                      DAG.getValueType(OldVT));
927 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
928   EVT OldVT = Op.getValueType();
929   SDLoc dl(Op);
930   bool Replace = false;
931   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
932   if (!NewOp.getNode())
933     return SDValue();
934   AddToWorklist(NewOp.getNode());
936   if (Replace)
937     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
938   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
941 /// Promote the specified integer binary operation if the target indicates it is
942 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
943 /// i32 since i16 instructions are longer.
944 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
945   if (!LegalOperations)
946     return SDValue();
948   EVT VT = Op.getValueType();
949   if (VT.isVector() || !VT.isInteger())
950     return SDValue();
952   // If operation type is 'undesirable', e.g. i16 on x86, consider
953   // promoting it.
954   unsigned Opc = Op.getOpcode();
955   if (TLI.isTypeDesirableForOp(Opc, VT))
956     return SDValue();
958   EVT PVT = VT;
959   // Consult target whether it is a good idea to promote this operation and
960   // what's the right type to promote it to.
961   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
962     assert(PVT != VT && "Don't know what type to promote to!");
964     bool Replace0 = false;
965     SDValue N0 = Op.getOperand(0);
966     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
967     if (!NN0.getNode())
968       return SDValue();
970     bool Replace1 = false;
971     SDValue N1 = Op.getOperand(1);
972     SDValue NN1;
973     if (N0 == N1)
974       NN1 = NN0;
975     else {
976       NN1 = PromoteOperand(N1, PVT, Replace1);
977       if (!NN1.getNode())
978         return SDValue();
979     }
981     AddToWorklist(NN0.getNode());
982     if (NN1.getNode())
983       AddToWorklist(NN1.getNode());
985     if (Replace0)
986       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
987     if (Replace1)
988       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
990     DEBUG(dbgs() << "\nPromoting ";
991           Op.getNode()->dump(&DAG));
992     SDLoc dl(Op);
993     return DAG.getNode(ISD::TRUNCATE, dl, VT,
994                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
995   }
996   return SDValue();
999 /// Promote the specified integer shift operation if the target indicates it is
1000 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1001 /// i32 since i16 instructions are longer.
1002 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1003   if (!LegalOperations)
1004     return SDValue();
1006   EVT VT = Op.getValueType();
1007   if (VT.isVector() || !VT.isInteger())
1008     return SDValue();
1010   // If operation type is 'undesirable', e.g. i16 on x86, consider
1011   // promoting it.
1012   unsigned Opc = Op.getOpcode();
1013   if (TLI.isTypeDesirableForOp(Opc, VT))
1014     return SDValue();
1016   EVT PVT = VT;
1017   // Consult target whether it is a good idea to promote this operation and
1018   // what's the right type to promote it to.
1019   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1020     assert(PVT != VT && "Don't know what type to promote to!");
1022     bool Replace = false;
1023     SDValue N0 = Op.getOperand(0);
1024     if (Opc == ISD::SRA)
1025       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1026     else if (Opc == ISD::SRL)
1027       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1028     else
1029       N0 = PromoteOperand(N0, PVT, Replace);
1030     if (!N0.getNode())
1031       return SDValue();
1033     AddToWorklist(N0.getNode());
1034     if (Replace)
1035       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1037     DEBUG(dbgs() << "\nPromoting ";
1038           Op.getNode()->dump(&DAG));
1039     SDLoc dl(Op);
1040     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1041                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1042   }
1043   return SDValue();
1046 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1047   if (!LegalOperations)
1048     return SDValue();
1050   EVT VT = Op.getValueType();
1051   if (VT.isVector() || !VT.isInteger())
1052     return SDValue();
1054   // If operation type is 'undesirable', e.g. i16 on x86, consider
1055   // promoting it.
1056   unsigned Opc = Op.getOpcode();
1057   if (TLI.isTypeDesirableForOp(Opc, VT))
1058     return SDValue();
1060   EVT PVT = VT;
1061   // Consult target whether it is a good idea to promote this operation and
1062   // what's the right type to promote it to.
1063   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1064     assert(PVT != VT && "Don't know what type to promote to!");
1065     // fold (aext (aext x)) -> (aext x)
1066     // fold (aext (zext x)) -> (zext x)
1067     // fold (aext (sext x)) -> (sext x)
1068     DEBUG(dbgs() << "\nPromoting ";
1069           Op.getNode()->dump(&DAG));
1070     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1071   }
1072   return SDValue();
1075 bool DAGCombiner::PromoteLoad(SDValue Op) {
1076   if (!LegalOperations)
1077     return false;
1079   EVT VT = Op.getValueType();
1080   if (VT.isVector() || !VT.isInteger())
1081     return false;
1083   // If operation type is 'undesirable', e.g. i16 on x86, consider
1084   // promoting it.
1085   unsigned Opc = Op.getOpcode();
1086   if (TLI.isTypeDesirableForOp(Opc, VT))
1087     return false;
1089   EVT PVT = VT;
1090   // Consult target whether it is a good idea to promote this operation and
1091   // what's the right type to promote it to.
1092   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1093     assert(PVT != VT && "Don't know what type to promote to!");
1095     SDLoc dl(Op);
1096     SDNode *N = Op.getNode();
1097     LoadSDNode *LD = cast<LoadSDNode>(N);
1098     EVT MemVT = LD->getMemoryVT();
1099     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1100       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1101                                                        : ISD::EXTLOAD)
1102       : LD->getExtensionType();
1103     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1104                                    LD->getChain(), LD->getBasePtr(),
1105                                    MemVT, LD->getMemOperand());
1106     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1108     DEBUG(dbgs() << "\nPromoting ";
1109           N->dump(&DAG);
1110           dbgs() << "\nTo: ";
1111           Result.getNode()->dump(&DAG);
1112           dbgs() << '\n');
1113     WorklistRemover DeadNodes(*this);
1114     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1115     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1116     deleteAndRecombine(N);
1117     AddToWorklist(Result.getNode());
1118     return true;
1119   }
1120   return false;
1123 /// \brief Recursively delete a node which has no uses and any operands for
1124 /// which it is the only use.
1125 ///
1126 /// Note that this both deletes the nodes and removes them from the worklist.
1127 /// It also adds any nodes who have had a user deleted to the worklist as they
1128 /// may now have only one use and subject to other combines.
1129 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1130   if (!N->use_empty())
1131     return false;
1133   SmallSetVector<SDNode *, 16> Nodes;
1134   Nodes.insert(N);
1135   do {
1136     N = Nodes.pop_back_val();
1137     if (!N)
1138       continue;
1140     if (N->use_empty()) {
1141       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1142         Nodes.insert(N->getOperand(i).getNode());
1144       removeFromWorklist(N);
1145       DAG.DeleteNode(N);
1146     } else {
1147       AddToWorklist(N);
1148     }
1149   } while (!Nodes.empty());
1150   return true;
1153 //===----------------------------------------------------------------------===//
1154 //  Main DAG Combiner implementation
1155 //===----------------------------------------------------------------------===//
1157 void DAGCombiner::Run(CombineLevel AtLevel) {
1158   // set the instance variables, so that the various visit routines may use it.
1159   Level = AtLevel;
1160   LegalOperations = Level >= AfterLegalizeVectorOps;
1161   LegalTypes = Level >= AfterLegalizeTypes;
1163   // Early exit if this basic block is in an optnone function.
1164   AttributeSet FnAttrs =
1165     DAG.getMachineFunction().getFunction()->getAttributes();
1166   if (FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
1167                            Attribute::OptimizeNone))
1168     return;
1170   // Add all the dag nodes to the worklist.
1171   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1172        E = DAG.allnodes_end(); I != E; ++I)
1173     AddToWorklist(I);
1175   // Create a dummy node (which is not added to allnodes), that adds a reference
1176   // to the root node, preventing it from being deleted, and tracking any
1177   // changes of the root.
1178   HandleSDNode Dummy(DAG.getRoot());
1180   // while the worklist isn't empty, find a node and
1181   // try and combine it.
1182   while (!WorklistMap.empty()) {
1183     SDNode *N;
1184     // The Worklist holds the SDNodes in order, but it may contain null entries.
1185     do {
1186       N = Worklist.pop_back_val();
1187     } while (!N);
1189     bool GoodWorklistEntry = WorklistMap.erase(N);
1190     (void)GoodWorklistEntry;
1191     assert(GoodWorklistEntry &&
1192            "Found a worklist entry without a corresponding map entry!");
1194     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1195     // N is deleted from the DAG, since they too may now be dead or may have a
1196     // reduced number of uses, allowing other xforms.
1197     if (recursivelyDeleteUnusedNodes(N))
1198       continue;
1200     WorklistRemover DeadNodes(*this);
1202     // If this combine is running after legalizing the DAG, re-legalize any
1203     // nodes pulled off the worklist.
1204     if (Level == AfterLegalizeDAG) {
1205       SmallSetVector<SDNode *, 16> UpdatedNodes;
1206       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1208       for (SDNode *LN : UpdatedNodes) {
1209         AddToWorklist(LN);
1210         AddUsersToWorklist(LN);
1211       }
1212       if (!NIsValid)
1213         continue;
1214     }
1216     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1218     // Add any operands of the new node which have not yet been combined to the
1219     // worklist as well. Because the worklist uniques things already, this
1220     // won't repeatedly process the same operand.
1221     CombinedNodes.insert(N);
1222     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1223       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1224         AddToWorklist(N->getOperand(i).getNode());
1226     SDValue RV = combine(N);
1228     if (!RV.getNode())
1229       continue;
1231     ++NodesCombined;
1233     // If we get back the same node we passed in, rather than a new node or
1234     // zero, we know that the node must have defined multiple values and
1235     // CombineTo was used.  Since CombineTo takes care of the worklist
1236     // mechanics for us, we have no work to do in this case.
1237     if (RV.getNode() == N)
1238       continue;
1240     assert(N->getOpcode() != ISD::DELETED_NODE &&
1241            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1242            "Node was deleted but visit returned new node!");
1244     DEBUG(dbgs() << " ... into: ";
1245           RV.getNode()->dump(&DAG));
1247     // Transfer debug value.
1248     DAG.TransferDbgValues(SDValue(N, 0), RV);
1249     if (N->getNumValues() == RV.getNode()->getNumValues())
1250       DAG.ReplaceAllUsesWith(N, RV.getNode());
1251     else {
1252       assert(N->getValueType(0) == RV.getValueType() &&
1253              N->getNumValues() == 1 && "Type mismatch");
1254       SDValue OpV = RV;
1255       DAG.ReplaceAllUsesWith(N, &OpV);
1256     }
1258     // Push the new node and any users onto the worklist
1259     AddToWorklist(RV.getNode());
1260     AddUsersToWorklist(RV.getNode());
1262     // Finally, if the node is now dead, remove it from the graph.  The node
1263     // may not be dead if the replacement process recursively simplified to
1264     // something else needing this node. This will also take care of adding any
1265     // operands which have lost a user to the worklist.
1266     recursivelyDeleteUnusedNodes(N);
1267   }
1269   // If the root changed (e.g. it was a dead load, update the root).
1270   DAG.setRoot(Dummy.getValue());
1271   DAG.RemoveDeadNodes();
1274 SDValue DAGCombiner::visit(SDNode *N) {
1275   switch (N->getOpcode()) {
1276   default: break;
1277   case ISD::TokenFactor:        return visitTokenFactor(N);
1278   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1279   case ISD::ADD:                return visitADD(N);
1280   case ISD::SUB:                return visitSUB(N);
1281   case ISD::ADDC:               return visitADDC(N);
1282   case ISD::SUBC:               return visitSUBC(N);
1283   case ISD::ADDE:               return visitADDE(N);
1284   case ISD::SUBE:               return visitSUBE(N);
1285   case ISD::MUL:                return visitMUL(N);
1286   case ISD::SDIV:               return visitSDIV(N);
1287   case ISD::UDIV:               return visitUDIV(N);
1288   case ISD::SREM:               return visitSREM(N);
1289   case ISD::UREM:               return visitUREM(N);
1290   case ISD::MULHU:              return visitMULHU(N);
1291   case ISD::MULHS:              return visitMULHS(N);
1292   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1293   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1294   case ISD::SMULO:              return visitSMULO(N);
1295   case ISD::UMULO:              return visitUMULO(N);
1296   case ISD::SDIVREM:            return visitSDIVREM(N);
1297   case ISD::UDIVREM:            return visitUDIVREM(N);
1298   case ISD::AND:                return visitAND(N);
1299   case ISD::OR:                 return visitOR(N);
1300   case ISD::XOR:                return visitXOR(N);
1301   case ISD::SHL:                return visitSHL(N);
1302   case ISD::SRA:                return visitSRA(N);
1303   case ISD::SRL:                return visitSRL(N);
1304   case ISD::ROTR:
1305   case ISD::ROTL:               return visitRotate(N);
1306   case ISD::CTLZ:               return visitCTLZ(N);
1307   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1308   case ISD::CTTZ:               return visitCTTZ(N);
1309   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1310   case ISD::CTPOP:              return visitCTPOP(N);
1311   case ISD::SELECT:             return visitSELECT(N);
1312   case ISD::VSELECT:            return visitVSELECT(N);
1313   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1314   case ISD::SETCC:              return visitSETCC(N);
1315   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1316   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1317   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1318   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1319   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1320   case ISD::BITCAST:            return visitBITCAST(N);
1321   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1322   case ISD::FADD:               return visitFADD(N);
1323   case ISD::FSUB:               return visitFSUB(N);
1324   case ISD::FMUL:               return visitFMUL(N);
1325   case ISD::FMA:                return visitFMA(N);
1326   case ISD::FDIV:               return visitFDIV(N);
1327   case ISD::FREM:               return visitFREM(N);
1328   case ISD::FSQRT:              return visitFSQRT(N);
1329   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1330   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1331   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1332   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1333   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1334   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1335   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1336   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1337   case ISD::FNEG:               return visitFNEG(N);
1338   case ISD::FABS:               return visitFABS(N);
1339   case ISD::FFLOOR:             return visitFFLOOR(N);
1340   case ISD::FMINNUM:            return visitFMINNUM(N);
1341   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1342   case ISD::FCEIL:              return visitFCEIL(N);
1343   case ISD::FTRUNC:             return visitFTRUNC(N);
1344   case ISD::BRCOND:             return visitBRCOND(N);
1345   case ISD::BR_CC:              return visitBR_CC(N);
1346   case ISD::LOAD:               return visitLOAD(N);
1347   case ISD::STORE:              return visitSTORE(N);
1348   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1349   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1350   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1351   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1352   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1353   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1354   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1355   case ISD::MLOAD:              return visitMLOAD(N);
1356   case ISD::MSTORE:             return visitMSTORE(N);
1357   }
1358   return SDValue();
1361 SDValue DAGCombiner::combine(SDNode *N) {
1362   SDValue RV = visit(N);
1364   // If nothing happened, try a target-specific DAG combine.
1365   if (!RV.getNode()) {
1366     assert(N->getOpcode() != ISD::DELETED_NODE &&
1367            "Node was deleted but visit returned NULL!");
1369     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1370         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1372       // Expose the DAG combiner to the target combiner impls.
1373       TargetLowering::DAGCombinerInfo
1374         DagCombineInfo(DAG, Level, false, this);
1376       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1377     }
1378   }
1380   // If nothing happened still, try promoting the operation.
1381   if (!RV.getNode()) {
1382     switch (N->getOpcode()) {
1383     default: break;
1384     case ISD::ADD:
1385     case ISD::SUB:
1386     case ISD::MUL:
1387     case ISD::AND:
1388     case ISD::OR:
1389     case ISD::XOR:
1390       RV = PromoteIntBinOp(SDValue(N, 0));
1391       break;
1392     case ISD::SHL:
1393     case ISD::SRA:
1394     case ISD::SRL:
1395       RV = PromoteIntShiftOp(SDValue(N, 0));
1396       break;
1397     case ISD::SIGN_EXTEND:
1398     case ISD::ZERO_EXTEND:
1399     case ISD::ANY_EXTEND:
1400       RV = PromoteExtend(SDValue(N, 0));
1401       break;
1402     case ISD::LOAD:
1403       if (PromoteLoad(SDValue(N, 0)))
1404         RV = SDValue(N, 0);
1405       break;
1406     }
1407   }
1409   // If N is a commutative binary node, try commuting it to enable more
1410   // sdisel CSE.
1411   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1412       N->getNumValues() == 1) {
1413     SDValue N0 = N->getOperand(0);
1414     SDValue N1 = N->getOperand(1);
1416     // Constant operands are canonicalized to RHS.
1417     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1418       SDValue Ops[] = {N1, N0};
1419       SDNode *CSENode;
1420       if (const BinaryWithFlagsSDNode *BinNode =
1421               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1422         CSENode = DAG.getNodeIfExists(
1423             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1424             BinNode->hasNoSignedWrap(), BinNode->isExact());
1425       } else {
1426         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1427       }
1428       if (CSENode)
1429         return SDValue(CSENode, 0);
1430     }
1431   }
1433   return RV;
1436 /// Given a node, return its input chain if it has one, otherwise return a null
1437 /// sd operand.
1438 static SDValue getInputChainForNode(SDNode *N) {
1439   if (unsigned NumOps = N->getNumOperands()) {
1440     if (N->getOperand(0).getValueType() == MVT::Other)
1441       return N->getOperand(0);
1442     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1443       return N->getOperand(NumOps-1);
1444     for (unsigned i = 1; i < NumOps-1; ++i)
1445       if (N->getOperand(i).getValueType() == MVT::Other)
1446         return N->getOperand(i);
1447   }
1448   return SDValue();
1451 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1452   // If N has two operands, where one has an input chain equal to the other,
1453   // the 'other' chain is redundant.
1454   if (N->getNumOperands() == 2) {
1455     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1456       return N->getOperand(0);
1457     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1458       return N->getOperand(1);
1459   }
1461   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1462   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1463   SmallPtrSet<SDNode*, 16> SeenOps;
1464   bool Changed = false;             // If we should replace this token factor.
1466   // Start out with this token factor.
1467   TFs.push_back(N);
1469   // Iterate through token factors.  The TFs grows when new token factors are
1470   // encountered.
1471   for (unsigned i = 0; i < TFs.size(); ++i) {
1472     SDNode *TF = TFs[i];
1474     // Check each of the operands.
1475     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1476       SDValue Op = TF->getOperand(i);
1478       switch (Op.getOpcode()) {
1479       case ISD::EntryToken:
1480         // Entry tokens don't need to be added to the list. They are
1481         // rededundant.
1482         Changed = true;
1483         break;
1485       case ISD::TokenFactor:
1486         if (Op.hasOneUse() &&
1487             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1488           // Queue up for processing.
1489           TFs.push_back(Op.getNode());
1490           // Clean up in case the token factor is removed.
1491           AddToWorklist(Op.getNode());
1492           Changed = true;
1493           break;
1494         }
1495         // Fall thru
1497       default:
1498         // Only add if it isn't already in the list.
1499         if (SeenOps.insert(Op.getNode()).second)
1500           Ops.push_back(Op);
1501         else
1502           Changed = true;
1503         break;
1504       }
1505     }
1506   }
1508   SDValue Result;
1510   // If we've change things around then replace token factor.
1511   if (Changed) {
1512     if (Ops.empty()) {
1513       // The entry token is the only possible outcome.
1514       Result = DAG.getEntryNode();
1515     } else {
1516       // New and improved token factor.
1517       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1518     }
1520     // Don't add users to work list.
1521     return CombineTo(N, Result, false);
1522   }
1524   return Result;
1527 /// MERGE_VALUES can always be eliminated.
1528 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1529   WorklistRemover DeadNodes(*this);
1530   // Replacing results may cause a different MERGE_VALUES to suddenly
1531   // be CSE'd with N, and carry its uses with it. Iterate until no
1532   // uses remain, to ensure that the node can be safely deleted.
1533   // First add the users of this node to the work list so that they
1534   // can be tried again once they have new operands.
1535   AddUsersToWorklist(N);
1536   do {
1537     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1538       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1539   } while (!N->use_empty());
1540   deleteAndRecombine(N);
1541   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1544 SDValue DAGCombiner::visitADD(SDNode *N) {
1545   SDValue N0 = N->getOperand(0);
1546   SDValue N1 = N->getOperand(1);
1547   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1548   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1549   EVT VT = N0.getValueType();
1551   // fold vector ops
1552   if (VT.isVector()) {
1553     SDValue FoldedVOp = SimplifyVBinOp(N);
1554     if (FoldedVOp.getNode()) return FoldedVOp;
1556     // fold (add x, 0) -> x, vector edition
1557     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1558       return N0;
1559     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1560       return N1;
1561   }
1563   // fold (add x, undef) -> undef
1564   if (N0.getOpcode() == ISD::UNDEF)
1565     return N0;
1566   if (N1.getOpcode() == ISD::UNDEF)
1567     return N1;
1568   // fold (add c1, c2) -> c1+c2
1569   if (N0C && N1C)
1570     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1571   // canonicalize constant to RHS
1572   if (N0C && !N1C)
1573     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1574   // fold (add x, 0) -> x
1575   if (N1C && N1C->isNullValue())
1576     return N0;
1577   // fold (add Sym, c) -> Sym+c
1578   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1579     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1580         GA->getOpcode() == ISD::GlobalAddress)
1581       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1582                                   GA->getOffset() +
1583                                     (uint64_t)N1C->getSExtValue());
1584   // fold ((c1-A)+c2) -> (c1+c2)-A
1585   if (N1C && N0.getOpcode() == ISD::SUB)
1586     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1587       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1588                          DAG.getConstant(N1C->getAPIntValue()+
1589                                          N0C->getAPIntValue(), VT),
1590                          N0.getOperand(1));
1591   // reassociate add
1592   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1593   if (RADD.getNode())
1594     return RADD;
1595   // fold ((0-A) + B) -> B-A
1596   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1597       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1598     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1599   // fold (A + (0-B)) -> A-B
1600   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1601       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1602     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1603   // fold (A+(B-A)) -> B
1604   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1605     return N1.getOperand(0);
1606   // fold ((B-A)+A) -> B
1607   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1608     return N0.getOperand(0);
1609   // fold (A+(B-(A+C))) to (B-C)
1610   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1611       N0 == N1.getOperand(1).getOperand(0))
1612     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1613                        N1.getOperand(1).getOperand(1));
1614   // fold (A+(B-(C+A))) to (B-C)
1615   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1616       N0 == N1.getOperand(1).getOperand(1))
1617     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1618                        N1.getOperand(1).getOperand(0));
1619   // fold (A+((B-A)+or-C)) to (B+or-C)
1620   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1621       N1.getOperand(0).getOpcode() == ISD::SUB &&
1622       N0 == N1.getOperand(0).getOperand(1))
1623     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1624                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1626   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1627   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1628     SDValue N00 = N0.getOperand(0);
1629     SDValue N01 = N0.getOperand(1);
1630     SDValue N10 = N1.getOperand(0);
1631     SDValue N11 = N1.getOperand(1);
1633     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1634       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1635                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1636                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1637   }
1639   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1640     return SDValue(N, 0);
1642   // fold (a+b) -> (a|b) iff a and b share no bits.
1643   if (VT.isInteger() && !VT.isVector()) {
1644     APInt LHSZero, LHSOne;
1645     APInt RHSZero, RHSOne;
1646     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1648     if (LHSZero.getBoolValue()) {
1649       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1651       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1652       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1653       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1654         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1655           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1656       }
1657     }
1658   }
1660   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1661   if (N1.getOpcode() == ISD::SHL &&
1662       N1.getOperand(0).getOpcode() == ISD::SUB)
1663     if (ConstantSDNode *C =
1664           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1665       if (C->getAPIntValue() == 0)
1666         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1667                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1668                                        N1.getOperand(0).getOperand(1),
1669                                        N1.getOperand(1)));
1670   if (N0.getOpcode() == ISD::SHL &&
1671       N0.getOperand(0).getOpcode() == ISD::SUB)
1672     if (ConstantSDNode *C =
1673           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1674       if (C->getAPIntValue() == 0)
1675         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1676                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1677                                        N0.getOperand(0).getOperand(1),
1678                                        N0.getOperand(1)));
1680   if (N1.getOpcode() == ISD::AND) {
1681     SDValue AndOp0 = N1.getOperand(0);
1682     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1683     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1684     unsigned DestBits = VT.getScalarType().getSizeInBits();
1686     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1687     // and similar xforms where the inner op is either ~0 or 0.
1688     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1689       SDLoc DL(N);
1690       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1691     }
1692   }
1694   // add (sext i1), X -> sub X, (zext i1)
1695   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1696       N0.getOperand(0).getValueType() == MVT::i1 &&
1697       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1698     SDLoc DL(N);
1699     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1700     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1701   }
1703   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1704   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1705     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1706     if (TN->getVT() == MVT::i1) {
1707       SDLoc DL(N);
1708       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1709                                  DAG.getConstant(1, VT));
1710       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1711     }
1712   }
1714   return SDValue();
1717 SDValue DAGCombiner::visitADDC(SDNode *N) {
1718   SDValue N0 = N->getOperand(0);
1719   SDValue N1 = N->getOperand(1);
1720   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1721   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1722   EVT VT = N0.getValueType();
1724   // If the flag result is dead, turn this into an ADD.
1725   if (!N->hasAnyUseOfValue(1))
1726     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1727                      DAG.getNode(ISD::CARRY_FALSE,
1728                                  SDLoc(N), MVT::Glue));
1730   // canonicalize constant to RHS.
1731   if (N0C && !N1C)
1732     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1734   // fold (addc x, 0) -> x + no carry out
1735   if (N1C && N1C->isNullValue())
1736     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1737                                         SDLoc(N), MVT::Glue));
1739   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1740   APInt LHSZero, LHSOne;
1741   APInt RHSZero, RHSOne;
1742   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1744   if (LHSZero.getBoolValue()) {
1745     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1747     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1748     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1749     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1750       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1751                        DAG.getNode(ISD::CARRY_FALSE,
1752                                    SDLoc(N), MVT::Glue));
1753   }
1755   return SDValue();
1758 SDValue DAGCombiner::visitADDE(SDNode *N) {
1759   SDValue N0 = N->getOperand(0);
1760   SDValue N1 = N->getOperand(1);
1761   SDValue CarryIn = N->getOperand(2);
1762   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1763   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1765   // canonicalize constant to RHS
1766   if (N0C && !N1C)
1767     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1768                        N1, N0, CarryIn);
1770   // fold (adde x, y, false) -> (addc x, y)
1771   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1772     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1774   return SDValue();
1777 // Since it may not be valid to emit a fold to zero for vector initializers
1778 // check if we can before folding.
1779 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1780                              SelectionDAG &DAG,
1781                              bool LegalOperations, bool LegalTypes) {
1782   if (!VT.isVector())
1783     return DAG.getConstant(0, VT);
1784   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1785     return DAG.getConstant(0, VT);
1786   return SDValue();
1789 SDValue DAGCombiner::visitSUB(SDNode *N) {
1790   SDValue N0 = N->getOperand(0);
1791   SDValue N1 = N->getOperand(1);
1792   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1793   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1794   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1795     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1796   EVT VT = N0.getValueType();
1798   // fold vector ops
1799   if (VT.isVector()) {
1800     SDValue FoldedVOp = SimplifyVBinOp(N);
1801     if (FoldedVOp.getNode()) return FoldedVOp;
1803     // fold (sub x, 0) -> x, vector edition
1804     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1805       return N0;
1806   }
1808   // fold (sub x, x) -> 0
1809   // FIXME: Refactor this and xor and other similar operations together.
1810   if (N0 == N1)
1811     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1812   // fold (sub c1, c2) -> c1-c2
1813   if (N0C && N1C)
1814     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1815   // fold (sub x, c) -> (add x, -c)
1816   if (N1C)
1817     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1818                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1819   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1820   if (N0C && N0C->isAllOnesValue())
1821     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1822   // fold A-(A-B) -> B
1823   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1824     return N1.getOperand(1);
1825   // fold (A+B)-A -> B
1826   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1827     return N0.getOperand(1);
1828   // fold (A+B)-B -> A
1829   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1830     return N0.getOperand(0);
1831   // fold C2-(A+C1) -> (C2-C1)-A
1832   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1833     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1834                                    VT);
1835     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1836                        N1.getOperand(0));
1837   }
1838   // fold ((A+(B+or-C))-B) -> A+or-C
1839   if (N0.getOpcode() == ISD::ADD &&
1840       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1841        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1842       N0.getOperand(1).getOperand(0) == N1)
1843     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1844                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1845   // fold ((A+(C+B))-B) -> A+C
1846   if (N0.getOpcode() == ISD::ADD &&
1847       N0.getOperand(1).getOpcode() == ISD::ADD &&
1848       N0.getOperand(1).getOperand(1) == N1)
1849     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1850                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1851   // fold ((A-(B-C))-C) -> A-B
1852   if (N0.getOpcode() == ISD::SUB &&
1853       N0.getOperand(1).getOpcode() == ISD::SUB &&
1854       N0.getOperand(1).getOperand(1) == N1)
1855     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1856                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1858   // If either operand of a sub is undef, the result is undef
1859   if (N0.getOpcode() == ISD::UNDEF)
1860     return N0;
1861   if (N1.getOpcode() == ISD::UNDEF)
1862     return N1;
1864   // If the relocation model supports it, consider symbol offsets.
1865   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1866     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1867       // fold (sub Sym, c) -> Sym-c
1868       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1869         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1870                                     GA->getOffset() -
1871                                       (uint64_t)N1C->getSExtValue());
1872       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1873       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1874         if (GA->getGlobal() == GB->getGlobal())
1875           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1876                                  VT);
1877     }
1879   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1880   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1881     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1882     if (TN->getVT() == MVT::i1) {
1883       SDLoc DL(N);
1884       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1885                                  DAG.getConstant(1, VT));
1886       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1887     }
1888   }
1890   return SDValue();
1893 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1894   SDValue N0 = N->getOperand(0);
1895   SDValue N1 = N->getOperand(1);
1896   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1897   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1898   EVT VT = N0.getValueType();
1900   // If the flag result is dead, turn this into an SUB.
1901   if (!N->hasAnyUseOfValue(1))
1902     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1903                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1904                                  MVT::Glue));
1906   // fold (subc x, x) -> 0 + no borrow
1907   if (N0 == N1)
1908     return CombineTo(N, DAG.getConstant(0, VT),
1909                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1910                                  MVT::Glue));
1912   // fold (subc x, 0) -> x + no borrow
1913   if (N1C && N1C->isNullValue())
1914     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1915                                         MVT::Glue));
1917   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1918   if (N0C && N0C->isAllOnesValue())
1919     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1920                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1921                                  MVT::Glue));
1923   return SDValue();
1926 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1927   SDValue N0 = N->getOperand(0);
1928   SDValue N1 = N->getOperand(1);
1929   SDValue CarryIn = N->getOperand(2);
1931   // fold (sube x, y, false) -> (subc x, y)
1932   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1933     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1935   return SDValue();
1938 SDValue DAGCombiner::visitMUL(SDNode *N) {
1939   SDValue N0 = N->getOperand(0);
1940   SDValue N1 = N->getOperand(1);
1941   EVT VT = N0.getValueType();
1943   // fold (mul x, undef) -> 0
1944   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1945     return DAG.getConstant(0, VT);
1947   bool N0IsConst = false;
1948   bool N1IsConst = false;
1949   APInt ConstValue0, ConstValue1;
1950   // fold vector ops
1951   if (VT.isVector()) {
1952     SDValue FoldedVOp = SimplifyVBinOp(N);
1953     if (FoldedVOp.getNode()) return FoldedVOp;
1955     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1956     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1957   } else {
1958     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1959     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1960                             : APInt();
1961     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1962     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1963                             : APInt();
1964   }
1966   // fold (mul c1, c2) -> c1*c2
1967   if (N0IsConst && N1IsConst)
1968     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1970   // canonicalize constant to RHS
1971   if (N0IsConst && !N1IsConst)
1972     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1973   // fold (mul x, 0) -> 0
1974   if (N1IsConst && ConstValue1 == 0)
1975     return N1;
1976   // We require a splat of the entire scalar bit width for non-contiguous
1977   // bit patterns.
1978   bool IsFullSplat =
1979     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1980   // fold (mul x, 1) -> x
1981   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1982     return N0;
1983   // fold (mul x, -1) -> 0-x
1984   if (N1IsConst && ConstValue1.isAllOnesValue())
1985     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1986                        DAG.getConstant(0, VT), N0);
1987   // fold (mul x, (1 << c)) -> x << c
1988   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1989     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1990                        DAG.getConstant(ConstValue1.logBase2(),
1991                                        getShiftAmountTy(N0.getValueType())));
1992   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1993   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1994     unsigned Log2Val = (-ConstValue1).logBase2();
1995     // FIXME: If the input is something that is easily negated (e.g. a
1996     // single-use add), we should put the negate there.
1997     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1998                        DAG.getConstant(0, VT),
1999                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2000                             DAG.getConstant(Log2Val,
2001                                       getShiftAmountTy(N0.getValueType()))));
2002   }
2004   APInt Val;
2005   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2006   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2007       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2008                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2009     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2010                              N1, N0.getOperand(1));
2011     AddToWorklist(C3.getNode());
2012     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2013                        N0.getOperand(0), C3);
2014   }
2016   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2017   // use.
2018   {
2019     SDValue Sh(nullptr,0), Y(nullptr,0);
2020     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2021     if (N0.getOpcode() == ISD::SHL &&
2022         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2023                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2024         N0.getNode()->hasOneUse()) {
2025       Sh = N0; Y = N1;
2026     } else if (N1.getOpcode() == ISD::SHL &&
2027                isa<ConstantSDNode>(N1.getOperand(1)) &&
2028                N1.getNode()->hasOneUse()) {
2029       Sh = N1; Y = N0;
2030     }
2032     if (Sh.getNode()) {
2033       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2034                                 Sh.getOperand(0), Y);
2035       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2036                          Mul, Sh.getOperand(1));
2037     }
2038   }
2040   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2041   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2042       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2043                      isa<ConstantSDNode>(N0.getOperand(1))))
2044     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2045                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2046                                    N0.getOperand(0), N1),
2047                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2048                                    N0.getOperand(1), N1));
2050   // reassociate mul
2051   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2052   if (RMUL.getNode())
2053     return RMUL;
2055   return SDValue();
2058 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2059   SDValue N0 = N->getOperand(0);
2060   SDValue N1 = N->getOperand(1);
2061   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2062   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2063   EVT VT = N->getValueType(0);
2065   // fold vector ops
2066   if (VT.isVector()) {
2067     SDValue FoldedVOp = SimplifyVBinOp(N);
2068     if (FoldedVOp.getNode()) return FoldedVOp;
2069   }
2071   // fold (sdiv c1, c2) -> c1/c2
2072   if (N0C && N1C && !N1C->isNullValue())
2073     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2074   // fold (sdiv X, 1) -> X
2075   if (N1C && N1C->getAPIntValue() == 1LL)
2076     return N0;
2077   // fold (sdiv X, -1) -> 0-X
2078   if (N1C && N1C->isAllOnesValue())
2079     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2080                        DAG.getConstant(0, VT), N0);
2081   // If we know the sign bits of both operands are zero, strength reduce to a
2082   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2083   if (!VT.isVector()) {
2084     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2085       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2086                          N0, N1);
2087   }
2089   // fold (sdiv X, pow2) -> simple ops after legalize
2090   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2091                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2092     // If dividing by powers of two is cheap, then don't perform the following
2093     // fold.
2094     if (TLI.isPow2SDivCheap())
2095       return SDValue();
2097     // Target-specific implementation of sdiv x, pow2.
2098     SDValue Res = BuildSDIVPow2(N);
2099     if (Res.getNode())
2100       return Res;
2102     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2104     // Splat the sign bit into the register
2105     SDValue SGN =
2106         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2107                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2108                                     getShiftAmountTy(N0.getValueType())));
2109     AddToWorklist(SGN.getNode());
2111     // Add (N0 < 0) ? abs2 - 1 : 0;
2112     SDValue SRL =
2113         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2114                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2115                                     getShiftAmountTy(SGN.getValueType())));
2116     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2117     AddToWorklist(SRL.getNode());
2118     AddToWorklist(ADD.getNode());    // Divide by pow2
2119     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2120                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2122     // If we're dividing by a positive value, we're done.  Otherwise, we must
2123     // negate the result.
2124     if (N1C->getAPIntValue().isNonNegative())
2125       return SRA;
2127     AddToWorklist(SRA.getNode());
2128     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2129   }
2131   // if integer divide is expensive and we satisfy the requirements, emit an
2132   // alternate sequence.
2133   if (N1C && !TLI.isIntDivCheap()) {
2134     SDValue Op = BuildSDIV(N);
2135     if (Op.getNode()) return Op;
2136   }
2138   // undef / X -> 0
2139   if (N0.getOpcode() == ISD::UNDEF)
2140     return DAG.getConstant(0, VT);
2141   // X / undef -> undef
2142   if (N1.getOpcode() == ISD::UNDEF)
2143     return N1;
2145   return SDValue();
2148 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2149   SDValue N0 = N->getOperand(0);
2150   SDValue N1 = N->getOperand(1);
2151   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2152   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2153   EVT VT = N->getValueType(0);
2155   // fold vector ops
2156   if (VT.isVector()) {
2157     SDValue FoldedVOp = SimplifyVBinOp(N);
2158     if (FoldedVOp.getNode()) return FoldedVOp;
2159   }
2161   // fold (udiv c1, c2) -> c1/c2
2162   if (N0C && N1C && !N1C->isNullValue())
2163     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2164   // fold (udiv x, (1 << c)) -> x >>u c
2165   if (N1C && N1C->getAPIntValue().isPowerOf2())
2166     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2167                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2168                                        getShiftAmountTy(N0.getValueType())));
2169   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2170   if (N1.getOpcode() == ISD::SHL) {
2171     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2172       if (SHC->getAPIntValue().isPowerOf2()) {
2173         EVT ADDVT = N1.getOperand(1).getValueType();
2174         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2175                                   N1.getOperand(1),
2176                                   DAG.getConstant(SHC->getAPIntValue()
2177                                                                   .logBase2(),
2178                                                   ADDVT));
2179         AddToWorklist(Add.getNode());
2180         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2181       }
2182     }
2183   }
2184   // fold (udiv x, c) -> alternate
2185   if (N1C && !TLI.isIntDivCheap()) {
2186     SDValue Op = BuildUDIV(N);
2187     if (Op.getNode()) return Op;
2188   }
2190   // undef / X -> 0
2191   if (N0.getOpcode() == ISD::UNDEF)
2192     return DAG.getConstant(0, VT);
2193   // X / undef -> undef
2194   if (N1.getOpcode() == ISD::UNDEF)
2195     return N1;
2197   return SDValue();
2200 SDValue DAGCombiner::visitSREM(SDNode *N) {
2201   SDValue N0 = N->getOperand(0);
2202   SDValue N1 = N->getOperand(1);
2203   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2204   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2205   EVT VT = N->getValueType(0);
2207   // fold (srem c1, c2) -> c1%c2
2208   if (N0C && N1C && !N1C->isNullValue())
2209     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2210   // If we know the sign bits of both operands are zero, strength reduce to a
2211   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2212   if (!VT.isVector()) {
2213     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2214       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2215   }
2217   // If X/C can be simplified by the division-by-constant logic, lower
2218   // X%C to the equivalent of X-X/C*C.
2219   if (N1C && !N1C->isNullValue()) {
2220     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2221     AddToWorklist(Div.getNode());
2222     SDValue OptimizedDiv = combine(Div.getNode());
2223     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2224       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2225                                 OptimizedDiv, N1);
2226       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2227       AddToWorklist(Mul.getNode());
2228       return Sub;
2229     }
2230   }
2232   // undef % X -> 0
2233   if (N0.getOpcode() == ISD::UNDEF)
2234     return DAG.getConstant(0, VT);
2235   // X % undef -> undef
2236   if (N1.getOpcode() == ISD::UNDEF)
2237     return N1;
2239   return SDValue();
2242 SDValue DAGCombiner::visitUREM(SDNode *N) {
2243   SDValue N0 = N->getOperand(0);
2244   SDValue N1 = N->getOperand(1);
2245   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2246   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2247   EVT VT = N->getValueType(0);
2249   // fold (urem c1, c2) -> c1%c2
2250   if (N0C && N1C && !N1C->isNullValue())
2251     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2252   // fold (urem x, pow2) -> (and x, pow2-1)
2253   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2254     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2255                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2256   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2257   if (N1.getOpcode() == ISD::SHL) {
2258     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2259       if (SHC->getAPIntValue().isPowerOf2()) {
2260         SDValue Add =
2261           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2262                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2263                                  VT));
2264         AddToWorklist(Add.getNode());
2265         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2266       }
2267     }
2268   }
2270   // If X/C can be simplified by the division-by-constant logic, lower
2271   // X%C to the equivalent of X-X/C*C.
2272   if (N1C && !N1C->isNullValue()) {
2273     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2274     AddToWorklist(Div.getNode());
2275     SDValue OptimizedDiv = combine(Div.getNode());
2276     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2277       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2278                                 OptimizedDiv, N1);
2279       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2280       AddToWorklist(Mul.getNode());
2281       return Sub;
2282     }
2283   }
2285   // undef % X -> 0
2286   if (N0.getOpcode() == ISD::UNDEF)
2287     return DAG.getConstant(0, VT);
2288   // X % undef -> undef
2289   if (N1.getOpcode() == ISD::UNDEF)
2290     return N1;
2292   return SDValue();
2295 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2296   SDValue N0 = N->getOperand(0);
2297   SDValue N1 = N->getOperand(1);
2298   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2299   EVT VT = N->getValueType(0);
2300   SDLoc DL(N);
2302   // fold (mulhs x, 0) -> 0
2303   if (N1C && N1C->isNullValue())
2304     return N1;
2305   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2306   if (N1C && N1C->getAPIntValue() == 1)
2307     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2308                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2309                                        getShiftAmountTy(N0.getValueType())));
2310   // fold (mulhs x, undef) -> 0
2311   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2312     return DAG.getConstant(0, VT);
2314   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2315   // plus a shift.
2316   if (VT.isSimple() && !VT.isVector()) {
2317     MVT Simple = VT.getSimpleVT();
2318     unsigned SimpleSize = Simple.getSizeInBits();
2319     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2320     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2321       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2322       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2323       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2324       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2325             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2326       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2327     }
2328   }
2330   return SDValue();
2333 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2334   SDValue N0 = N->getOperand(0);
2335   SDValue N1 = N->getOperand(1);
2336   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2337   EVT VT = N->getValueType(0);
2338   SDLoc DL(N);
2340   // fold (mulhu x, 0) -> 0
2341   if (N1C && N1C->isNullValue())
2342     return N1;
2343   // fold (mulhu x, 1) -> 0
2344   if (N1C && N1C->getAPIntValue() == 1)
2345     return DAG.getConstant(0, N0.getValueType());
2346   // fold (mulhu x, undef) -> 0
2347   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2348     return DAG.getConstant(0, VT);
2350   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2351   // plus a shift.
2352   if (VT.isSimple() && !VT.isVector()) {
2353     MVT Simple = VT.getSimpleVT();
2354     unsigned SimpleSize = Simple.getSizeInBits();
2355     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2356     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2357       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2358       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2359       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2360       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2361             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2362       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2363     }
2364   }
2366   return SDValue();
2369 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2370 /// give the opcodes for the two computations that are being performed. Return
2371 /// true if a simplification was made.
2372 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2373                                                 unsigned HiOp) {
2374   // If the high half is not needed, just compute the low half.
2375   bool HiExists = N->hasAnyUseOfValue(1);
2376   if (!HiExists &&
2377       (!LegalOperations ||
2378        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2379     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2380     return CombineTo(N, Res, Res);
2381   }
2383   // If the low half is not needed, just compute the high half.
2384   bool LoExists = N->hasAnyUseOfValue(0);
2385   if (!LoExists &&
2386       (!LegalOperations ||
2387        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2388     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2389     return CombineTo(N, Res, Res);
2390   }
2392   // If both halves are used, return as it is.
2393   if (LoExists && HiExists)
2394     return SDValue();
2396   // If the two computed results can be simplified separately, separate them.
2397   if (LoExists) {
2398     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2399     AddToWorklist(Lo.getNode());
2400     SDValue LoOpt = combine(Lo.getNode());
2401     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2402         (!LegalOperations ||
2403          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2404       return CombineTo(N, LoOpt, LoOpt);
2405   }
2407   if (HiExists) {
2408     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2409     AddToWorklist(Hi.getNode());
2410     SDValue HiOpt = combine(Hi.getNode());
2411     if (HiOpt.getNode() && HiOpt != Hi &&
2412         (!LegalOperations ||
2413          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2414       return CombineTo(N, HiOpt, HiOpt);
2415   }
2417   return SDValue();
2420 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2421   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2422   if (Res.getNode()) return Res;
2424   EVT VT = N->getValueType(0);
2425   SDLoc DL(N);
2427   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2428   // plus a shift.
2429   if (VT.isSimple() && !VT.isVector()) {
2430     MVT Simple = VT.getSimpleVT();
2431     unsigned SimpleSize = Simple.getSizeInBits();
2432     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2433     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2434       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2435       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2436       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2437       // Compute the high part as N1.
2438       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2439             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2440       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2441       // Compute the low part as N0.
2442       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2443       return CombineTo(N, Lo, Hi);
2444     }
2445   }
2447   return SDValue();
2450 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2451   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2452   if (Res.getNode()) return Res;
2454   EVT VT = N->getValueType(0);
2455   SDLoc DL(N);
2457   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2458   // plus a shift.
2459   if (VT.isSimple() && !VT.isVector()) {
2460     MVT Simple = VT.getSimpleVT();
2461     unsigned SimpleSize = Simple.getSizeInBits();
2462     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2463     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2464       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2465       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2466       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2467       // Compute the high part as N1.
2468       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2469             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2470       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2471       // Compute the low part as N0.
2472       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2473       return CombineTo(N, Lo, Hi);
2474     }
2475   }
2477   return SDValue();
2480 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2481   // (smulo x, 2) -> (saddo x, x)
2482   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2483     if (C2->getAPIntValue() == 2)
2484       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2485                          N->getOperand(0), N->getOperand(0));
2487   return SDValue();
2490 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2491   // (umulo x, 2) -> (uaddo x, x)
2492   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2493     if (C2->getAPIntValue() == 2)
2494       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2495                          N->getOperand(0), N->getOperand(0));
2497   return SDValue();
2500 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2501   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2502   if (Res.getNode()) return Res;
2504   return SDValue();
2507 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2508   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2509   if (Res.getNode()) return Res;
2511   return SDValue();
2514 /// If this is a binary operator with two operands of the same opcode, try to
2515 /// simplify it.
2516 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2517   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2518   EVT VT = N0.getValueType();
2519   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2521   // Bail early if none of these transforms apply.
2522   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2524   // For each of OP in AND/OR/XOR:
2525   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2526   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2527   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2528   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2529   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2530   //
2531   // do not sink logical op inside of a vector extend, since it may combine
2532   // into a vsetcc.
2533   EVT Op0VT = N0.getOperand(0).getValueType();
2534   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2535        N0.getOpcode() == ISD::SIGN_EXTEND ||
2536        N0.getOpcode() == ISD::BSWAP ||
2537        // Avoid infinite looping with PromoteIntBinOp.
2538        (N0.getOpcode() == ISD::ANY_EXTEND &&
2539         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2540        (N0.getOpcode() == ISD::TRUNCATE &&
2541         (!TLI.isZExtFree(VT, Op0VT) ||
2542          !TLI.isTruncateFree(Op0VT, VT)) &&
2543         TLI.isTypeLegal(Op0VT))) &&
2544       !VT.isVector() &&
2545       Op0VT == N1.getOperand(0).getValueType() &&
2546       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2547     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2548                                  N0.getOperand(0).getValueType(),
2549                                  N0.getOperand(0), N1.getOperand(0));
2550     AddToWorklist(ORNode.getNode());
2551     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2552   }
2554   // For each of OP in SHL/SRL/SRA/AND...
2555   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2556   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2557   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2558   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2559        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2560       N0.getOperand(1) == N1.getOperand(1)) {
2561     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2562                                  N0.getOperand(0).getValueType(),
2563                                  N0.getOperand(0), N1.getOperand(0));
2564     AddToWorklist(ORNode.getNode());
2565     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2566                        ORNode, N0.getOperand(1));
2567   }
2569   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2570   // Only perform this optimization after type legalization and before
2571   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2572   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2573   // we don't want to undo this promotion.
2574   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2575   // on scalars.
2576   if ((N0.getOpcode() == ISD::BITCAST ||
2577        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2578       Level == AfterLegalizeTypes) {
2579     SDValue In0 = N0.getOperand(0);
2580     SDValue In1 = N1.getOperand(0);
2581     EVT In0Ty = In0.getValueType();
2582     EVT In1Ty = In1.getValueType();
2583     SDLoc DL(N);
2584     // If both incoming values are integers, and the original types are the
2585     // same.
2586     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2587       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2588       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2589       AddToWorklist(Op.getNode());
2590       return BC;
2591     }
2592   }
2594   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2595   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2596   // If both shuffles use the same mask, and both shuffle within a single
2597   // vector, then it is worthwhile to move the swizzle after the operation.
2598   // The type-legalizer generates this pattern when loading illegal
2599   // vector types from memory. In many cases this allows additional shuffle
2600   // optimizations.
2601   // There are other cases where moving the shuffle after the xor/and/or
2602   // is profitable even if shuffles don't perform a swizzle.
2603   // If both shuffles use the same mask, and both shuffles have the same first
2604   // or second operand, then it might still be profitable to move the shuffle
2605   // after the xor/and/or operation.
2606   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2607     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2608     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2610     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2611            "Inputs to shuffles are not the same type");
2613     // Check that both shuffles use the same mask. The masks are known to be of
2614     // the same length because the result vector type is the same.
2615     // Check also that shuffles have only one use to avoid introducing extra
2616     // instructions.
2617     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2618         SVN0->getMask().equals(SVN1->getMask())) {
2619       SDValue ShOp = N0->getOperand(1);
2621       // Don't try to fold this node if it requires introducing a
2622       // build vector of all zeros that might be illegal at this stage.
2623       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2624         if (!LegalTypes)
2625           ShOp = DAG.getConstant(0, VT);
2626         else
2627           ShOp = SDValue();
2628       }
2630       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2631       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2632       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2633       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2634         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2635                                       N0->getOperand(0), N1->getOperand(0));
2636         AddToWorklist(NewNode.getNode());
2637         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2638                                     &SVN0->getMask()[0]);
2639       }
2641       // Don't try to fold this node if it requires introducing a
2642       // build vector of all zeros that might be illegal at this stage.
2643       ShOp = N0->getOperand(0);
2644       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2645         if (!LegalTypes)
2646           ShOp = DAG.getConstant(0, VT);
2647         else
2648           ShOp = SDValue();
2649       }
2651       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2652       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2653       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2654       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2655         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2656                                       N0->getOperand(1), N1->getOperand(1));
2657         AddToWorklist(NewNode.getNode());
2658         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2659                                     &SVN0->getMask()[0]);
2660       }
2661     }
2662   }
2664   return SDValue();
2667 SDValue DAGCombiner::visitAND(SDNode *N) {
2668   SDValue N0 = N->getOperand(0);
2669   SDValue N1 = N->getOperand(1);
2670   SDValue LL, LR, RL, RR, CC0, CC1;
2671   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2672   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2673   EVT VT = N1.getValueType();
2674   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2676   // fold vector ops
2677   if (VT.isVector()) {
2678     SDValue FoldedVOp = SimplifyVBinOp(N);
2679     if (FoldedVOp.getNode()) return FoldedVOp;
2681     // fold (and x, 0) -> 0, vector edition
2682     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2683       // do not return N0, because undef node may exist in N0
2684       return DAG.getConstant(
2685           APInt::getNullValue(
2686               N0.getValueType().getScalarType().getSizeInBits()),
2687           N0.getValueType());
2688     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2689       // do not return N1, because undef node may exist in N1
2690       return DAG.getConstant(
2691           APInt::getNullValue(
2692               N1.getValueType().getScalarType().getSizeInBits()),
2693           N1.getValueType());
2695     // fold (and x, -1) -> x, vector edition
2696     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2697       return N1;
2698     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2699       return N0;
2700   }
2702   // fold (and x, undef) -> 0
2703   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2704     return DAG.getConstant(0, VT);
2705   // fold (and c1, c2) -> c1&c2
2706   if (N0C && N1C)
2707     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2708   // canonicalize constant to RHS
2709   if (N0C && !N1C)
2710     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2711   // fold (and x, -1) -> x
2712   if (N1C && N1C->isAllOnesValue())
2713     return N0;
2714   // if (and x, c) is known to be zero, return 0
2715   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2716                                    APInt::getAllOnesValue(BitWidth)))
2717     return DAG.getConstant(0, VT);
2718   // reassociate and
2719   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2720   if (RAND.getNode())
2721     return RAND;
2722   // fold (and (or x, C), D) -> D if (C & D) == D
2723   if (N1C && N0.getOpcode() == ISD::OR)
2724     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2725       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2726         return N1;
2727   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2728   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2729     SDValue N0Op0 = N0.getOperand(0);
2730     APInt Mask = ~N1C->getAPIntValue();
2731     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2732     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2733       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2734                                  N0.getValueType(), N0Op0);
2736       // Replace uses of the AND with uses of the Zero extend node.
2737       CombineTo(N, Zext);
2739       // We actually want to replace all uses of the any_extend with the
2740       // zero_extend, to avoid duplicating things.  This will later cause this
2741       // AND to be folded.
2742       CombineTo(N0.getNode(), Zext);
2743       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2744     }
2745   }
2746   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2747   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2748   // already be zero by virtue of the width of the base type of the load.
2749   //
2750   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2751   // more cases.
2752   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2753        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2754       N0.getOpcode() == ISD::LOAD) {
2755     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2756                                          N0 : N0.getOperand(0) );
2758     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2759     // This can be a pure constant or a vector splat, in which case we treat the
2760     // vector as a scalar and use the splat value.
2761     APInt Constant = APInt::getNullValue(1);
2762     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2763       Constant = C->getAPIntValue();
2764     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2765       APInt SplatValue, SplatUndef;
2766       unsigned SplatBitSize;
2767       bool HasAnyUndefs;
2768       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2769                                              SplatBitSize, HasAnyUndefs);
2770       if (IsSplat) {
2771         // Undef bits can contribute to a possible optimisation if set, so
2772         // set them.
2773         SplatValue |= SplatUndef;
2775         // The splat value may be something like "0x00FFFFFF", which means 0 for
2776         // the first vector value and FF for the rest, repeating. We need a mask
2777         // that will apply equally to all members of the vector, so AND all the
2778         // lanes of the constant together.
2779         EVT VT = Vector->getValueType(0);
2780         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2782         // If the splat value has been compressed to a bitlength lower
2783         // than the size of the vector lane, we need to re-expand it to
2784         // the lane size.
2785         if (BitWidth > SplatBitSize)
2786           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2787                SplatBitSize < BitWidth;
2788                SplatBitSize = SplatBitSize * 2)
2789             SplatValue |= SplatValue.shl(SplatBitSize);
2791         Constant = APInt::getAllOnesValue(BitWidth);
2792         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2793           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2794       }
2795     }
2797     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2798     // actually legal and isn't going to get expanded, else this is a false
2799     // optimisation.
2800     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2801                                                     Load->getValueType(0),
2802                                                     Load->getMemoryVT());
2804     // Resize the constant to the same size as the original memory access before
2805     // extension. If it is still the AllOnesValue then this AND is completely
2806     // unneeded.
2807     Constant =
2808       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2810     bool B;
2811     switch (Load->getExtensionType()) {
2812     default: B = false; break;
2813     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2814     case ISD::ZEXTLOAD:
2815     case ISD::NON_EXTLOAD: B = true; break;
2816     }
2818     if (B && Constant.isAllOnesValue()) {
2819       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2820       // preserve semantics once we get rid of the AND.
2821       SDValue NewLoad(Load, 0);
2822       if (Load->getExtensionType() == ISD::EXTLOAD) {
2823         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2824                               Load->getValueType(0), SDLoc(Load),
2825                               Load->getChain(), Load->getBasePtr(),
2826                               Load->getOffset(), Load->getMemoryVT(),
2827                               Load->getMemOperand());
2828         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2829         if (Load->getNumValues() == 3) {
2830           // PRE/POST_INC loads have 3 values.
2831           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2832                            NewLoad.getValue(2) };
2833           CombineTo(Load, To, 3, true);
2834         } else {
2835           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2836         }
2837       }
2839       // Fold the AND away, taking care not to fold to the old load node if we
2840       // replaced it.
2841       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2843       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2844     }
2845   }
2846   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2847   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2848     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2849     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2851     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2852         LL.getValueType().isInteger()) {
2853       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2854       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2855         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2856                                      LR.getValueType(), LL, RL);
2857         AddToWorklist(ORNode.getNode());
2858         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2859       }
2860       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2861       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2862         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2863                                       LR.getValueType(), LL, RL);
2864         AddToWorklist(ANDNode.getNode());
2865         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2866       }
2867       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2868       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2869         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2870                                      LR.getValueType(), LL, RL);
2871         AddToWorklist(ORNode.getNode());
2872         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2873       }
2874     }
2875     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2876     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2877         Op0 == Op1 && LL.getValueType().isInteger() &&
2878       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2879                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2880                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2881                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2882       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2883                                     LL, DAG.getConstant(1, LL.getValueType()));
2884       AddToWorklist(ADDNode.getNode());
2885       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2886                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2887     }
2888     // canonicalize equivalent to ll == rl
2889     if (LL == RR && LR == RL) {
2890       Op1 = ISD::getSetCCSwappedOperands(Op1);
2891       std::swap(RL, RR);
2892     }
2893     if (LL == RL && LR == RR) {
2894       bool isInteger = LL.getValueType().isInteger();
2895       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2896       if (Result != ISD::SETCC_INVALID &&
2897           (!LegalOperations ||
2898            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2899             TLI.isOperationLegal(ISD::SETCC,
2900                             getSetCCResultType(N0.getSimpleValueType())))))
2901         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2902                             LL, LR, Result);
2903     }
2904   }
2906   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2907   if (N0.getOpcode() == N1.getOpcode()) {
2908     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2909     if (Tmp.getNode()) return Tmp;
2910   }
2912   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2913   // fold (and (sra)) -> (and (srl)) when possible.
2914   if (!VT.isVector() &&
2915       SimplifyDemandedBits(SDValue(N, 0)))
2916     return SDValue(N, 0);
2918   // fold (zext_inreg (extload x)) -> (zextload x)
2919   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2920     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2921     EVT MemVT = LN0->getMemoryVT();
2922     // If we zero all the possible extended bits, then we can turn this into
2923     // a zextload if we are running before legalize or the operation is legal.
2924     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2925     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2926                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2927         ((!LegalOperations && !LN0->isVolatile()) ||
2928          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
2929       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2930                                        LN0->getChain(), LN0->getBasePtr(),
2931                                        MemVT, LN0->getMemOperand());
2932       AddToWorklist(N);
2933       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2934       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2935     }
2936   }
2937   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2938   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2939       N0.hasOneUse()) {
2940     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2941     EVT MemVT = LN0->getMemoryVT();
2942     // If we zero all the possible extended bits, then we can turn this into
2943     // a zextload if we are running before legalize or the operation is legal.
2944     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2945     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2946                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2947         ((!LegalOperations && !LN0->isVolatile()) ||
2948          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
2949       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2950                                        LN0->getChain(), LN0->getBasePtr(),
2951                                        MemVT, LN0->getMemOperand());
2952       AddToWorklist(N);
2953       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2954       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2955     }
2956   }
2958   // fold (and (load x), 255) -> (zextload x, i8)
2959   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2960   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2961   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2962               (N0.getOpcode() == ISD::ANY_EXTEND &&
2963                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2964     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2965     LoadSDNode *LN0 = HasAnyExt
2966       ? cast<LoadSDNode>(N0.getOperand(0))
2967       : cast<LoadSDNode>(N0);
2968     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2969         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2970       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2971       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2972         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2973         EVT LoadedVT = LN0->getMemoryVT();
2974         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2976         if (ExtVT == LoadedVT &&
2977             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
2978                                                     ExtVT))) {
2980           SDValue NewLoad =
2981             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2982                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2983                            LN0->getMemOperand());
2984           AddToWorklist(N);
2985           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2986           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2987         }
2989         // Do not change the width of a volatile load.
2990         // Do not generate loads of non-round integer types since these can
2991         // be expensive (and would be wrong if the type is not byte sized).
2992         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2993             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
2994                                                     ExtVT))) {
2995           EVT PtrType = LN0->getOperand(1).getValueType();
2997           unsigned Alignment = LN0->getAlignment();
2998           SDValue NewPtr = LN0->getBasePtr();
3000           // For big endian targets, we need to add an offset to the pointer
3001           // to load the correct bytes.  For little endian systems, we merely
3002           // need to read fewer bytes from the same pointer.
3003           if (TLI.isBigEndian()) {
3004             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3005             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3006             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3007             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
3008                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
3009             Alignment = MinAlign(Alignment, PtrOff);
3010           }
3012           AddToWorklist(NewPtr.getNode());
3014           SDValue Load =
3015             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3016                            LN0->getChain(), NewPtr,
3017                            LN0->getPointerInfo(),
3018                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3019                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3020           AddToWorklist(N);
3021           CombineTo(LN0, Load, Load.getValue(1));
3022           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3023         }
3024       }
3025     }
3026   }
3028   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3029       VT.getSizeInBits() <= 64) {
3030     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3031       APInt ADDC = ADDI->getAPIntValue();
3032       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3033         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3034         // immediate for an add, but it is legal if its top c2 bits are set,
3035         // transform the ADD so the immediate doesn't need to be materialized
3036         // in a register.
3037         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3038           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3039                                              SRLI->getZExtValue());
3040           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3041             ADDC |= Mask;
3042             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3043               SDValue NewAdd =
3044                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3045                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
3046               CombineTo(N0.getNode(), NewAdd);
3047               return SDValue(N, 0); // Return N so it doesn't get rechecked!
3048             }
3049           }
3050         }
3051       }
3052     }
3053   }
3055   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3056   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3057     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3058                                        N0.getOperand(1), false);
3059     if (BSwap.getNode())
3060       return BSwap;
3061   }
3063   return SDValue();
3066 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3067 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3068                                         bool DemandHighBits) {
3069   if (!LegalOperations)
3070     return SDValue();
3072   EVT VT = N->getValueType(0);
3073   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3074     return SDValue();
3075   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3076     return SDValue();
3078   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3079   bool LookPassAnd0 = false;
3080   bool LookPassAnd1 = false;
3081   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3082       std::swap(N0, N1);
3083   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3084       std::swap(N0, N1);
3085   if (N0.getOpcode() == ISD::AND) {
3086     if (!N0.getNode()->hasOneUse())
3087       return SDValue();
3088     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3089     if (!N01C || N01C->getZExtValue() != 0xFF00)
3090       return SDValue();
3091     N0 = N0.getOperand(0);
3092     LookPassAnd0 = true;
3093   }
3095   if (N1.getOpcode() == ISD::AND) {
3096     if (!N1.getNode()->hasOneUse())
3097       return SDValue();
3098     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3099     if (!N11C || N11C->getZExtValue() != 0xFF)
3100       return SDValue();
3101     N1 = N1.getOperand(0);
3102     LookPassAnd1 = true;
3103   }
3105   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3106     std::swap(N0, N1);
3107   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3108     return SDValue();
3109   if (!N0.getNode()->hasOneUse() ||
3110       !N1.getNode()->hasOneUse())
3111     return SDValue();
3113   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3114   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3115   if (!N01C || !N11C)
3116     return SDValue();
3117   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3118     return SDValue();
3120   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3121   SDValue N00 = N0->getOperand(0);
3122   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3123     if (!N00.getNode()->hasOneUse())
3124       return SDValue();
3125     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3126     if (!N001C || N001C->getZExtValue() != 0xFF)
3127       return SDValue();
3128     N00 = N00.getOperand(0);
3129     LookPassAnd0 = true;
3130   }
3132   SDValue N10 = N1->getOperand(0);
3133   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3134     if (!N10.getNode()->hasOneUse())
3135       return SDValue();
3136     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3137     if (!N101C || N101C->getZExtValue() != 0xFF00)
3138       return SDValue();
3139     N10 = N10.getOperand(0);
3140     LookPassAnd1 = true;
3141   }
3143   if (N00 != N10)
3144     return SDValue();
3146   // Make sure everything beyond the low halfword gets set to zero since the SRL
3147   // 16 will clear the top bits.
3148   unsigned OpSizeInBits = VT.getSizeInBits();
3149   if (DemandHighBits && OpSizeInBits > 16) {
3150     // If the left-shift isn't masked out then the only way this is a bswap is
3151     // if all bits beyond the low 8 are 0. In that case the entire pattern
3152     // reduces to a left shift anyway: leave it for other parts of the combiner.
3153     if (!LookPassAnd0)
3154       return SDValue();
3156     // However, if the right shift isn't masked out then it might be because
3157     // it's not needed. See if we can spot that too.
3158     if (!LookPassAnd1 &&
3159         !DAG.MaskedValueIsZero(
3160             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3161       return SDValue();
3162   }
3164   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3165   if (OpSizeInBits > 16)
3166     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3167                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3168   return Res;
3171 /// Return true if the specified node is an element that makes up a 32-bit
3172 /// packed halfword byteswap.
3173 /// ((x & 0x000000ff) << 8) |
3174 /// ((x & 0x0000ff00) >> 8) |
3175 /// ((x & 0x00ff0000) << 8) |
3176 /// ((x & 0xff000000) >> 8)
3177 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3178   if (!N.getNode()->hasOneUse())
3179     return false;
3181   unsigned Opc = N.getOpcode();
3182   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3183     return false;
3185   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3186   if (!N1C)
3187     return false;
3189   unsigned Num;
3190   switch (N1C->getZExtValue()) {
3191   default:
3192     return false;
3193   case 0xFF:       Num = 0; break;
3194   case 0xFF00:     Num = 1; break;
3195   case 0xFF0000:   Num = 2; break;
3196   case 0xFF000000: Num = 3; break;
3197   }
3199   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3200   SDValue N0 = N.getOperand(0);
3201   if (Opc == ISD::AND) {
3202     if (Num == 0 || Num == 2) {
3203       // (x >> 8) & 0xff
3204       // (x >> 8) & 0xff0000
3205       if (N0.getOpcode() != ISD::SRL)
3206         return false;
3207       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3208       if (!C || C->getZExtValue() != 8)
3209         return false;
3210     } else {
3211       // (x << 8) & 0xff00
3212       // (x << 8) & 0xff000000
3213       if (N0.getOpcode() != ISD::SHL)
3214         return false;
3215       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3216       if (!C || C->getZExtValue() != 8)
3217         return false;
3218     }
3219   } else if (Opc == ISD::SHL) {
3220     // (x & 0xff) << 8
3221     // (x & 0xff0000) << 8
3222     if (Num != 0 && Num != 2)
3223       return false;
3224     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3225     if (!C || C->getZExtValue() != 8)
3226       return false;
3227   } else { // Opc == ISD::SRL
3228     // (x & 0xff00) >> 8
3229     // (x & 0xff000000) >> 8
3230     if (Num != 1 && Num != 3)
3231       return false;
3232     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3233     if (!C || C->getZExtValue() != 8)
3234       return false;
3235   }
3237   if (Parts[Num])
3238     return false;
3240   Parts[Num] = N0.getOperand(0).getNode();
3241   return true;
3244 /// Match a 32-bit packed halfword bswap. That is
3245 /// ((x & 0x000000ff) << 8) |
3246 /// ((x & 0x0000ff00) >> 8) |
3247 /// ((x & 0x00ff0000) << 8) |
3248 /// ((x & 0xff000000) >> 8)
3249 /// => (rotl (bswap x), 16)
3250 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3251   if (!LegalOperations)
3252     return SDValue();
3254   EVT VT = N->getValueType(0);
3255   if (VT != MVT::i32)
3256     return SDValue();
3257   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3258     return SDValue();
3260   // Look for either
3261   // (or (or (and), (and)), (or (and), (and)))
3262   // (or (or (or (and), (and)), (and)), (and))
3263   if (N0.getOpcode() != ISD::OR)
3264     return SDValue();
3265   SDValue N00 = N0.getOperand(0);
3266   SDValue N01 = N0.getOperand(1);
3267   SDNode *Parts[4] = {};
3269   if (N1.getOpcode() == ISD::OR &&
3270       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3271     // (or (or (and), (and)), (or (and), (and)))
3272     SDValue N000 = N00.getOperand(0);
3273     if (!isBSwapHWordElement(N000, Parts))
3274       return SDValue();
3276     SDValue N001 = N00.getOperand(1);
3277     if (!isBSwapHWordElement(N001, Parts))
3278       return SDValue();
3279     SDValue N010 = N01.getOperand(0);
3280     if (!isBSwapHWordElement(N010, Parts))
3281       return SDValue();
3282     SDValue N011 = N01.getOperand(1);
3283     if (!isBSwapHWordElement(N011, Parts))
3284       return SDValue();
3285   } else {
3286     // (or (or (or (and), (and)), (and)), (and))
3287     if (!isBSwapHWordElement(N1, Parts))
3288       return SDValue();
3289     if (!isBSwapHWordElement(N01, Parts))
3290       return SDValue();
3291     if (N00.getOpcode() != ISD::OR)
3292       return SDValue();
3293     SDValue N000 = N00.getOperand(0);
3294     if (!isBSwapHWordElement(N000, Parts))
3295       return SDValue();
3296     SDValue N001 = N00.getOperand(1);
3297     if (!isBSwapHWordElement(N001, Parts))
3298       return SDValue();
3299   }
3301   // Make sure the parts are all coming from the same node.
3302   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3303     return SDValue();
3305   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3306                               SDValue(Parts[0],0));
3308   // Result of the bswap should be rotated by 16. If it's not legal, then
3309   // do  (x << 16) | (x >> 16).
3310   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3311   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3312     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3313   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3314     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3315   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3316                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3317                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3320 SDValue DAGCombiner::visitOR(SDNode *N) {
3321   SDValue N0 = N->getOperand(0);
3322   SDValue N1 = N->getOperand(1);
3323   SDValue LL, LR, RL, RR, CC0, CC1;
3324   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3325   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3326   EVT VT = N1.getValueType();
3328   // fold vector ops
3329   if (VT.isVector()) {
3330     SDValue FoldedVOp = SimplifyVBinOp(N);
3331     if (FoldedVOp.getNode()) return FoldedVOp;
3333     // fold (or x, 0) -> x, vector edition
3334     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3335       return N1;
3336     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3337       return N0;
3339     // fold (or x, -1) -> -1, vector edition
3340     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3341       // do not return N0, because undef node may exist in N0
3342       return DAG.getConstant(
3343           APInt::getAllOnesValue(
3344               N0.getValueType().getScalarType().getSizeInBits()),
3345           N0.getValueType());
3346     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3347       // do not return N1, because undef node may exist in N1
3348       return DAG.getConstant(
3349           APInt::getAllOnesValue(
3350               N1.getValueType().getScalarType().getSizeInBits()),
3351           N1.getValueType());
3353     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3354     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3355     // Do this only if the resulting shuffle is legal.
3356     if (isa<ShuffleVectorSDNode>(N0) &&
3357         isa<ShuffleVectorSDNode>(N1) &&
3358         // Avoid folding a node with illegal type.
3359         TLI.isTypeLegal(VT) &&
3360         N0->getOperand(1) == N1->getOperand(1) &&
3361         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3362       bool CanFold = true;
3363       unsigned NumElts = VT.getVectorNumElements();
3364       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3365       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3366       // We construct two shuffle masks:
3367       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3368       // and N1 as the second operand.
3369       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3370       // and N0 as the second operand.
3371       // We do this because OR is commutable and therefore there might be
3372       // two ways to fold this node into a shuffle.
3373       SmallVector<int,4> Mask1;
3374       SmallVector<int,4> Mask2;
3376       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3377         int M0 = SV0->getMaskElt(i);
3378         int M1 = SV1->getMaskElt(i);
3380         // Both shuffle indexes are undef. Propagate Undef.
3381         if (M0 < 0 && M1 < 0) {
3382           Mask1.push_back(M0);
3383           Mask2.push_back(M0);
3384           continue;
3385         }
3387         if (M0 < 0 || M1 < 0 ||
3388             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3389             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3390           CanFold = false;
3391           break;
3392         }
3394         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3395         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3396       }
3398       if (CanFold) {
3399         // Fold this sequence only if the resulting shuffle is 'legal'.
3400         if (TLI.isShuffleMaskLegal(Mask1, VT))
3401           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3402                                       N1->getOperand(0), &Mask1[0]);
3403         if (TLI.isShuffleMaskLegal(Mask2, VT))
3404           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3405                                       N0->getOperand(0), &Mask2[0]);
3406       }
3407     }
3408   }
3410   // fold (or x, undef) -> -1
3411   if (!LegalOperations &&
3412       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3413     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3414     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3415   }
3416   // fold (or c1, c2) -> c1|c2
3417   if (N0C && N1C)
3418     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3419   // canonicalize constant to RHS
3420   if (N0C && !N1C)
3421     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3422   // fold (or x, 0) -> x
3423   if (N1C && N1C->isNullValue())
3424     return N0;
3425   // fold (or x, -1) -> -1
3426   if (N1C && N1C->isAllOnesValue())
3427     return N1;
3428   // fold (or x, c) -> c iff (x & ~c) == 0
3429   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3430     return N1;
3432   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3433   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3434   if (BSwap.getNode())
3435     return BSwap;
3436   BSwap = MatchBSwapHWordLow(N, N0, N1);
3437   if (BSwap.getNode())
3438     return BSwap;
3440   // reassociate or
3441   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3442   if (ROR.getNode())
3443     return ROR;
3444   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3445   // iff (c1 & c2) == 0.
3446   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3447              isa<ConstantSDNode>(N0.getOperand(1))) {
3448     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3449     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3450       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1))
3451         return DAG.getNode(
3452             ISD::AND, SDLoc(N), VT,
3453             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3454       return SDValue();
3455     }
3456   }
3457   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3458   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3459     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3460     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3462     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3463         LL.getValueType().isInteger()) {
3464       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3465       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3466       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3467           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3468         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3469                                      LR.getValueType(), LL, RL);
3470         AddToWorklist(ORNode.getNode());
3471         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3472       }
3473       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3474       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3475       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3476           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3477         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3478                                       LR.getValueType(), LL, RL);
3479         AddToWorklist(ANDNode.getNode());
3480         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3481       }
3482     }
3483     // canonicalize equivalent to ll == rl
3484     if (LL == RR && LR == RL) {
3485       Op1 = ISD::getSetCCSwappedOperands(Op1);
3486       std::swap(RL, RR);
3487     }
3488     if (LL == RL && LR == RR) {
3489       bool isInteger = LL.getValueType().isInteger();
3490       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3491       if (Result != ISD::SETCC_INVALID &&
3492           (!LegalOperations ||
3493            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3494             TLI.isOperationLegal(ISD::SETCC,
3495               getSetCCResultType(N0.getValueType())))))
3496         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3497                             LL, LR, Result);
3498     }
3499   }
3501   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3502   if (N0.getOpcode() == N1.getOpcode()) {
3503     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3504     if (Tmp.getNode()) return Tmp;
3505   }
3507   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3508   if (N0.getOpcode() == ISD::AND &&
3509       N1.getOpcode() == ISD::AND &&
3510       N0.getOperand(1).getOpcode() == ISD::Constant &&
3511       N1.getOperand(1).getOpcode() == ISD::Constant &&
3512       // Don't increase # computations.
3513       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3514     // We can only do this xform if we know that bits from X that are set in C2
3515     // but not in C1 are already zero.  Likewise for Y.
3516     const APInt &LHSMask =
3517       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3518     const APInt &RHSMask =
3519       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3521     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3522         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3523       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3524                               N0.getOperand(0), N1.getOperand(0));
3525       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3526                          DAG.getConstant(LHSMask | RHSMask, VT));
3527     }
3528   }
3530   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3531   if (N0.getOpcode() == ISD::AND &&
3532       N1.getOpcode() == ISD::AND &&
3533       N0.getOperand(0) == N1.getOperand(0) &&
3534       // Don't increase # computations.
3535       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3536     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3537                             N0.getOperand(1), N1.getOperand(1));
3538     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0), X);
3539   }
3541   // See if this is some rotate idiom.
3542   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3543     return SDValue(Rot, 0);
3545   // Simplify the operands using demanded-bits information.
3546   if (!VT.isVector() &&
3547       SimplifyDemandedBits(SDValue(N, 0)))
3548     return SDValue(N, 0);
3550   return SDValue();
3553 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3554 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3555   if (Op.getOpcode() == ISD::AND) {
3556     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3557       Mask = Op.getOperand(1);
3558       Op = Op.getOperand(0);
3559     } else {
3560       return false;
3561     }
3562   }
3564   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3565     Shift = Op;
3566     return true;
3567   }
3569   return false;
3572 // Return true if we can prove that, whenever Neg and Pos are both in the
3573 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3574 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3575 //
3576 //     (or (shift1 X, Neg), (shift2 X, Pos))
3577 //
3578 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3579 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3580 // to consider shift amounts with defined behavior.
3581 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3582   // If OpSize is a power of 2 then:
3583   //
3584   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3585   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3586   //
3587   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3588   // for the stronger condition:
3589   //
3590   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3591   //
3592   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3593   // we can just replace Neg with Neg' for the rest of the function.
3594   //
3595   // In other cases we check for the even stronger condition:
3596   //
3597   //     Neg == OpSize - Pos                                    [B]
3598   //
3599   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3600   // behavior if Pos == 0 (and consequently Neg == OpSize).
3601   //
3602   // We could actually use [A] whenever OpSize is a power of 2, but the
3603   // only extra cases that it would match are those uninteresting ones
3604   // where Neg and Pos are never in range at the same time.  E.g. for
3605   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3606   // as well as (sub 32, Pos), but:
3607   //
3608   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3609   //
3610   // always invokes undefined behavior for 32-bit X.
3611   //
3612   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3613   unsigned MaskLoBits = 0;
3614   if (Neg.getOpcode() == ISD::AND &&
3615       isPowerOf2_64(OpSize) &&
3616       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3617       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3618     Neg = Neg.getOperand(0);
3619     MaskLoBits = Log2_64(OpSize);
3620   }
3622   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3623   if (Neg.getOpcode() != ISD::SUB)
3624     return 0;
3625   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3626   if (!NegC)
3627     return 0;
3628   SDValue NegOp1 = Neg.getOperand(1);
3630   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3631   // Pos'.  The truncation is redundant for the purpose of the equality.
3632   if (MaskLoBits &&
3633       Pos.getOpcode() == ISD::AND &&
3634       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3635       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3636     Pos = Pos.getOperand(0);
3638   // The condition we need is now:
3639   //
3640   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3641   //
3642   // If NegOp1 == Pos then we need:
3643   //
3644   //              OpSize & Mask == NegC & Mask
3645   //
3646   // (because "x & Mask" is a truncation and distributes through subtraction).
3647   APInt Width;
3648   if (Pos == NegOp1)
3649     Width = NegC->getAPIntValue();
3650   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3651   // Then the condition we want to prove becomes:
3652   //
3653   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3654   //
3655   // which, again because "x & Mask" is a truncation, becomes:
3656   //
3657   //                NegC & Mask == (OpSize - PosC) & Mask
3658   //              OpSize & Mask == (NegC + PosC) & Mask
3659   else if (Pos.getOpcode() == ISD::ADD &&
3660            Pos.getOperand(0) == NegOp1 &&
3661            Pos.getOperand(1).getOpcode() == ISD::Constant)
3662     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3663              NegC->getAPIntValue());
3664   else
3665     return false;
3667   // Now we just need to check that OpSize & Mask == Width & Mask.
3668   if (MaskLoBits)
3669     // Opsize & Mask is 0 since Mask is Opsize - 1.
3670     return Width.getLoBits(MaskLoBits) == 0;
3671   return Width == OpSize;
3674 // A subroutine of MatchRotate used once we have found an OR of two opposite
3675 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3676 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3677 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3678 // Neg with outer conversions stripped away.
3679 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3680                                        SDValue Neg, SDValue InnerPos,
3681                                        SDValue InnerNeg, unsigned PosOpcode,
3682                                        unsigned NegOpcode, SDLoc DL) {
3683   // fold (or (shl x, (*ext y)),
3684   //          (srl x, (*ext (sub 32, y)))) ->
3685   //   (rotl x, y) or (rotr x, (sub 32, y))
3686   //
3687   // fold (or (shl x, (*ext (sub 32, y))),
3688   //          (srl x, (*ext y))) ->
3689   //   (rotr x, y) or (rotl x, (sub 32, y))
3690   EVT VT = Shifted.getValueType();
3691   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3692     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3693     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3694                        HasPos ? Pos : Neg).getNode();
3695   }
3697   return nullptr;
3700 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3701 // idioms for rotate, and if the target supports rotation instructions, generate
3702 // a rot[lr].
3703 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3704   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3705   EVT VT = LHS.getValueType();
3706   if (!TLI.isTypeLegal(VT)) return nullptr;
3708   // The target must have at least one rotate flavor.
3709   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3710   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3711   if (!HasROTL && !HasROTR) return nullptr;
3713   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3714   SDValue LHSShift;   // The shift.
3715   SDValue LHSMask;    // AND value if any.
3716   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3717     return nullptr; // Not part of a rotate.
3719   SDValue RHSShift;   // The shift.
3720   SDValue RHSMask;    // AND value if any.
3721   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3722     return nullptr; // Not part of a rotate.
3724   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3725     return nullptr;   // Not shifting the same value.
3727   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3728     return nullptr;   // Shifts must disagree.
3730   // Canonicalize shl to left side in a shl/srl pair.
3731   if (RHSShift.getOpcode() == ISD::SHL) {
3732     std::swap(LHS, RHS);
3733     std::swap(LHSShift, RHSShift);
3734     std::swap(LHSMask , RHSMask );
3735   }
3737   unsigned OpSizeInBits = VT.getSizeInBits();
3738   SDValue LHSShiftArg = LHSShift.getOperand(0);
3739   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3740   SDValue RHSShiftArg = RHSShift.getOperand(0);
3741   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3743   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3744   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3745   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3746       RHSShiftAmt.getOpcode() == ISD::Constant) {
3747     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3748     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3749     if ((LShVal + RShVal) != OpSizeInBits)
3750       return nullptr;
3752     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3753                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3755     // If there is an AND of either shifted operand, apply it to the result.
3756     if (LHSMask.getNode() || RHSMask.getNode()) {
3757       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3759       if (LHSMask.getNode()) {
3760         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3761         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3762       }
3763       if (RHSMask.getNode()) {
3764         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3765         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3766       }
3768       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3769     }
3771     return Rot.getNode();
3772   }
3774   // If there is a mask here, and we have a variable shift, we can't be sure
3775   // that we're masking out the right stuff.
3776   if (LHSMask.getNode() || RHSMask.getNode())
3777     return nullptr;
3779   // If the shift amount is sign/zext/any-extended just peel it off.
3780   SDValue LExtOp0 = LHSShiftAmt;
3781   SDValue RExtOp0 = RHSShiftAmt;
3782   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3783        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3784        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3785        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3786       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3787        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3788        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3789        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3790     LExtOp0 = LHSShiftAmt.getOperand(0);
3791     RExtOp0 = RHSShiftAmt.getOperand(0);
3792   }
3794   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3795                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3796   if (TryL)
3797     return TryL;
3799   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3800                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3801   if (TryR)
3802     return TryR;
3804   return nullptr;
3807 SDValue DAGCombiner::visitXOR(SDNode *N) {
3808   SDValue N0 = N->getOperand(0);
3809   SDValue N1 = N->getOperand(1);
3810   SDValue LHS, RHS, CC;
3811   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3812   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3813   EVT VT = N0.getValueType();
3815   // fold vector ops
3816   if (VT.isVector()) {
3817     SDValue FoldedVOp = SimplifyVBinOp(N);
3818     if (FoldedVOp.getNode()) return FoldedVOp;
3820     // fold (xor x, 0) -> x, vector edition
3821     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3822       return N1;
3823     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3824       return N0;
3825   }
3827   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3828   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3829     return DAG.getConstant(0, VT);
3830   // fold (xor x, undef) -> undef
3831   if (N0.getOpcode() == ISD::UNDEF)
3832     return N0;
3833   if (N1.getOpcode() == ISD::UNDEF)
3834     return N1;
3835   // fold (xor c1, c2) -> c1^c2
3836   if (N0C && N1C)
3837     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3838   // canonicalize constant to RHS
3839   if (N0C && !N1C)
3840     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3841   // fold (xor x, 0) -> x
3842   if (N1C && N1C->isNullValue())
3843     return N0;
3844   // reassociate xor
3845   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3846   if (RXOR.getNode())
3847     return RXOR;
3849   // fold !(x cc y) -> (x !cc y)
3850   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3851     bool isInt = LHS.getValueType().isInteger();
3852     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3853                                                isInt);
3855     if (!LegalOperations ||
3856         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3857       switch (N0.getOpcode()) {
3858       default:
3859         llvm_unreachable("Unhandled SetCC Equivalent!");
3860       case ISD::SETCC:
3861         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3862       case ISD::SELECT_CC:
3863         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3864                                N0.getOperand(3), NotCC);
3865       }
3866     }
3867   }
3869   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3870   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3871       N0.getNode()->hasOneUse() &&
3872       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3873     SDValue V = N0.getOperand(0);
3874     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3875                     DAG.getConstant(1, V.getValueType()));
3876     AddToWorklist(V.getNode());
3877     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3878   }
3880   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3881   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3882       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3883     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3884     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3885       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3886       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3887       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3888       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3889       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3890     }
3891   }
3892   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3893   if (N1C && N1C->isAllOnesValue() &&
3894       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3895     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3896     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3897       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3898       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3899       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3900       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3901       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3902     }
3903   }
3904   // fold (xor (and x, y), y) -> (and (not x), y)
3905   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3906       N0->getOperand(1) == N1) {
3907     SDValue X = N0->getOperand(0);
3908     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3909     AddToWorklist(NotX.getNode());
3910     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3911   }
3912   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3913   if (N1C && N0.getOpcode() == ISD::XOR) {
3914     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3915     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3916     if (N00C)
3917       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3918                          DAG.getConstant(N1C->getAPIntValue() ^
3919                                          N00C->getAPIntValue(), VT));
3920     if (N01C)
3921       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3922                          DAG.getConstant(N1C->getAPIntValue() ^
3923                                          N01C->getAPIntValue(), VT));
3924   }
3925   // fold (xor x, x) -> 0
3926   if (N0 == N1)
3927     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3929   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3930   if (N0.getOpcode() == N1.getOpcode()) {
3931     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3932     if (Tmp.getNode()) return Tmp;
3933   }
3935   // Simplify the expression using non-local knowledge.
3936   if (!VT.isVector() &&
3937       SimplifyDemandedBits(SDValue(N, 0)))
3938     return SDValue(N, 0);
3940   return SDValue();
3943 /// Handle transforms common to the three shifts, when the shift amount is a
3944 /// constant.
3945 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3946   // We can't and shouldn't fold opaque constants.
3947   if (Amt->isOpaque())
3948     return SDValue();
3950   SDNode *LHS = N->getOperand(0).getNode();
3951   if (!LHS->hasOneUse()) return SDValue();
3953   // We want to pull some binops through shifts, so that we have (and (shift))
3954   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3955   // thing happens with address calculations, so it's important to canonicalize
3956   // it.
3957   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3959   switch (LHS->getOpcode()) {
3960   default: return SDValue();
3961   case ISD::OR:
3962   case ISD::XOR:
3963     HighBitSet = false; // We can only transform sra if the high bit is clear.
3964     break;
3965   case ISD::AND:
3966     HighBitSet = true;  // We can only transform sra if the high bit is set.
3967     break;
3968   case ISD::ADD:
3969     if (N->getOpcode() != ISD::SHL)
3970       return SDValue(); // only shl(add) not sr[al](add).
3971     HighBitSet = false; // We can only transform sra if the high bit is clear.
3972     break;
3973   }
3975   // We require the RHS of the binop to be a constant and not opaque as well.
3976   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3977   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3979   // FIXME: disable this unless the input to the binop is a shift by a constant.
3980   // If it is not a shift, it pessimizes some common cases like:
3981   //
3982   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3983   //    int bar(int *X, int i) { return X[i & 255]; }
3984   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3985   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3986        BinOpLHSVal->getOpcode() != ISD::SRA &&
3987        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3988       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3989     return SDValue();
3991   EVT VT = N->getValueType(0);
3993   // If this is a signed shift right, and the high bit is modified by the
3994   // logical operation, do not perform the transformation. The highBitSet
3995   // boolean indicates the value of the high bit of the constant which would
3996   // cause it to be modified for this operation.
3997   if (N->getOpcode() == ISD::SRA) {
3998     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3999     if (BinOpRHSSignSet != HighBitSet)
4000       return SDValue();
4001   }
4003   if (!TLI.isDesirableToCommuteWithShift(LHS))
4004     return SDValue();
4006   // Fold the constants, shifting the binop RHS by the shift amount.
4007   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4008                                N->getValueType(0),
4009                                LHS->getOperand(1), N->getOperand(1));
4010   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4012   // Create the new shift.
4013   SDValue NewShift = DAG.getNode(N->getOpcode(),
4014                                  SDLoc(LHS->getOperand(0)),
4015                                  VT, LHS->getOperand(0), N->getOperand(1));
4017   // Create the new binop.
4018   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4021 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4022   assert(N->getOpcode() == ISD::TRUNCATE);
4023   assert(N->getOperand(0).getOpcode() == ISD::AND);
4025   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4026   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4027     SDValue N01 = N->getOperand(0).getOperand(1);
4029     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4030       EVT TruncVT = N->getValueType(0);
4031       SDValue N00 = N->getOperand(0).getOperand(0);
4032       APInt TruncC = N01C->getAPIntValue();
4033       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4035       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4036                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4037                          DAG.getConstant(TruncC, TruncVT));
4038     }
4039   }
4041   return SDValue();
4044 SDValue DAGCombiner::visitRotate(SDNode *N) {
4045   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4046   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4047       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4048     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4049     if (NewOp1.getNode())
4050       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4051                          N->getOperand(0), NewOp1);
4052   }
4053   return SDValue();
4056 SDValue DAGCombiner::visitSHL(SDNode *N) {
4057   SDValue N0 = N->getOperand(0);
4058   SDValue N1 = N->getOperand(1);
4059   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4060   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4061   EVT VT = N0.getValueType();
4062   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4064   // fold vector ops
4065   if (VT.isVector()) {
4066     SDValue FoldedVOp = SimplifyVBinOp(N);
4067     if (FoldedVOp.getNode()) return FoldedVOp;
4069     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4070     // If setcc produces all-one true value then:
4071     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4072     if (N1CV && N1CV->isConstant()) {
4073       if (N0.getOpcode() == ISD::AND) {
4074         SDValue N00 = N0->getOperand(0);
4075         SDValue N01 = N0->getOperand(1);
4076         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4078         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4079             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4080                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4081           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV))
4082             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4083         }
4084       } else {
4085         N1C = isConstOrConstSplat(N1);
4086       }
4087     }
4088   }
4090   // fold (shl c1, c2) -> c1<<c2
4091   if (N0C && N1C)
4092     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4093   // fold (shl 0, x) -> 0
4094   if (N0C && N0C->isNullValue())
4095     return N0;
4096   // fold (shl x, c >= size(x)) -> undef
4097   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4098     return DAG.getUNDEF(VT);
4099   // fold (shl x, 0) -> x
4100   if (N1C && N1C->isNullValue())
4101     return N0;
4102   // fold (shl undef, x) -> 0
4103   if (N0.getOpcode() == ISD::UNDEF)
4104     return DAG.getConstant(0, VT);
4105   // if (shl x, c) is known to be zero, return 0
4106   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4107                             APInt::getAllOnesValue(OpSizeInBits)))
4108     return DAG.getConstant(0, VT);
4109   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4110   if (N1.getOpcode() == ISD::TRUNCATE &&
4111       N1.getOperand(0).getOpcode() == ISD::AND) {
4112     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4113     if (NewOp1.getNode())
4114       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4115   }
4117   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4118     return SDValue(N, 0);
4120   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4121   if (N1C && N0.getOpcode() == ISD::SHL) {
4122     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4123       uint64_t c1 = N0C1->getZExtValue();
4124       uint64_t c2 = N1C->getZExtValue();
4125       if (c1 + c2 >= OpSizeInBits)
4126         return DAG.getConstant(0, VT);
4127       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4128                          DAG.getConstant(c1 + c2, N1.getValueType()));
4129     }
4130   }
4132   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4133   // For this to be valid, the second form must not preserve any of the bits
4134   // that are shifted out by the inner shift in the first form.  This means
4135   // the outer shift size must be >= the number of bits added by the ext.
4136   // As a corollary, we don't care what kind of ext it is.
4137   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4138               N0.getOpcode() == ISD::ANY_EXTEND ||
4139               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4140       N0.getOperand(0).getOpcode() == ISD::SHL) {
4141     SDValue N0Op0 = N0.getOperand(0);
4142     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4143       uint64_t c1 = N0Op0C1->getZExtValue();
4144       uint64_t c2 = N1C->getZExtValue();
4145       EVT InnerShiftVT = N0Op0.getValueType();
4146       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4147       if (c2 >= OpSizeInBits - InnerShiftSize) {
4148         if (c1 + c2 >= OpSizeInBits)
4149           return DAG.getConstant(0, VT);
4150         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4151                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4152                                        N0Op0->getOperand(0)),
4153                            DAG.getConstant(c1 + c2, N1.getValueType()));
4154       }
4155     }
4156   }
4158   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4159   // Only fold this if the inner zext has no other uses to avoid increasing
4160   // the total number of instructions.
4161   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4162       N0.getOperand(0).getOpcode() == ISD::SRL) {
4163     SDValue N0Op0 = N0.getOperand(0);
4164     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4165       uint64_t c1 = N0Op0C1->getZExtValue();
4166       if (c1 < VT.getScalarSizeInBits()) {
4167         uint64_t c2 = N1C->getZExtValue();
4168         if (c1 == c2) {
4169           SDValue NewOp0 = N0.getOperand(0);
4170           EVT CountVT = NewOp0.getOperand(1).getValueType();
4171           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4172                                        NewOp0, DAG.getConstant(c2, CountVT));
4173           AddToWorklist(NewSHL.getNode());
4174           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4175         }
4176       }
4177     }
4178   }
4180   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4181   //                               (and (srl x, (sub c1, c2), MASK)
4182   // Only fold this if the inner shift has no other uses -- if it does, folding
4183   // this will increase the total number of instructions.
4184   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4185     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4186       uint64_t c1 = N0C1->getZExtValue();
4187       if (c1 < OpSizeInBits) {
4188         uint64_t c2 = N1C->getZExtValue();
4189         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4190         SDValue Shift;
4191         if (c2 > c1) {
4192           Mask = Mask.shl(c2 - c1);
4193           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4194                               DAG.getConstant(c2 - c1, N1.getValueType()));
4195         } else {
4196           Mask = Mask.lshr(c1 - c2);
4197           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4198                               DAG.getConstant(c1 - c2, N1.getValueType()));
4199         }
4200         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4201                            DAG.getConstant(Mask, VT));
4202       }
4203     }
4204   }
4205   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4206   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4207     unsigned BitSize = VT.getScalarSizeInBits();
4208     SDValue HiBitsMask =
4209       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4210                                             BitSize - N1C->getZExtValue()), VT);
4211     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4212                        HiBitsMask);
4213   }
4215   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4216   // Variant of version done on multiply, except mul by a power of 2 is turned
4217   // into a shift.
4218   APInt Val;
4219   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4220       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4221        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4222     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4223     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4224     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4225   }
4227   if (N1C) {
4228     SDValue NewSHL = visitShiftByConstant(N, N1C);
4229     if (NewSHL.getNode())
4230       return NewSHL;
4231   }
4233   return SDValue();
4236 SDValue DAGCombiner::visitSRA(SDNode *N) {
4237   SDValue N0 = N->getOperand(0);
4238   SDValue N1 = N->getOperand(1);
4239   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4240   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4241   EVT VT = N0.getValueType();
4242   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4244   // fold vector ops
4245   if (VT.isVector()) {
4246     SDValue FoldedVOp = SimplifyVBinOp(N);
4247     if (FoldedVOp.getNode()) return FoldedVOp;
4249     N1C = isConstOrConstSplat(N1);
4250   }
4252   // fold (sra c1, c2) -> (sra c1, c2)
4253   if (N0C && N1C)
4254     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4255   // fold (sra 0, x) -> 0
4256   if (N0C && N0C->isNullValue())
4257     return N0;
4258   // fold (sra -1, x) -> -1
4259   if (N0C && N0C->isAllOnesValue())
4260     return N0;
4261   // fold (sra x, (setge c, size(x))) -> undef
4262   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4263     return DAG.getUNDEF(VT);
4264   // fold (sra x, 0) -> x
4265   if (N1C && N1C->isNullValue())
4266     return N0;
4267   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4268   // sext_inreg.
4269   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4270     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4271     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4272     if (VT.isVector())
4273       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4274                                ExtVT, VT.getVectorNumElements());
4275     if ((!LegalOperations ||
4276          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4277       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4278                          N0.getOperand(0), DAG.getValueType(ExtVT));
4279   }
4281   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4282   if (N1C && N0.getOpcode() == ISD::SRA) {
4283     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4284       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4285       if (Sum >= OpSizeInBits)
4286         Sum = OpSizeInBits - 1;
4287       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4288                          DAG.getConstant(Sum, N1.getValueType()));
4289     }
4290   }
4292   // fold (sra (shl X, m), (sub result_size, n))
4293   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4294   // result_size - n != m.
4295   // If truncate is free for the target sext(shl) is likely to result in better
4296   // code.
4297   if (N0.getOpcode() == ISD::SHL && N1C) {
4298     // Get the two constanst of the shifts, CN0 = m, CN = n.
4299     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4300     if (N01C) {
4301       LLVMContext &Ctx = *DAG.getContext();
4302       // Determine what the truncate's result bitsize and type would be.
4303       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4305       if (VT.isVector())
4306         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4308       // Determine the residual right-shift amount.
4309       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4311       // If the shift is not a no-op (in which case this should be just a sign
4312       // extend already), the truncated to type is legal, sign_extend is legal
4313       // on that type, and the truncate to that type is both legal and free,
4314       // perform the transform.
4315       if ((ShiftAmt > 0) &&
4316           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4317           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4318           TLI.isTruncateFree(VT, TruncVT)) {
4320           SDValue Amt = DAG.getConstant(ShiftAmt,
4321               getShiftAmountTy(N0.getOperand(0).getValueType()));
4322           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4323                                       N0.getOperand(0), Amt);
4324           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4325                                       Shift);
4326           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4327                              N->getValueType(0), Trunc);
4328       }
4329     }
4330   }
4332   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4333   if (N1.getOpcode() == ISD::TRUNCATE &&
4334       N1.getOperand(0).getOpcode() == ISD::AND) {
4335     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4336     if (NewOp1.getNode())
4337       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4338   }
4340   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4341   //      if c1 is equal to the number of bits the trunc removes
4342   if (N0.getOpcode() == ISD::TRUNCATE &&
4343       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4344        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4345       N0.getOperand(0).hasOneUse() &&
4346       N0.getOperand(0).getOperand(1).hasOneUse() &&
4347       N1C) {
4348     SDValue N0Op0 = N0.getOperand(0);
4349     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4350       unsigned LargeShiftVal = LargeShift->getZExtValue();
4351       EVT LargeVT = N0Op0.getValueType();
4353       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4354         SDValue Amt =
4355           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4356                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4357         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4358                                   N0Op0.getOperand(0), Amt);
4359         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4360       }
4361     }
4362   }
4364   // Simplify, based on bits shifted out of the LHS.
4365   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4366     return SDValue(N, 0);
4369   // If the sign bit is known to be zero, switch this to a SRL.
4370   if (DAG.SignBitIsZero(N0))
4371     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4373   if (N1C) {
4374     SDValue NewSRA = visitShiftByConstant(N, N1C);
4375     if (NewSRA.getNode())
4376       return NewSRA;
4377   }
4379   return SDValue();
4382 SDValue DAGCombiner::visitSRL(SDNode *N) {
4383   SDValue N0 = N->getOperand(0);
4384   SDValue N1 = N->getOperand(1);
4385   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4386   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4387   EVT VT = N0.getValueType();
4388   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4390   // fold vector ops
4391   if (VT.isVector()) {
4392     SDValue FoldedVOp = SimplifyVBinOp(N);
4393     if (FoldedVOp.getNode()) return FoldedVOp;
4395     N1C = isConstOrConstSplat(N1);
4396   }
4398   // fold (srl c1, c2) -> c1 >>u c2
4399   if (N0C && N1C)
4400     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4401   // fold (srl 0, x) -> 0
4402   if (N0C && N0C->isNullValue())
4403     return N0;
4404   // fold (srl x, c >= size(x)) -> undef
4405   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4406     return DAG.getUNDEF(VT);
4407   // fold (srl x, 0) -> x
4408   if (N1C && N1C->isNullValue())
4409     return N0;
4410   // if (srl x, c) is known to be zero, return 0
4411   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4412                                    APInt::getAllOnesValue(OpSizeInBits)))
4413     return DAG.getConstant(0, VT);
4415   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4416   if (N1C && N0.getOpcode() == ISD::SRL) {
4417     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4418       uint64_t c1 = N01C->getZExtValue();
4419       uint64_t c2 = N1C->getZExtValue();
4420       if (c1 + c2 >= OpSizeInBits)
4421         return DAG.getConstant(0, VT);
4422       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4423                          DAG.getConstant(c1 + c2, N1.getValueType()));
4424     }
4425   }
4427   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4428   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4429       N0.getOperand(0).getOpcode() == ISD::SRL &&
4430       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4431     uint64_t c1 =
4432       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4433     uint64_t c2 = N1C->getZExtValue();
4434     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4435     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4436     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4437     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4438     if (c1 + OpSizeInBits == InnerShiftSize) {
4439       if (c1 + c2 >= InnerShiftSize)
4440         return DAG.getConstant(0, VT);
4441       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4442                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4443                                      N0.getOperand(0)->getOperand(0),
4444                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4445     }
4446   }
4448   // fold (srl (shl x, c), c) -> (and x, cst2)
4449   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4450     unsigned BitSize = N0.getScalarValueSizeInBits();
4451     if (BitSize <= 64) {
4452       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4453       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4454                          DAG.getConstant(~0ULL >> ShAmt, VT));
4455     }
4456   }
4458   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4459   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4460     // Shifting in all undef bits?
4461     EVT SmallVT = N0.getOperand(0).getValueType();
4462     unsigned BitSize = SmallVT.getScalarSizeInBits();
4463     if (N1C->getZExtValue() >= BitSize)
4464       return DAG.getUNDEF(VT);
4466     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4467       uint64_t ShiftAmt = N1C->getZExtValue();
4468       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4469                                        N0.getOperand(0),
4470                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4471       AddToWorklist(SmallShift.getNode());
4472       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4473       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4474                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4475                          DAG.getConstant(Mask, VT));
4476     }
4477   }
4479   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4480   // bit, which is unmodified by sra.
4481   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4482     if (N0.getOpcode() == ISD::SRA)
4483       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4484   }
4486   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4487   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4488       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4489     APInt KnownZero, KnownOne;
4490     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4492     // If any of the input bits are KnownOne, then the input couldn't be all
4493     // zeros, thus the result of the srl will always be zero.
4494     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4496     // If all of the bits input the to ctlz node are known to be zero, then
4497     // the result of the ctlz is "32" and the result of the shift is one.
4498     APInt UnknownBits = ~KnownZero;
4499     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4501     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4502     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4503       // Okay, we know that only that the single bit specified by UnknownBits
4504       // could be set on input to the CTLZ node. If this bit is set, the SRL
4505       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4506       // to an SRL/XOR pair, which is likely to simplify more.
4507       unsigned ShAmt = UnknownBits.countTrailingZeros();
4508       SDValue Op = N0.getOperand(0);
4510       if (ShAmt) {
4511         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4512                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4513         AddToWorklist(Op.getNode());
4514       }
4516       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4517                          Op, DAG.getConstant(1, VT));
4518     }
4519   }
4521   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4522   if (N1.getOpcode() == ISD::TRUNCATE &&
4523       N1.getOperand(0).getOpcode() == ISD::AND) {
4524     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4525     if (NewOp1.getNode())
4526       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4527   }
4529   // fold operands of srl based on knowledge that the low bits are not
4530   // demanded.
4531   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4532     return SDValue(N, 0);
4534   if (N1C) {
4535     SDValue NewSRL = visitShiftByConstant(N, N1C);
4536     if (NewSRL.getNode())
4537       return NewSRL;
4538   }
4540   // Attempt to convert a srl of a load into a narrower zero-extending load.
4541   SDValue NarrowLoad = ReduceLoadWidth(N);
4542   if (NarrowLoad.getNode())
4543     return NarrowLoad;
4545   // Here is a common situation. We want to optimize:
4546   //
4547   //   %a = ...
4548   //   %b = and i32 %a, 2
4549   //   %c = srl i32 %b, 1
4550   //   brcond i32 %c ...
4551   //
4552   // into
4553   //
4554   //   %a = ...
4555   //   %b = and %a, 2
4556   //   %c = setcc eq %b, 0
4557   //   brcond %c ...
4558   //
4559   // However when after the source operand of SRL is optimized into AND, the SRL
4560   // itself may not be optimized further. Look for it and add the BRCOND into
4561   // the worklist.
4562   if (N->hasOneUse()) {
4563     SDNode *Use = *N->use_begin();
4564     if (Use->getOpcode() == ISD::BRCOND)
4565       AddToWorklist(Use);
4566     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4567       // Also look pass the truncate.
4568       Use = *Use->use_begin();
4569       if (Use->getOpcode() == ISD::BRCOND)
4570         AddToWorklist(Use);
4571     }
4572   }
4574   return SDValue();
4577 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4578   SDValue N0 = N->getOperand(0);
4579   EVT VT = N->getValueType(0);
4581   // fold (ctlz c1) -> c2
4582   if (isa<ConstantSDNode>(N0))
4583     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4584   return SDValue();
4587 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4588   SDValue N0 = N->getOperand(0);
4589   EVT VT = N->getValueType(0);
4591   // fold (ctlz_zero_undef c1) -> c2
4592   if (isa<ConstantSDNode>(N0))
4593     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4594   return SDValue();
4597 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4598   SDValue N0 = N->getOperand(0);
4599   EVT VT = N->getValueType(0);
4601   // fold (cttz c1) -> c2
4602   if (isa<ConstantSDNode>(N0))
4603     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4604   return SDValue();
4607 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4608   SDValue N0 = N->getOperand(0);
4609   EVT VT = N->getValueType(0);
4611   // fold (cttz_zero_undef c1) -> c2
4612   if (isa<ConstantSDNode>(N0))
4613     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4614   return SDValue();
4617 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4618   SDValue N0 = N->getOperand(0);
4619   EVT VT = N->getValueType(0);
4621   // fold (ctpop c1) -> c2
4622   if (isa<ConstantSDNode>(N0))
4623     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4624   return SDValue();
4628 /// \brief Generate Min/Max node
4629 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4630                                    SDValue True, SDValue False,
4631                                    ISD::CondCode CC, const TargetLowering &TLI,
4632                                    SelectionDAG &DAG) {
4633   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4634     return SDValue();
4636   switch (CC) {
4637   case ISD::SETOLT:
4638   case ISD::SETOLE:
4639   case ISD::SETLT:
4640   case ISD::SETLE:
4641   case ISD::SETULT:
4642   case ISD::SETULE: {
4643     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4644     if (TLI.isOperationLegal(Opcode, VT))
4645       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4646     return SDValue();
4647   }
4648   case ISD::SETOGT:
4649   case ISD::SETOGE:
4650   case ISD::SETGT:
4651   case ISD::SETGE:
4652   case ISD::SETUGT:
4653   case ISD::SETUGE: {
4654     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4655     if (TLI.isOperationLegal(Opcode, VT))
4656       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4657     return SDValue();
4658   }
4659   default:
4660     return SDValue();
4661   }
4664 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4665   SDValue N0 = N->getOperand(0);
4666   SDValue N1 = N->getOperand(1);
4667   SDValue N2 = N->getOperand(2);
4668   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4669   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4670   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4671   EVT VT = N->getValueType(0);
4672   EVT VT0 = N0.getValueType();
4674   // fold (select C, X, X) -> X
4675   if (N1 == N2)
4676     return N1;
4677   // fold (select true, X, Y) -> X
4678   if (N0C && !N0C->isNullValue())
4679     return N1;
4680   // fold (select false, X, Y) -> Y
4681   if (N0C && N0C->isNullValue())
4682     return N2;
4683   // fold (select C, 1, X) -> (or C, X)
4684   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4685     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4686   // fold (select C, 0, 1) -> (xor C, 1)
4687   // We can't do this reliably if integer based booleans have different contents
4688   // to floating point based booleans. This is because we can't tell whether we
4689   // have an integer-based boolean or a floating-point-based boolean unless we
4690   // can find the SETCC that produced it and inspect its operands. This is
4691   // fairly easy if C is the SETCC node, but it can potentially be
4692   // undiscoverable (or not reasonably discoverable). For example, it could be
4693   // in another basic block or it could require searching a complicated
4694   // expression.
4695   if (VT.isInteger() &&
4696       (VT0 == MVT::i1 || (VT0.isInteger() &&
4697                           TLI.getBooleanContents(false, false) ==
4698                               TLI.getBooleanContents(false, true) &&
4699                           TLI.getBooleanContents(false, false) ==
4700                               TargetLowering::ZeroOrOneBooleanContent)) &&
4701       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4702     SDValue XORNode;
4703     if (VT == VT0)
4704       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4705                          N0, DAG.getConstant(1, VT0));
4706     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4707                           N0, DAG.getConstant(1, VT0));
4708     AddToWorklist(XORNode.getNode());
4709     if (VT.bitsGT(VT0))
4710       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4711     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4712   }
4713   // fold (select C, 0, X) -> (and (not C), X)
4714   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4715     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4716     AddToWorklist(NOTNode.getNode());
4717     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4718   }
4719   // fold (select C, X, 1) -> (or (not C), X)
4720   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4721     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4722     AddToWorklist(NOTNode.getNode());
4723     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4724   }
4725   // fold (select C, X, 0) -> (and C, X)
4726   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4727     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4728   // fold (select X, X, Y) -> (or X, Y)
4729   // fold (select X, 1, Y) -> (or X, Y)
4730   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4731     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4732   // fold (select X, Y, X) -> (and X, Y)
4733   // fold (select X, Y, 0) -> (and X, Y)
4734   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4735     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4737   // If we can fold this based on the true/false value, do so.
4738   if (SimplifySelectOps(N, N1, N2))
4739     return SDValue(N, 0);  // Don't revisit N.
4741   // fold selects based on a setcc into other things, such as min/max/abs
4742   if (N0.getOpcode() == ISD::SETCC) {
4743     // select x, y (fcmp lt x, y) -> fminnum x, y
4744     // select x, y (fcmp gt x, y) -> fmaxnum x, y
4745     //
4746     // This is OK if we don't care about what happens if either operand is a
4747     // NaN.
4748     //
4750     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4751     // no signed zeros as well as no nans.
4752     const TargetOptions &Options = DAG.getTarget().Options;
4753     if (Options.UnsafeFPMath &&
4754         VT.isFloatingPoint() && N0.hasOneUse() &&
4755         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4756       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4758       SDValue FMinMax =
4759           combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4760                               N1, N2, CC, TLI, DAG);
4761       if (FMinMax)
4762         return FMinMax;
4763     }
4765     if ((!LegalOperations &&
4766          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4767         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4768       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4769                          N0.getOperand(0), N0.getOperand(1),
4770                          N1, N2, N0.getOperand(2));
4771     return SimplifySelect(SDLoc(N), N0, N1, N2);
4772   }
4774   return SDValue();
4777 static
4778 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4779   SDLoc DL(N);
4780   EVT LoVT, HiVT;
4781   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4783   // Split the inputs.
4784   SDValue Lo, Hi, LL, LH, RL, RH;
4785   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4786   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4788   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4789   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4791   return std::make_pair(Lo, Hi);
4794 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4795 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4796 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4797   SDLoc dl(N);
4798   SDValue Cond = N->getOperand(0);
4799   SDValue LHS = N->getOperand(1);
4800   SDValue RHS = N->getOperand(2);
4801   EVT VT = N->getValueType(0);
4802   int NumElems = VT.getVectorNumElements();
4803   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4804          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4805          Cond.getOpcode() == ISD::BUILD_VECTOR);
4807   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4808   // binary ones here.
4809   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4810     return SDValue();
4812   // We're sure we have an even number of elements due to the
4813   // concat_vectors we have as arguments to vselect.
4814   // Skip BV elements until we find one that's not an UNDEF
4815   // After we find an UNDEF element, keep looping until we get to half the
4816   // length of the BV and see if all the non-undef nodes are the same.
4817   ConstantSDNode *BottomHalf = nullptr;
4818   for (int i = 0; i < NumElems / 2; ++i) {
4819     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4820       continue;
4822     if (BottomHalf == nullptr)
4823       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4824     else if (Cond->getOperand(i).getNode() != BottomHalf)
4825       return SDValue();
4826   }
4828   // Do the same for the second half of the BuildVector
4829   ConstantSDNode *TopHalf = nullptr;
4830   for (int i = NumElems / 2; i < NumElems; ++i) {
4831     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4832       continue;
4834     if (TopHalf == nullptr)
4835       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4836     else if (Cond->getOperand(i).getNode() != TopHalf)
4837       return SDValue();
4838   }
4840   assert(TopHalf && BottomHalf &&
4841          "One half of the selector was all UNDEFs and the other was all the "
4842          "same value. This should have been addressed before this function.");
4843   return DAG.getNode(
4844       ISD::CONCAT_VECTORS, dl, VT,
4845       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4846       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4849 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
4851   if (Level >= AfterLegalizeTypes)
4852     return SDValue();
4854   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
4855   SDValue Mask = MST->getMask();
4856   SDValue Data  = MST->getData();
4857   SDLoc DL(N);
4859   // If the MSTORE data type requires splitting and the mask is provided by a
4860   // SETCC, then split both nodes and its operands before legalization. This
4861   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4862   // and enables future optimizations (e.g. min/max pattern matching on X86).
4863   if (Mask.getOpcode() == ISD::SETCC) {
4865     // Check if any splitting is required.
4866     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
4867         TargetLowering::TypeSplitVector)
4868       return SDValue();
4870     SDValue MaskLo, MaskHi, Lo, Hi;
4871     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4873     EVT LoVT, HiVT;
4874     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
4876     SDValue Chain = MST->getChain();
4877     SDValue Ptr   = MST->getBasePtr();
4879     EVT MemoryVT = MST->getMemoryVT();
4880     unsigned Alignment = MST->getOriginalAlignment();
4882     // if Alignment is equal to the vector size,
4883     // take the half of it for the second part
4884     unsigned SecondHalfAlignment =
4885       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
4886          Alignment/2 : Alignment;
4888     EVT LoMemVT, HiMemVT;
4889     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4891     SDValue DataLo, DataHi;
4892     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
4894     MachineMemOperand *MMO = DAG.getMachineFunction().
4895       getMachineMemOperand(MST->getPointerInfo(), 
4896                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
4897                            Alignment, MST->getAAInfo(), MST->getRanges());
4899     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, MMO);
4901     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4902     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4903                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
4905     MMO = DAG.getMachineFunction().
4906       getMachineMemOperand(MST->getPointerInfo(), 
4907                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
4908                            SecondHalfAlignment, MST->getAAInfo(),
4909                            MST->getRanges());
4911     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, MMO);
4913     AddToWorklist(Lo.getNode());
4914     AddToWorklist(Hi.getNode());
4916     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
4917   }
4918   return SDValue();
4921 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
4923   if (Level >= AfterLegalizeTypes)
4924     return SDValue();
4926   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
4927   SDValue Mask = MLD->getMask();
4928   SDLoc DL(N);
4930   // If the MLOAD result requires splitting and the mask is provided by a
4931   // SETCC, then split both nodes and its operands before legalization. This
4932   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4933   // and enables future optimizations (e.g. min/max pattern matching on X86).
4935   if (Mask.getOpcode() == ISD::SETCC) {
4936     EVT VT = N->getValueType(0);
4938     // Check if any splitting is required.
4939     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4940         TargetLowering::TypeSplitVector)
4941       return SDValue();
4943     SDValue MaskLo, MaskHi, Lo, Hi;
4944     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4946     SDValue Src0 = MLD->getSrc0();
4947     SDValue Src0Lo, Src0Hi;
4948     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
4950     EVT LoVT, HiVT;
4951     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
4953     SDValue Chain = MLD->getChain();
4954     SDValue Ptr   = MLD->getBasePtr();
4955     EVT MemoryVT = MLD->getMemoryVT();
4956     unsigned Alignment = MLD->getOriginalAlignment();
4958     // if Alignment is equal to the vector size,
4959     // take the half of it for the second part
4960     unsigned SecondHalfAlignment =
4961       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
4962          Alignment/2 : Alignment;
4964     EVT LoMemVT, HiMemVT;
4965     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4967     MachineMemOperand *MMO = DAG.getMachineFunction().
4968     getMachineMemOperand(MLD->getPointerInfo(), 
4969                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
4970                          Alignment, MLD->getAAInfo(), MLD->getRanges());
4972     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, MMO);
4974     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4975     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4976                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
4978     MMO = DAG.getMachineFunction().
4979     getMachineMemOperand(MLD->getPointerInfo(), 
4980                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
4981                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
4983     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, MMO);
4985     AddToWorklist(Lo.getNode());
4986     AddToWorklist(Hi.getNode());
4988     // Build a factor node to remember that this load is independent of the
4989     // other one.
4990     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
4991                         Hi.getValue(1));
4993     // Legalized the chain result - switch anything that used the old chain to
4994     // use the new one.
4995     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
4997     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4999     SDValue RetOps[] = { LoadRes, Chain };
5000     return DAG.getMergeValues(RetOps, DL);
5001   }
5002   return SDValue();
5005 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5006   SDValue N0 = N->getOperand(0);
5007   SDValue N1 = N->getOperand(1);
5008   SDValue N2 = N->getOperand(2);
5009   SDLoc DL(N);
5011   // Canonicalize integer abs.
5012   // vselect (setg[te] X,  0),  X, -X ->
5013   // vselect (setgt    X, -1),  X, -X ->
5014   // vselect (setl[te] X,  0), -X,  X ->
5015   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5016   if (N0.getOpcode() == ISD::SETCC) {
5017     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5018     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5019     bool isAbs = false;
5020     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5022     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5023          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5024         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5025       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5026     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5027              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5028       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5030     if (isAbs) {
5031       EVT VT = LHS.getValueType();
5032       SDValue Shift = DAG.getNode(
5033           ISD::SRA, DL, VT, LHS,
5034           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
5035       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5036       AddToWorklist(Shift.getNode());
5037       AddToWorklist(Add.getNode());
5038       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5039     }
5040   }
5042   // If the VSELECT result requires splitting and the mask is provided by a
5043   // SETCC, then split both nodes and its operands before legalization. This
5044   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5045   // and enables future optimizations (e.g. min/max pattern matching on X86).
5046   if (N0.getOpcode() == ISD::SETCC) {
5047     EVT VT = N->getValueType(0);
5049     // Check if any splitting is required.
5050     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5051         TargetLowering::TypeSplitVector)
5052       return SDValue();
5054     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5055     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5056     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5057     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5059     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5060     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5062     // Add the new VSELECT nodes to the work list in case they need to be split
5063     // again.
5064     AddToWorklist(Lo.getNode());
5065     AddToWorklist(Hi.getNode());
5067     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5068   }
5070   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5071   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5072     return N1;
5073   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5074   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5075     return N2;
5077   // The ConvertSelectToConcatVector function is assuming both the above
5078   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5079   // and addressed.
5080   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5081       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5082       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5083     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5084     if (CV.getNode())
5085       return CV;
5086   }
5088   return SDValue();
5091 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5092   SDValue N0 = N->getOperand(0);
5093   SDValue N1 = N->getOperand(1);
5094   SDValue N2 = N->getOperand(2);
5095   SDValue N3 = N->getOperand(3);
5096   SDValue N4 = N->getOperand(4);
5097   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5099   // fold select_cc lhs, rhs, x, x, cc -> x
5100   if (N2 == N3)
5101     return N2;
5103   // Determine if the condition we're dealing with is constant
5104   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5105                               N0, N1, CC, SDLoc(N), false);
5106   if (SCC.getNode()) {
5107     AddToWorklist(SCC.getNode());
5109     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5110       if (!SCCC->isNullValue())
5111         return N2;    // cond always true -> true val
5112       else
5113         return N3;    // cond always false -> false val
5114     } else if (SCC->getOpcode() == ISD::UNDEF) {
5115       // When the condition is UNDEF, just return the first operand. This is
5116       // coherent the DAG creation, no setcc node is created in this case
5117       return N2;
5118     } else if (SCC.getOpcode() == ISD::SETCC) {
5119       // Fold to a simpler select_cc
5120       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5121                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5122                          SCC.getOperand(2));
5123     }
5124   }
5126   // If we can fold this based on the true/false value, do so.
5127   if (SimplifySelectOps(N, N2, N3))
5128     return SDValue(N, 0);  // Don't revisit N.
5130   // fold select_cc into other things, such as min/max/abs
5131   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5134 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5135   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5136                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5137                        SDLoc(N));
5140 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5141 // dag node into a ConstantSDNode or a build_vector of constants.
5142 // This function is called by the DAGCombiner when visiting sext/zext/aext
5143 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5144 // Vector extends are not folded if operations are legal; this is to
5145 // avoid introducing illegal build_vector dag nodes.
5146 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5147                                          SelectionDAG &DAG, bool LegalTypes,
5148                                          bool LegalOperations) {
5149   unsigned Opcode = N->getOpcode();
5150   SDValue N0 = N->getOperand(0);
5151   EVT VT = N->getValueType(0);
5153   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5154          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5156   // fold (sext c1) -> c1
5157   // fold (zext c1) -> c1
5158   // fold (aext c1) -> c1
5159   if (isa<ConstantSDNode>(N0))
5160     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5162   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5163   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5164   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5165   EVT SVT = VT.getScalarType();
5166   if (!(VT.isVector() &&
5167       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5168       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5169     return nullptr;
5171   // We can fold this node into a build_vector.
5172   unsigned VTBits = SVT.getSizeInBits();
5173   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5174   unsigned ShAmt = VTBits - EVTBits;
5175   SmallVector<SDValue, 8> Elts;
5176   unsigned NumElts = N0->getNumOperands();
5177   SDLoc DL(N);
5179   for (unsigned i=0; i != NumElts; ++i) {
5180     SDValue Op = N0->getOperand(i);
5181     if (Op->getOpcode() == ISD::UNDEF) {
5182       Elts.push_back(DAG.getUNDEF(SVT));
5183       continue;
5184     }
5186     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5187     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5188     if (Opcode == ISD::SIGN_EXTEND)
5189       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5190                                      SVT));
5191     else
5192       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5193                                      SVT));
5194   }
5196   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5199 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5200 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5201 // transformation. Returns true if extension are possible and the above
5202 // mentioned transformation is profitable.
5203 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5204                                     unsigned ExtOpc,
5205                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5206                                     const TargetLowering &TLI) {
5207   bool HasCopyToRegUses = false;
5208   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5209   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5210                             UE = N0.getNode()->use_end();
5211        UI != UE; ++UI) {
5212     SDNode *User = *UI;
5213     if (User == N)
5214       continue;
5215     if (UI.getUse().getResNo() != N0.getResNo())
5216       continue;
5217     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5218     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5219       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5220       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5221         // Sign bits will be lost after a zext.
5222         return false;
5223       bool Add = false;
5224       for (unsigned i = 0; i != 2; ++i) {
5225         SDValue UseOp = User->getOperand(i);
5226         if (UseOp == N0)
5227           continue;
5228         if (!isa<ConstantSDNode>(UseOp))
5229           return false;
5230         Add = true;
5231       }
5232       if (Add)
5233         ExtendNodes.push_back(User);
5234       continue;
5235     }
5236     // If truncates aren't free and there are users we can't
5237     // extend, it isn't worthwhile.
5238     if (!isTruncFree)
5239       return false;
5240     // Remember if this value is live-out.
5241     if (User->getOpcode() == ISD::CopyToReg)
5242       HasCopyToRegUses = true;
5243   }
5245   if (HasCopyToRegUses) {
5246     bool BothLiveOut = false;
5247     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5248          UI != UE; ++UI) {
5249       SDUse &Use = UI.getUse();
5250       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5251         BothLiveOut = true;
5252         break;
5253       }
5254     }
5255     if (BothLiveOut)
5256       // Both unextended and extended values are live out. There had better be
5257       // a good reason for the transformation.
5258       return ExtendNodes.size();
5259   }
5260   return true;
5263 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5264                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5265                                   ISD::NodeType ExtType) {
5266   // Extend SetCC uses if necessary.
5267   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5268     SDNode *SetCC = SetCCs[i];
5269     SmallVector<SDValue, 4> Ops;
5271     for (unsigned j = 0; j != 2; ++j) {
5272       SDValue SOp = SetCC->getOperand(j);
5273       if (SOp == Trunc)
5274         Ops.push_back(ExtLoad);
5275       else
5276         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5277     }
5279     Ops.push_back(SetCC->getOperand(2));
5280     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5281   }
5284 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5285   SDValue N0 = N->getOperand(0);
5286   EVT VT = N->getValueType(0);
5288   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5289                                               LegalOperations))
5290     return SDValue(Res, 0);
5292   // fold (sext (sext x)) -> (sext x)
5293   // fold (sext (aext x)) -> (sext x)
5294   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5295     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5296                        N0.getOperand(0));
5298   if (N0.getOpcode() == ISD::TRUNCATE) {
5299     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5300     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5301     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5302     if (NarrowLoad.getNode()) {
5303       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5304       if (NarrowLoad.getNode() != N0.getNode()) {
5305         CombineTo(N0.getNode(), NarrowLoad);
5306         // CombineTo deleted the truncate, if needed, but not what's under it.
5307         AddToWorklist(oye);
5308       }
5309       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5310     }
5312     // See if the value being truncated is already sign extended.  If so, just
5313     // eliminate the trunc/sext pair.
5314     SDValue Op = N0.getOperand(0);
5315     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5316     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5317     unsigned DestBits = VT.getScalarType().getSizeInBits();
5318     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5320     if (OpBits == DestBits) {
5321       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5322       // bits, it is already ready.
5323       if (NumSignBits > DestBits-MidBits)
5324         return Op;
5325     } else if (OpBits < DestBits) {
5326       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5327       // bits, just sext from i32.
5328       if (NumSignBits > OpBits-MidBits)
5329         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5330     } else {
5331       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5332       // bits, just truncate to i32.
5333       if (NumSignBits > OpBits-MidBits)
5334         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5335     }
5337     // fold (sext (truncate x)) -> (sextinreg x).
5338     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5339                                                  N0.getValueType())) {
5340       if (OpBits < DestBits)
5341         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5342       else if (OpBits > DestBits)
5343         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5344       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5345                          DAG.getValueType(N0.getValueType()));
5346     }
5347   }
5349   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5350   // None of the supported targets knows how to perform load and sign extend
5351   // on vectors in one instruction.  We only perform this transformation on
5352   // scalars.
5353   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5354       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5355       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5356        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5357     bool DoXform = true;
5358     SmallVector<SDNode*, 4> SetCCs;
5359     if (!N0.hasOneUse())
5360       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5361     if (DoXform) {
5362       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5363       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5364                                        LN0->getChain(),
5365                                        LN0->getBasePtr(), N0.getValueType(),
5366                                        LN0->getMemOperand());
5367       CombineTo(N, ExtLoad);
5368       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5369                                   N0.getValueType(), ExtLoad);
5370       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5371       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5372                       ISD::SIGN_EXTEND);
5373       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5374     }
5375   }
5377   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5378   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5379   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5380       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5381     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5382     EVT MemVT = LN0->getMemoryVT();
5383     if ((!LegalOperations && !LN0->isVolatile()) ||
5384         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5385       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5386                                        LN0->getChain(),
5387                                        LN0->getBasePtr(), MemVT,
5388                                        LN0->getMemOperand());
5389       CombineTo(N, ExtLoad);
5390       CombineTo(N0.getNode(),
5391                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5392                             N0.getValueType(), ExtLoad),
5393                 ExtLoad.getValue(1));
5394       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5395     }
5396   }
5398   // fold (sext (and/or/xor (load x), cst)) ->
5399   //      (and/or/xor (sextload x), (sext cst))
5400   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5401        N0.getOpcode() == ISD::XOR) &&
5402       isa<LoadSDNode>(N0.getOperand(0)) &&
5403       N0.getOperand(1).getOpcode() == ISD::Constant &&
5404       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5405       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5406     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5407     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5408       bool DoXform = true;
5409       SmallVector<SDNode*, 4> SetCCs;
5410       if (!N0.hasOneUse())
5411         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5412                                           SetCCs, TLI);
5413       if (DoXform) {
5414         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5415                                          LN0->getChain(), LN0->getBasePtr(),
5416                                          LN0->getMemoryVT(),
5417                                          LN0->getMemOperand());
5418         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5419         Mask = Mask.sext(VT.getSizeInBits());
5420         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5421                                   ExtLoad, DAG.getConstant(Mask, VT));
5422         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5423                                     SDLoc(N0.getOperand(0)),
5424                                     N0.getOperand(0).getValueType(), ExtLoad);
5425         CombineTo(N, And);
5426         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5427         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5428                         ISD::SIGN_EXTEND);
5429         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5430       }
5431     }
5432   }
5434   if (N0.getOpcode() == ISD::SETCC) {
5435     EVT N0VT = N0.getOperand(0).getValueType();
5436     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5437     // Only do this before legalize for now.
5438     if (VT.isVector() && !LegalOperations &&
5439         TLI.getBooleanContents(N0VT) ==
5440             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5441       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5442       // of the same size as the compared operands. Only optimize sext(setcc())
5443       // if this is the case.
5444       EVT SVT = getSetCCResultType(N0VT);
5446       // We know that the # elements of the results is the same as the
5447       // # elements of the compare (and the # elements of the compare result
5448       // for that matter).  Check to see that they are the same size.  If so,
5449       // we know that the element size of the sext'd result matches the
5450       // element size of the compare operands.
5451       if (VT.getSizeInBits() == SVT.getSizeInBits())
5452         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5453                              N0.getOperand(1),
5454                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5456       // If the desired elements are smaller or larger than the source
5457       // elements we can use a matching integer vector type and then
5458       // truncate/sign extend
5459       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5460       if (SVT == MatchingVectorType) {
5461         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5462                                N0.getOperand(0), N0.getOperand(1),
5463                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5464         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5465       }
5466     }
5468     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5469     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5470     SDValue NegOne =
5471       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5472     SDValue SCC =
5473       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5474                        NegOne, DAG.getConstant(0, VT),
5475                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5476     if (SCC.getNode()) return SCC;
5478     if (!VT.isVector()) {
5479       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5480       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5481         SDLoc DL(N);
5482         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5483         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5484                                      N0.getOperand(0), N0.getOperand(1), CC);
5485         return DAG.getSelect(DL, VT, SetCC,
5486                              NegOne, DAG.getConstant(0, VT));
5487       }
5488     }
5489   }
5491   // fold (sext x) -> (zext x) if the sign bit is known zero.
5492   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5493       DAG.SignBitIsZero(N0))
5494     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5496   return SDValue();
5499 // isTruncateOf - If N is a truncate of some other value, return true, record
5500 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5501 // This function computes KnownZero to avoid a duplicated call to
5502 // computeKnownBits in the caller.
5503 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5504                          APInt &KnownZero) {
5505   APInt KnownOne;
5506   if (N->getOpcode() == ISD::TRUNCATE) {
5507     Op = N->getOperand(0);
5508     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5509     return true;
5510   }
5512   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5513       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5514     return false;
5516   SDValue Op0 = N->getOperand(0);
5517   SDValue Op1 = N->getOperand(1);
5518   assert(Op0.getValueType() == Op1.getValueType());
5520   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5521   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5522   if (COp0 && COp0->isNullValue())
5523     Op = Op1;
5524   else if (COp1 && COp1->isNullValue())
5525     Op = Op0;
5526   else
5527     return false;
5529   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5531   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5532     return false;
5534   return true;
5537 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5538   SDValue N0 = N->getOperand(0);
5539   EVT VT = N->getValueType(0);
5541   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5542                                               LegalOperations))
5543     return SDValue(Res, 0);
5545   // fold (zext (zext x)) -> (zext x)
5546   // fold (zext (aext x)) -> (zext x)
5547   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5548     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5549                        N0.getOperand(0));
5551   // fold (zext (truncate x)) -> (zext x) or
5552   //      (zext (truncate x)) -> (truncate x)
5553   // This is valid when the truncated bits of x are already zero.
5554   // FIXME: We should extend this to work for vectors too.
5555   SDValue Op;
5556   APInt KnownZero;
5557   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5558     APInt TruncatedBits =
5559       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5560       APInt(Op.getValueSizeInBits(), 0) :
5561       APInt::getBitsSet(Op.getValueSizeInBits(),
5562                         N0.getValueSizeInBits(),
5563                         std::min(Op.getValueSizeInBits(),
5564                                  VT.getSizeInBits()));
5565     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5566       if (VT.bitsGT(Op.getValueType()))
5567         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5568       if (VT.bitsLT(Op.getValueType()))
5569         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5571       return Op;
5572     }
5573   }
5575   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5576   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5577   if (N0.getOpcode() == ISD::TRUNCATE) {
5578     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5579     if (NarrowLoad.getNode()) {
5580       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5581       if (NarrowLoad.getNode() != N0.getNode()) {
5582         CombineTo(N0.getNode(), NarrowLoad);
5583         // CombineTo deleted the truncate, if needed, but not what's under it.
5584         AddToWorklist(oye);
5585       }
5586       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5587     }
5588   }
5590   // fold (zext (truncate x)) -> (and x, mask)
5591   if (N0.getOpcode() == ISD::TRUNCATE &&
5592       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5594     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5595     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5596     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5597     if (NarrowLoad.getNode()) {
5598       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5599       if (NarrowLoad.getNode() != N0.getNode()) {
5600         CombineTo(N0.getNode(), NarrowLoad);
5601         // CombineTo deleted the truncate, if needed, but not what's under it.
5602         AddToWorklist(oye);
5603       }
5604       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5605     }
5607     SDValue Op = N0.getOperand(0);
5608     if (Op.getValueType().bitsLT(VT)) {
5609       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5610       AddToWorklist(Op.getNode());
5611     } else if (Op.getValueType().bitsGT(VT)) {
5612       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5613       AddToWorklist(Op.getNode());
5614     }
5615     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5616                                   N0.getValueType().getScalarType());
5617   }
5619   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5620   // if either of the casts is not free.
5621   if (N0.getOpcode() == ISD::AND &&
5622       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5623       N0.getOperand(1).getOpcode() == ISD::Constant &&
5624       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5625                            N0.getValueType()) ||
5626        !TLI.isZExtFree(N0.getValueType(), VT))) {
5627     SDValue X = N0.getOperand(0).getOperand(0);
5628     if (X.getValueType().bitsLT(VT)) {
5629       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5630     } else if (X.getValueType().bitsGT(VT)) {
5631       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5632     }
5633     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5634     Mask = Mask.zext(VT.getSizeInBits());
5635     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5636                        X, DAG.getConstant(Mask, VT));
5637   }
5639   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5640   // None of the supported targets knows how to perform load and vector_zext
5641   // on vectors in one instruction.  We only perform this transformation on
5642   // scalars.
5643   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5644       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5645       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5646        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
5647     bool DoXform = true;
5648     SmallVector<SDNode*, 4> SetCCs;
5649     if (!N0.hasOneUse())
5650       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5651     if (DoXform) {
5652       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5653       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5654                                        LN0->getChain(),
5655                                        LN0->getBasePtr(), N0.getValueType(),
5656                                        LN0->getMemOperand());
5657       CombineTo(N, ExtLoad);
5658       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5659                                   N0.getValueType(), ExtLoad);
5660       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5662       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5663                       ISD::ZERO_EXTEND);
5664       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5665     }
5666   }
5668   // fold (zext (and/or/xor (load x), cst)) ->
5669   //      (and/or/xor (zextload x), (zext cst))
5670   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5671        N0.getOpcode() == ISD::XOR) &&
5672       isa<LoadSDNode>(N0.getOperand(0)) &&
5673       N0.getOperand(1).getOpcode() == ISD::Constant &&
5674       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
5675       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5676     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5677     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5678       bool DoXform = true;
5679       SmallVector<SDNode*, 4> SetCCs;
5680       if (!N0.hasOneUse())
5681         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5682                                           SetCCs, TLI);
5683       if (DoXform) {
5684         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5685                                          LN0->getChain(), LN0->getBasePtr(),
5686                                          LN0->getMemoryVT(),
5687                                          LN0->getMemOperand());
5688         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5689         Mask = Mask.zext(VT.getSizeInBits());
5690         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5691                                   ExtLoad, DAG.getConstant(Mask, VT));
5692         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5693                                     SDLoc(N0.getOperand(0)),
5694                                     N0.getOperand(0).getValueType(), ExtLoad);
5695         CombineTo(N, And);
5696         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5697         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5698                         ISD::ZERO_EXTEND);
5699         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5700       }
5701     }
5702   }
5704   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5705   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5706   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5707       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5708     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5709     EVT MemVT = LN0->getMemoryVT();
5710     if ((!LegalOperations && !LN0->isVolatile()) ||
5711         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
5712       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5713                                        LN0->getChain(),
5714                                        LN0->getBasePtr(), MemVT,
5715                                        LN0->getMemOperand());
5716       CombineTo(N, ExtLoad);
5717       CombineTo(N0.getNode(),
5718                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5719                             ExtLoad),
5720                 ExtLoad.getValue(1));
5721       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5722     }
5723   }
5725   if (N0.getOpcode() == ISD::SETCC) {
5726     if (!LegalOperations && VT.isVector() &&
5727         N0.getValueType().getVectorElementType() == MVT::i1) {
5728       EVT N0VT = N0.getOperand(0).getValueType();
5729       if (getSetCCResultType(N0VT) == N0.getValueType())
5730         return SDValue();
5732       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5733       // Only do this before legalize for now.
5734       EVT EltVT = VT.getVectorElementType();
5735       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5736                                     DAG.getConstant(1, EltVT));
5737       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5738         // We know that the # elements of the results is the same as the
5739         // # elements of the compare (and the # elements of the compare result
5740         // for that matter).  Check to see that they are the same size.  If so,
5741         // we know that the element size of the sext'd result matches the
5742         // element size of the compare operands.
5743         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5744                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5745                                          N0.getOperand(1),
5746                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5747                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5748                                        OneOps));
5750       // If the desired elements are smaller or larger than the source
5751       // elements we can use a matching integer vector type and then
5752       // truncate/sign extend
5753       EVT MatchingElementType =
5754         EVT::getIntegerVT(*DAG.getContext(),
5755                           N0VT.getScalarType().getSizeInBits());
5756       EVT MatchingVectorType =
5757         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5758                          N0VT.getVectorNumElements());
5759       SDValue VsetCC =
5760         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5761                       N0.getOperand(1),
5762                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5763       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5764                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5765                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5766     }
5768     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5769     SDValue SCC =
5770       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5771                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5772                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5773     if (SCC.getNode()) return SCC;
5774   }
5776   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5777   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5778       isa<ConstantSDNode>(N0.getOperand(1)) &&
5779       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5780       N0.hasOneUse()) {
5781     SDValue ShAmt = N0.getOperand(1);
5782     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5783     if (N0.getOpcode() == ISD::SHL) {
5784       SDValue InnerZExt = N0.getOperand(0);
5785       // If the original shl may be shifting out bits, do not perform this
5786       // transformation.
5787       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5788         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5789       if (ShAmtVal > KnownZeroBits)
5790         return SDValue();
5791     }
5793     SDLoc DL(N);
5795     // Ensure that the shift amount is wide enough for the shifted value.
5796     if (VT.getSizeInBits() >= 256)
5797       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5799     return DAG.getNode(N0.getOpcode(), DL, VT,
5800                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5801                        ShAmt);
5802   }
5804   return SDValue();
5807 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5808   SDValue N0 = N->getOperand(0);
5809   EVT VT = N->getValueType(0);
5811   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5812                                               LegalOperations))
5813     return SDValue(Res, 0);
5815   // fold (aext (aext x)) -> (aext x)
5816   // fold (aext (zext x)) -> (zext x)
5817   // fold (aext (sext x)) -> (sext x)
5818   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5819       N0.getOpcode() == ISD::ZERO_EXTEND ||
5820       N0.getOpcode() == ISD::SIGN_EXTEND)
5821     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5823   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5824   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5825   if (N0.getOpcode() == ISD::TRUNCATE) {
5826     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5827     if (NarrowLoad.getNode()) {
5828       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5829       if (NarrowLoad.getNode() != N0.getNode()) {
5830         CombineTo(N0.getNode(), NarrowLoad);
5831         // CombineTo deleted the truncate, if needed, but not what's under it.
5832         AddToWorklist(oye);
5833       }
5834       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5835     }
5836   }
5838   // fold (aext (truncate x))
5839   if (N0.getOpcode() == ISD::TRUNCATE) {
5840     SDValue TruncOp = N0.getOperand(0);
5841     if (TruncOp.getValueType() == VT)
5842       return TruncOp; // x iff x size == zext size.
5843     if (TruncOp.getValueType().bitsGT(VT))
5844       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5845     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5846   }
5848   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5849   // if the trunc is not free.
5850   if (N0.getOpcode() == ISD::AND &&
5851       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5852       N0.getOperand(1).getOpcode() == ISD::Constant &&
5853       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5854                           N0.getValueType())) {
5855     SDValue X = N0.getOperand(0).getOperand(0);
5856     if (X.getValueType().bitsLT(VT)) {
5857       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5858     } else if (X.getValueType().bitsGT(VT)) {
5859       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5860     }
5861     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5862     Mask = Mask.zext(VT.getSizeInBits());
5863     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5864                        X, DAG.getConstant(Mask, VT));
5865   }
5867   // fold (aext (load x)) -> (aext (truncate (extload x)))
5868   // None of the supported targets knows how to perform load and any_ext
5869   // on vectors in one instruction.  We only perform this transformation on
5870   // scalars.
5871   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5872       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5873       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
5874     bool DoXform = true;
5875     SmallVector<SDNode*, 4> SetCCs;
5876     if (!N0.hasOneUse())
5877       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5878     if (DoXform) {
5879       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5880       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5881                                        LN0->getChain(),
5882                                        LN0->getBasePtr(), N0.getValueType(),
5883                                        LN0->getMemOperand());
5884       CombineTo(N, ExtLoad);
5885       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5886                                   N0.getValueType(), ExtLoad);
5887       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5888       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5889                       ISD::ANY_EXTEND);
5890       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5891     }
5892   }
5894   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5895   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5896   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5897   if (N0.getOpcode() == ISD::LOAD &&
5898       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5899       N0.hasOneUse()) {
5900     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5901     ISD::LoadExtType ExtType = LN0->getExtensionType();
5902     EVT MemVT = LN0->getMemoryVT();
5903     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
5904       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5905                                        VT, LN0->getChain(), LN0->getBasePtr(),
5906                                        MemVT, LN0->getMemOperand());
5907       CombineTo(N, ExtLoad);
5908       CombineTo(N0.getNode(),
5909                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5910                             N0.getValueType(), ExtLoad),
5911                 ExtLoad.getValue(1));
5912       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5913     }
5914   }
5916   if (N0.getOpcode() == ISD::SETCC) {
5917     // For vectors:
5918     // aext(setcc) -> vsetcc
5919     // aext(setcc) -> truncate(vsetcc)
5920     // aext(setcc) -> aext(vsetcc)
5921     // Only do this before legalize for now.
5922     if (VT.isVector() && !LegalOperations) {
5923       EVT N0VT = N0.getOperand(0).getValueType();
5924         // We know that the # elements of the results is the same as the
5925         // # elements of the compare (and the # elements of the compare result
5926         // for that matter).  Check to see that they are the same size.  If so,
5927         // we know that the element size of the sext'd result matches the
5928         // element size of the compare operands.
5929       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5930         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5931                              N0.getOperand(1),
5932                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5933       // If the desired elements are smaller or larger than the source
5934       // elements we can use a matching integer vector type and then
5935       // truncate/any extend
5936       else {
5937         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5938         SDValue VsetCC =
5939           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5940                         N0.getOperand(1),
5941                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5942         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5943       }
5944     }
5946     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5947     SDValue SCC =
5948       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5949                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5950                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5951     if (SCC.getNode())
5952       return SCC;
5953   }
5955   return SDValue();
5958 /// See if the specified operand can be simplified with the knowledge that only
5959 /// the bits specified by Mask are used.  If so, return the simpler operand,
5960 /// otherwise return a null SDValue.
5961 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5962   switch (V.getOpcode()) {
5963   default: break;
5964   case ISD::Constant: {
5965     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5966     assert(CV && "Const value should be ConstSDNode.");
5967     const APInt &CVal = CV->getAPIntValue();
5968     APInt NewVal = CVal & Mask;
5969     if (NewVal != CVal)
5970       return DAG.getConstant(NewVal, V.getValueType());
5971     break;
5972   }
5973   case ISD::OR:
5974   case ISD::XOR:
5975     // If the LHS or RHS don't contribute bits to the or, drop them.
5976     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5977       return V.getOperand(1);
5978     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5979       return V.getOperand(0);
5980     break;
5981   case ISD::SRL:
5982     // Only look at single-use SRLs.
5983     if (!V.getNode()->hasOneUse())
5984       break;
5985     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5986       // See if we can recursively simplify the LHS.
5987       unsigned Amt = RHSC->getZExtValue();
5989       // Watch out for shift count overflow though.
5990       if (Amt >= Mask.getBitWidth()) break;
5991       APInt NewMask = Mask << Amt;
5992       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5993       if (SimplifyLHS.getNode())
5994         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5995                            SimplifyLHS, V.getOperand(1));
5996     }
5997   }
5998   return SDValue();
6001 /// If the result of a wider load is shifted to right of N  bits and then
6002 /// truncated to a narrower type and where N is a multiple of number of bits of
6003 /// the narrower type, transform it to a narrower load from address + N / num of
6004 /// bits of new type. If the result is to be extended, also fold the extension
6005 /// to form a extending load.
6006 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6007   unsigned Opc = N->getOpcode();
6009   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6010   SDValue N0 = N->getOperand(0);
6011   EVT VT = N->getValueType(0);
6012   EVT ExtVT = VT;
6014   // This transformation isn't valid for vector loads.
6015   if (VT.isVector())
6016     return SDValue();
6018   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6019   // extended to VT.
6020   if (Opc == ISD::SIGN_EXTEND_INREG) {
6021     ExtType = ISD::SEXTLOAD;
6022     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6023   } else if (Opc == ISD::SRL) {
6024     // Another special-case: SRL is basically zero-extending a narrower value.
6025     ExtType = ISD::ZEXTLOAD;
6026     N0 = SDValue(N, 0);
6027     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6028     if (!N01) return SDValue();
6029     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6030                               VT.getSizeInBits() - N01->getZExtValue());
6031   }
6032   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6033     return SDValue();
6035   unsigned EVTBits = ExtVT.getSizeInBits();
6037   // Do not generate loads of non-round integer types since these can
6038   // be expensive (and would be wrong if the type is not byte sized).
6039   if (!ExtVT.isRound())
6040     return SDValue();
6042   unsigned ShAmt = 0;
6043   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6044     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6045       ShAmt = N01->getZExtValue();
6046       // Is the shift amount a multiple of size of VT?
6047       if ((ShAmt & (EVTBits-1)) == 0) {
6048         N0 = N0.getOperand(0);
6049         // Is the load width a multiple of size of VT?
6050         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6051           return SDValue();
6052       }
6054       // At this point, we must have a load or else we can't do the transform.
6055       if (!isa<LoadSDNode>(N0)) return SDValue();
6057       // Because a SRL must be assumed to *need* to zero-extend the high bits
6058       // (as opposed to anyext the high bits), we can't combine the zextload
6059       // lowering of SRL and an sextload.
6060       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6061         return SDValue();
6063       // If the shift amount is larger than the input type then we're not
6064       // accessing any of the loaded bytes.  If the load was a zextload/extload
6065       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6066       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6067         return SDValue();
6068     }
6069   }
6071   // If the load is shifted left (and the result isn't shifted back right),
6072   // we can fold the truncate through the shift.
6073   unsigned ShLeftAmt = 0;
6074   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6075       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6076     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6077       ShLeftAmt = N01->getZExtValue();
6078       N0 = N0.getOperand(0);
6079     }
6080   }
6082   // If we haven't found a load, we can't narrow it.  Don't transform one with
6083   // multiple uses, this would require adding a new load.
6084   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6085     return SDValue();
6087   // Don't change the width of a volatile load.
6088   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6089   if (LN0->isVolatile())
6090     return SDValue();
6092   // Verify that we are actually reducing a load width here.
6093   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6094     return SDValue();
6096   // For the transform to be legal, the load must produce only two values
6097   // (the value loaded and the chain).  Don't transform a pre-increment
6098   // load, for example, which produces an extra value.  Otherwise the
6099   // transformation is not equivalent, and the downstream logic to replace
6100   // uses gets things wrong.
6101   if (LN0->getNumValues() > 2)
6102     return SDValue();
6104   // If the load that we're shrinking is an extload and we're not just
6105   // discarding the extension we can't simply shrink the load. Bail.
6106   // TODO: It would be possible to merge the extensions in some cases.
6107   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6108       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6109     return SDValue();
6111   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6112     return SDValue();
6114   EVT PtrType = N0.getOperand(1).getValueType();
6116   if (PtrType == MVT::Untyped || PtrType.isExtended())
6117     // It's not possible to generate a constant of extended or untyped type.
6118     return SDValue();
6120   // For big endian targets, we need to adjust the offset to the pointer to
6121   // load the correct bytes.
6122   if (TLI.isBigEndian()) {
6123     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6124     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6125     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6126   }
6128   uint64_t PtrOff = ShAmt / 8;
6129   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6130   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
6131                                PtrType, LN0->getBasePtr(),
6132                                DAG.getConstant(PtrOff, PtrType));
6133   AddToWorklist(NewPtr.getNode());
6135   SDValue Load;
6136   if (ExtType == ISD::NON_EXTLOAD)
6137     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6138                         LN0->getPointerInfo().getWithOffset(PtrOff),
6139                         LN0->isVolatile(), LN0->isNonTemporal(),
6140                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6141   else
6142     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6143                           LN0->getPointerInfo().getWithOffset(PtrOff),
6144                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6145                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6147   // Replace the old load's chain with the new load's chain.
6148   WorklistRemover DeadNodes(*this);
6149   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6151   // Shift the result left, if we've swallowed a left shift.
6152   SDValue Result = Load;
6153   if (ShLeftAmt != 0) {
6154     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6155     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6156       ShImmTy = VT;
6157     // If the shift amount is as large as the result size (but, presumably,
6158     // no larger than the source) then the useful bits of the result are
6159     // zero; we can't simply return the shortened shift, because the result
6160     // of that operation is undefined.
6161     if (ShLeftAmt >= VT.getSizeInBits())
6162       Result = DAG.getConstant(0, VT);
6163     else
6164       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
6165                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
6166   }
6168   // Return the new loaded value.
6169   return Result;
6172 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6173   SDValue N0 = N->getOperand(0);
6174   SDValue N1 = N->getOperand(1);
6175   EVT VT = N->getValueType(0);
6176   EVT EVT = cast<VTSDNode>(N1)->getVT();
6177   unsigned VTBits = VT.getScalarType().getSizeInBits();
6178   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6180   // fold (sext_in_reg c1) -> c1
6181   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6182     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6184   // If the input is already sign extended, just drop the extension.
6185   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6186     return N0;
6188   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6189   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6190       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6191     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6192                        N0.getOperand(0), N1);
6194   // fold (sext_in_reg (sext x)) -> (sext x)
6195   // fold (sext_in_reg (aext x)) -> (sext x)
6196   // if x is small enough.
6197   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6198     SDValue N00 = N0.getOperand(0);
6199     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6200         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6201       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6202   }
6204   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6205   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6206     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6208   // fold operands of sext_in_reg based on knowledge that the top bits are not
6209   // demanded.
6210   if (SimplifyDemandedBits(SDValue(N, 0)))
6211     return SDValue(N, 0);
6213   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6214   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6215   SDValue NarrowLoad = ReduceLoadWidth(N);
6216   if (NarrowLoad.getNode())
6217     return NarrowLoad;
6219   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6220   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6221   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6222   if (N0.getOpcode() == ISD::SRL) {
6223     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6224       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6225         // We can turn this into an SRA iff the input to the SRL is already sign
6226         // extended enough.
6227         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6228         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6229           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6230                              N0.getOperand(0), N0.getOperand(1));
6231       }
6232   }
6234   // fold (sext_inreg (extload x)) -> (sextload x)
6235   if (ISD::isEXTLoad(N0.getNode()) &&
6236       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6237       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6238       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6239        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6240     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6241     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6242                                      LN0->getChain(),
6243                                      LN0->getBasePtr(), EVT,
6244                                      LN0->getMemOperand());
6245     CombineTo(N, ExtLoad);
6246     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6247     AddToWorklist(ExtLoad.getNode());
6248     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6249   }
6250   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6251   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6252       N0.hasOneUse() &&
6253       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6254       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6255        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6256     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6257     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6258                                      LN0->getChain(),
6259                                      LN0->getBasePtr(), EVT,
6260                                      LN0->getMemOperand());
6261     CombineTo(N, ExtLoad);
6262     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6263     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6264   }
6266   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6267   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6268     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6269                                        N0.getOperand(1), false);
6270     if (BSwap.getNode())
6271       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6272                          BSwap, N1);
6273   }
6275   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6276   // into a build_vector.
6277   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6278     SmallVector<SDValue, 8> Elts;
6279     unsigned NumElts = N0->getNumOperands();
6280     unsigned ShAmt = VTBits - EVTBits;
6282     for (unsigned i = 0; i != NumElts; ++i) {
6283       SDValue Op = N0->getOperand(i);
6284       if (Op->getOpcode() == ISD::UNDEF) {
6285         Elts.push_back(Op);
6286         continue;
6287       }
6289       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6290       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6291       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6292                                      Op.getValueType()));
6293     }
6295     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6296   }
6298   return SDValue();
6301 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6302   SDValue N0 = N->getOperand(0);
6303   EVT VT = N->getValueType(0);
6304   bool isLE = TLI.isLittleEndian();
6306   // noop truncate
6307   if (N0.getValueType() == N->getValueType(0))
6308     return N0;
6309   // fold (truncate c1) -> c1
6310   if (isa<ConstantSDNode>(N0))
6311     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6312   // fold (truncate (truncate x)) -> (truncate x)
6313   if (N0.getOpcode() == ISD::TRUNCATE)
6314     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6315   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6316   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6317       N0.getOpcode() == ISD::SIGN_EXTEND ||
6318       N0.getOpcode() == ISD::ANY_EXTEND) {
6319     if (N0.getOperand(0).getValueType().bitsLT(VT))
6320       // if the source is smaller than the dest, we still need an extend
6321       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6322                          N0.getOperand(0));
6323     if (N0.getOperand(0).getValueType().bitsGT(VT))
6324       // if the source is larger than the dest, than we just need the truncate
6325       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6326     // if the source and dest are the same type, we can drop both the extend
6327     // and the truncate.
6328     return N0.getOperand(0);
6329   }
6331   // Fold extract-and-trunc into a narrow extract. For example:
6332   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6333   //   i32 y = TRUNCATE(i64 x)
6334   //        -- becomes --
6335   //   v16i8 b = BITCAST (v2i64 val)
6336   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6337   //
6338   // Note: We only run this optimization after type legalization (which often
6339   // creates this pattern) and before operation legalization after which
6340   // we need to be more careful about the vector instructions that we generate.
6341   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6342       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6344     EVT VecTy = N0.getOperand(0).getValueType();
6345     EVT ExTy = N0.getValueType();
6346     EVT TrTy = N->getValueType(0);
6348     unsigned NumElem = VecTy.getVectorNumElements();
6349     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6351     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6352     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6354     SDValue EltNo = N0->getOperand(1);
6355     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6356       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6357       EVT IndexTy = TLI.getVectorIdxTy();
6358       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6360       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6361                               NVT, N0.getOperand(0));
6363       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6364                          SDLoc(N), TrTy, V,
6365                          DAG.getConstant(Index, IndexTy));
6366     }
6367   }
6369   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6370   if (N0.getOpcode() == ISD::SELECT) {
6371     EVT SrcVT = N0.getValueType();
6372     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6373         TLI.isTruncateFree(SrcVT, VT)) {
6374       SDLoc SL(N0);
6375       SDValue Cond = N0.getOperand(0);
6376       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6377       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6378       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6379     }
6380   }
6382   // Fold a series of buildvector, bitcast, and truncate if possible.
6383   // For example fold
6384   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6385   //   (2xi32 (buildvector x, y)).
6386   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6387       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6388       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6389       N0.getOperand(0).hasOneUse()) {
6391     SDValue BuildVect = N0.getOperand(0);
6392     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6393     EVT TruncVecEltTy = VT.getVectorElementType();
6395     // Check that the element types match.
6396     if (BuildVectEltTy == TruncVecEltTy) {
6397       // Now we only need to compute the offset of the truncated elements.
6398       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6399       unsigned TruncVecNumElts = VT.getVectorNumElements();
6400       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6402       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6403              "Invalid number of elements");
6405       SmallVector<SDValue, 8> Opnds;
6406       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6407         Opnds.push_back(BuildVect.getOperand(i));
6409       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6410     }
6411   }
6413   // See if we can simplify the input to this truncate through knowledge that
6414   // only the low bits are being used.
6415   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6416   // Currently we only perform this optimization on scalars because vectors
6417   // may have different active low bits.
6418   if (!VT.isVector()) {
6419     SDValue Shorter =
6420       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6421                                                VT.getSizeInBits()));
6422     if (Shorter.getNode())
6423       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6424   }
6425   // fold (truncate (load x)) -> (smaller load x)
6426   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6427   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6428     SDValue Reduced = ReduceLoadWidth(N);
6429     if (Reduced.getNode())
6430       return Reduced;
6431     // Handle the case where the load remains an extending load even
6432     // after truncation.
6433     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6434       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6435       if (!LN0->isVolatile() &&
6436           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6437         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6438                                          VT, LN0->getChain(), LN0->getBasePtr(),
6439                                          LN0->getMemoryVT(),
6440                                          LN0->getMemOperand());
6441         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6442         return NewLoad;
6443       }
6444     }
6445   }
6446   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6447   // where ... are all 'undef'.
6448   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6449     SmallVector<EVT, 8> VTs;
6450     SDValue V;
6451     unsigned Idx = 0;
6452     unsigned NumDefs = 0;
6454     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6455       SDValue X = N0.getOperand(i);
6456       if (X.getOpcode() != ISD::UNDEF) {
6457         V = X;
6458         Idx = i;
6459         NumDefs++;
6460       }
6461       // Stop if more than one members are non-undef.
6462       if (NumDefs > 1)
6463         break;
6464       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6465                                      VT.getVectorElementType(),
6466                                      X.getValueType().getVectorNumElements()));
6467     }
6469     if (NumDefs == 0)
6470       return DAG.getUNDEF(VT);
6472     if (NumDefs == 1) {
6473       assert(V.getNode() && "The single defined operand is empty!");
6474       SmallVector<SDValue, 8> Opnds;
6475       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6476         if (i != Idx) {
6477           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6478           continue;
6479         }
6480         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6481         AddToWorklist(NV.getNode());
6482         Opnds.push_back(NV);
6483       }
6484       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6485     }
6486   }
6488   // Simplify the operands using demanded-bits information.
6489   if (!VT.isVector() &&
6490       SimplifyDemandedBits(SDValue(N, 0)))
6491     return SDValue(N, 0);
6493   return SDValue();
6496 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6497   SDValue Elt = N->getOperand(i);
6498   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6499     return Elt.getNode();
6500   return Elt.getOperand(Elt.getResNo()).getNode();
6503 /// build_pair (load, load) -> load
6504 /// if load locations are consecutive.
6505 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6506   assert(N->getOpcode() == ISD::BUILD_PAIR);
6508   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6509   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6510   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6511       LD1->getAddressSpace() != LD2->getAddressSpace())
6512     return SDValue();
6513   EVT LD1VT = LD1->getValueType(0);
6515   if (ISD::isNON_EXTLoad(LD2) &&
6516       LD2->hasOneUse() &&
6517       // If both are volatile this would reduce the number of volatile loads.
6518       // If one is volatile it might be ok, but play conservative and bail out.
6519       !LD1->isVolatile() &&
6520       !LD2->isVolatile() &&
6521       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6522     unsigned Align = LD1->getAlignment();
6523     unsigned NewAlign = TLI.getDataLayout()->
6524       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6526     if (NewAlign <= Align &&
6527         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6528       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6529                          LD1->getBasePtr(), LD1->getPointerInfo(),
6530                          false, false, false, Align);
6531   }
6533   return SDValue();
6536 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6537   SDValue N0 = N->getOperand(0);
6538   EVT VT = N->getValueType(0);
6540   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6541   // Only do this before legalize, since afterward the target may be depending
6542   // on the bitconvert.
6543   // First check to see if this is all constant.
6544   if (!LegalTypes &&
6545       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6546       VT.isVector()) {
6547     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6549     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6550     assert(!DestEltVT.isVector() &&
6551            "Element type of vector ValueType must not be vector!");
6552     if (isSimple)
6553       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6554   }
6556   // If the input is a constant, let getNode fold it.
6557   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6558     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6559     if (Res.getNode() != N) {
6560       if (!LegalOperations ||
6561           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6562         return Res;
6564       // Folding it resulted in an illegal node, and it's too late to
6565       // do that. Clean up the old node and forego the transformation.
6566       // Ideally this won't happen very often, because instcombine
6567       // and the earlier dagcombine runs (where illegal nodes are
6568       // permitted) should have folded most of them already.
6569       deleteAndRecombine(Res.getNode());
6570     }
6571   }
6573   // (conv (conv x, t1), t2) -> (conv x, t2)
6574   if (N0.getOpcode() == ISD::BITCAST)
6575     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6576                        N0.getOperand(0));
6578   // fold (conv (load x)) -> (load (conv*)x)
6579   // If the resultant load doesn't need a higher alignment than the original!
6580   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6581       // Do not change the width of a volatile load.
6582       !cast<LoadSDNode>(N0)->isVolatile() &&
6583       // Do not remove the cast if the types differ in endian layout.
6584       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6585       TLI.hasBigEndianPartOrdering(VT) &&
6586       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6587       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6588     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6589     unsigned Align = TLI.getDataLayout()->
6590       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6591     unsigned OrigAlign = LN0->getAlignment();
6593     if (Align <= OrigAlign) {
6594       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6595                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6596                                  LN0->isVolatile(), LN0->isNonTemporal(),
6597                                  LN0->isInvariant(), OrigAlign,
6598                                  LN0->getAAInfo());
6599       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6600       return Load;
6601     }
6602   }
6604   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6605   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6606   // This often reduces constant pool loads.
6607   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6608        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6609       N0.getNode()->hasOneUse() && VT.isInteger() &&
6610       !VT.isVector() && !N0.getValueType().isVector()) {
6611     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6612                                   N0.getOperand(0));
6613     AddToWorklist(NewConv.getNode());
6615     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6616     if (N0.getOpcode() == ISD::FNEG)
6617       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6618                          NewConv, DAG.getConstant(SignBit, VT));
6619     assert(N0.getOpcode() == ISD::FABS);
6620     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6621                        NewConv, DAG.getConstant(~SignBit, VT));
6622   }
6624   // fold (bitconvert (fcopysign cst, x)) ->
6625   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6626   // Note that we don't handle (copysign x, cst) because this can always be
6627   // folded to an fneg or fabs.
6628   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6629       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6630       VT.isInteger() && !VT.isVector()) {
6631     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6632     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6633     if (isTypeLegal(IntXVT)) {
6634       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6635                               IntXVT, N0.getOperand(1));
6636       AddToWorklist(X.getNode());
6638       // If X has a different width than the result/lhs, sext it or truncate it.
6639       unsigned VTWidth = VT.getSizeInBits();
6640       if (OrigXWidth < VTWidth) {
6641         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6642         AddToWorklist(X.getNode());
6643       } else if (OrigXWidth > VTWidth) {
6644         // To get the sign bit in the right place, we have to shift it right
6645         // before truncating.
6646         X = DAG.getNode(ISD::SRL, SDLoc(X),
6647                         X.getValueType(), X,
6648                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6649         AddToWorklist(X.getNode());
6650         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6651         AddToWorklist(X.getNode());
6652       }
6654       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6655       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6656                       X, DAG.getConstant(SignBit, VT));
6657       AddToWorklist(X.getNode());
6659       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6660                                 VT, N0.getOperand(0));
6661       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6662                         Cst, DAG.getConstant(~SignBit, VT));
6663       AddToWorklist(Cst.getNode());
6665       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6666     }
6667   }
6669   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6670   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6671     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6672     if (CombineLD.getNode())
6673       return CombineLD;
6674   }
6676   return SDValue();
6679 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6680   EVT VT = N->getValueType(0);
6681   return CombineConsecutiveLoads(N, VT);
6684 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6685 /// operands. DstEltVT indicates the destination element value type.
6686 SDValue DAGCombiner::
6687 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6688   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6690   // If this is already the right type, we're done.
6691   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6693   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6694   unsigned DstBitSize = DstEltVT.getSizeInBits();
6696   // If this is a conversion of N elements of one type to N elements of another
6697   // type, convert each element.  This handles FP<->INT cases.
6698   if (SrcBitSize == DstBitSize) {
6699     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6700                               BV->getValueType(0).getVectorNumElements());
6702     // Due to the FP element handling below calling this routine recursively,
6703     // we can end up with a scalar-to-vector node here.
6704     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6705       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6706                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6707                                      DstEltVT, BV->getOperand(0)));
6709     SmallVector<SDValue, 8> Ops;
6710     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6711       SDValue Op = BV->getOperand(i);
6712       // If the vector element type is not legal, the BUILD_VECTOR operands
6713       // are promoted and implicitly truncated.  Make that explicit here.
6714       if (Op.getValueType() != SrcEltVT)
6715         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6716       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6717                                 DstEltVT, Op));
6718       AddToWorklist(Ops.back().getNode());
6719     }
6720     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6721   }
6723   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6724   // handle annoying details of growing/shrinking FP values, we convert them to
6725   // int first.
6726   if (SrcEltVT.isFloatingPoint()) {
6727     // Convert the input float vector to a int vector where the elements are the
6728     // same sizes.
6729     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6730     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6731     SrcEltVT = IntVT;
6732   }
6734   // Now we know the input is an integer vector.  If the output is a FP type,
6735   // convert to integer first, then to FP of the right size.
6736   if (DstEltVT.isFloatingPoint()) {
6737     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6738     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6740     // Next, convert to FP elements of the same size.
6741     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6742   }
6744   // Okay, we know the src/dst types are both integers of differing types.
6745   // Handling growing first.
6746   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6747   if (SrcBitSize < DstBitSize) {
6748     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6750     SmallVector<SDValue, 8> Ops;
6751     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6752          i += NumInputsPerOutput) {
6753       bool isLE = TLI.isLittleEndian();
6754       APInt NewBits = APInt(DstBitSize, 0);
6755       bool EltIsUndef = true;
6756       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6757         // Shift the previously computed bits over.
6758         NewBits <<= SrcBitSize;
6759         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6760         if (Op.getOpcode() == ISD::UNDEF) continue;
6761         EltIsUndef = false;
6763         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6764                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6765       }
6767       if (EltIsUndef)
6768         Ops.push_back(DAG.getUNDEF(DstEltVT));
6769       else
6770         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6771     }
6773     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6774     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6775   }
6777   // Finally, this must be the case where we are shrinking elements: each input
6778   // turns into multiple outputs.
6779   bool isS2V = ISD::isScalarToVector(BV);
6780   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6781   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6782                             NumOutputsPerInput*BV->getNumOperands());
6783   SmallVector<SDValue, 8> Ops;
6785   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6786     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6787       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6788         Ops.push_back(DAG.getUNDEF(DstEltVT));
6789       continue;
6790     }
6792     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6793                   getAPIntValue().zextOrTrunc(SrcBitSize);
6795     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6796       APInt ThisVal = OpVal.trunc(DstBitSize);
6797       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6798       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6799         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6800         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6801                            Ops[0]);
6802       OpVal = OpVal.lshr(DstBitSize);
6803     }
6805     // For big endian targets, swap the order of the pieces of each element.
6806     if (TLI.isBigEndian())
6807       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6808   }
6810   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6813 SDValue DAGCombiner::visitFADD(SDNode *N) {
6814   SDValue N0 = N->getOperand(0);
6815   SDValue N1 = N->getOperand(1);
6816   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6817   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6818   EVT VT = N->getValueType(0);
6819   const TargetOptions &Options = DAG.getTarget().Options;
6821   // fold vector ops
6822   if (VT.isVector()) {
6823     SDValue FoldedVOp = SimplifyVBinOp(N);
6824     if (FoldedVOp.getNode()) return FoldedVOp;
6825   }
6827   // fold (fadd c1, c2) -> c1 + c2
6828   if (N0CFP && N1CFP)
6829     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6831   // canonicalize constant to RHS
6832   if (N0CFP && !N1CFP)
6833     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6835   // fold (fadd A, (fneg B)) -> (fsub A, B)
6836   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6837       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6838     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6839                        GetNegatedExpression(N1, DAG, LegalOperations));
6841   // fold (fadd (fneg A), B) -> (fsub B, A)
6842   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6843       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6844     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6845                        GetNegatedExpression(N0, DAG, LegalOperations));
6847   // If 'unsafe math' is enabled, fold lots of things.
6848   if (Options.UnsafeFPMath) {
6849     // No FP constant should be created after legalization as Instruction
6850     // Selection pass has a hard time dealing with FP constants.
6851     bool AllowNewConst = (Level < AfterLegalizeDAG);
6853     // fold (fadd A, 0) -> A
6854     if (N1CFP && N1CFP->getValueAPF().isZero())
6855       return N0;
6857     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6858     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6859         isa<ConstantFPSDNode>(N0.getOperand(1)))
6860       return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6861                          DAG.getNode(ISD::FADD, SDLoc(N), VT,
6862                                      N0.getOperand(1), N1));
6864     // If allowed, fold (fadd (fneg x), x) -> 0.0
6865     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6866       return DAG.getConstantFP(0.0, VT);
6868     // If allowed, fold (fadd x, (fneg x)) -> 0.0
6869     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6870       return DAG.getConstantFP(0.0, VT);
6872     // We can fold chains of FADD's of the same value into multiplications.
6873     // This transform is not safe in general because we are reducing the number
6874     // of rounding steps.
6875     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
6876       if (N0.getOpcode() == ISD::FMUL) {
6877         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6878         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6880         // (fadd (fmul x, c), x) -> (fmul x, c+1)
6881         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6882           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6883                                        SDValue(CFP01, 0),
6884                                        DAG.getConstantFP(1.0, VT));
6885           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
6886         }
6888         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6889         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6890             N1.getOperand(0) == N1.getOperand(1) &&
6891             N0.getOperand(0) == N1.getOperand(0)) {
6892           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6893                                        SDValue(CFP01, 0),
6894                                        DAG.getConstantFP(2.0, VT));
6895           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6896                              N0.getOperand(0), NewCFP);
6897         }
6898       }
6900       if (N1.getOpcode() == ISD::FMUL) {
6901         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6902         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6904         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6905         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6906           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6907                                        SDValue(CFP11, 0),
6908                                        DAG.getConstantFP(1.0, VT));
6909           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
6910         }
6912         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6913         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6914             N0.getOperand(0) == N0.getOperand(1) &&
6915             N1.getOperand(0) == N0.getOperand(0)) {
6916           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6917                                        SDValue(CFP11, 0),
6918                                        DAG.getConstantFP(2.0, VT));
6919           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
6920         }
6921       }
6923       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
6924         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6925         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6926         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6927             (N0.getOperand(0) == N1))
6928           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6929                              N1, DAG.getConstantFP(3.0, VT));
6930       }
6932       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
6933         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6934         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6935         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6936             N1.getOperand(0) == N0)
6937           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6938                              N0, DAG.getConstantFP(3.0, VT));
6939       }
6941       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6942       if (AllowNewConst &&
6943           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6944           N0.getOperand(0) == N0.getOperand(1) &&
6945           N1.getOperand(0) == N1.getOperand(1) &&
6946           N0.getOperand(0) == N1.getOperand(0))
6947         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6948                            N0.getOperand(0), DAG.getConstantFP(4.0, VT));
6949     }
6950   } // enable-unsafe-fp-math
6952   // FADD -> FMA combines:
6953   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6954       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6955       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6957     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6958     if (N0.getOpcode() == ISD::FMUL &&
6959         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6960       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6961                          N0.getOperand(0), N0.getOperand(1), N1);
6963     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6964     // Note: Commutes FADD operands.
6965     if (N1.getOpcode() == ISD::FMUL &&
6966         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6967       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6968                          N1.getOperand(0), N1.getOperand(1), N0);
6970     // When FP_EXTEND nodes are free on the target, and there is an opportunity
6971     // to combine into FMA, arrange such nodes accordingly.
6972     if (TLI.isFPExtFree(VT)) {
6974       // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
6975       if (N0.getOpcode() == ISD::FP_EXTEND) {
6976         SDValue N00 = N0.getOperand(0);
6977         if (N00.getOpcode() == ISD::FMUL)
6978           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6979                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
6980                                          N00.getOperand(0)),
6981                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
6982                                          N00.getOperand(1)), N1);
6983       }
6985       // fold (fadd x, (fpext (fmul y, z)), z) -> (fma (fpext y), (fpext z), x)
6986       // Note: Commutes FADD operands.
6987       if (N1.getOpcode() == ISD::FP_EXTEND) {
6988         SDValue N10 = N1.getOperand(0);
6989         if (N10.getOpcode() == ISD::FMUL)
6990           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6991                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
6992                                          N10.getOperand(0)),
6993                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
6994                                          N10.getOperand(1)), N0);
6995       }
6996     }
6998     // More folding opportunities when target permits.
6999     if (TLI.enableAggressiveFMAFusion(VT)) {
7001       // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7002       if (N0.getOpcode() == ISD::FMA &&
7003           N0.getOperand(2).getOpcode() == ISD::FMUL)
7004         return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7005                            N0.getOperand(0), N0.getOperand(1),
7006                            DAG.getNode(ISD::FMA, SDLoc(N), VT,
7007                                        N0.getOperand(2).getOperand(0),
7008                                        N0.getOperand(2).getOperand(1),
7009                                        N1));
7011       // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7012       if (N1->getOpcode() == ISD::FMA &&
7013           N1.getOperand(2).getOpcode() == ISD::FMUL)
7014         return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7015                            N1.getOperand(0), N1.getOperand(1),
7016                            DAG.getNode(ISD::FMA, SDLoc(N), VT,
7017                                        N1.getOperand(2).getOperand(0),
7018                                        N1.getOperand(2).getOperand(1),
7019                                        N0));
7020     }
7021   }
7023   return SDValue();
7026 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7027   SDValue N0 = N->getOperand(0);
7028   SDValue N1 = N->getOperand(1);
7029   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7030   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7031   EVT VT = N->getValueType(0);
7032   SDLoc dl(N);
7033   const TargetOptions &Options = DAG.getTarget().Options;
7035   // fold vector ops
7036   if (VT.isVector()) {
7037     SDValue FoldedVOp = SimplifyVBinOp(N);
7038     if (FoldedVOp.getNode()) return FoldedVOp;
7039   }
7041   // fold (fsub c1, c2) -> c1-c2
7042   if (N0CFP && N1CFP)
7043     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
7045   // fold (fsub A, (fneg B)) -> (fadd A, B)
7046   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7047     return DAG.getNode(ISD::FADD, dl, VT, N0,
7048                        GetNegatedExpression(N1, DAG, LegalOperations));
7050   // If 'unsafe math' is enabled, fold lots of things.
7051   if (Options.UnsafeFPMath) {
7052     // (fsub A, 0) -> A
7053     if (N1CFP && N1CFP->getValueAPF().isZero())
7054       return N0;
7056     // (fsub 0, B) -> -B
7057     if (N0CFP && N0CFP->getValueAPF().isZero()) {
7058       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7059         return GetNegatedExpression(N1, DAG, LegalOperations);
7060       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7061         return DAG.getNode(ISD::FNEG, dl, VT, N1);
7062     }
7064     // (fsub x, x) -> 0.0
7065     if (N0 == N1)
7066       return DAG.getConstantFP(0.0f, VT);
7068     // (fsub x, (fadd x, y)) -> (fneg y)
7069     // (fsub x, (fadd y, x)) -> (fneg y)
7070     if (N1.getOpcode() == ISD::FADD) {
7071       SDValue N10 = N1->getOperand(0);
7072       SDValue N11 = N1->getOperand(1);
7074       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7075         return GetNegatedExpression(N11, DAG, LegalOperations);
7077       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7078         return GetNegatedExpression(N10, DAG, LegalOperations);
7079     }
7080   }
7082   // FSUB -> FMA combines:
7083   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
7084       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7085       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
7087     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7088     if (N0.getOpcode() == ISD::FMUL &&
7089         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
7090       return DAG.getNode(ISD::FMA, dl, VT,
7091                          N0.getOperand(0), N0.getOperand(1),
7092                          DAG.getNode(ISD::FNEG, dl, VT, N1));
7094     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7095     // Note: Commutes FSUB operands.
7096     if (N1.getOpcode() == ISD::FMUL &&
7097         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
7098       return DAG.getNode(ISD::FMA, dl, VT,
7099                          DAG.getNode(ISD::FNEG, dl, VT,
7100                          N1.getOperand(0)),
7101                          N1.getOperand(1), N0);
7103     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7104     if (N0.getOpcode() == ISD::FNEG &&
7105         N0.getOperand(0).getOpcode() == ISD::FMUL &&
7106         ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
7107             TLI.enableAggressiveFMAFusion(VT))) {
7108       SDValue N00 = N0.getOperand(0).getOperand(0);
7109       SDValue N01 = N0.getOperand(0).getOperand(1);
7110       return DAG.getNode(ISD::FMA, dl, VT,
7111                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
7112                          DAG.getNode(ISD::FNEG, dl, VT, N1));
7113     }
7115     // When FP_EXTEND nodes are free on the target, and there is an opportunity
7116     // to combine into FMA, arrange such nodes accordingly.
7117     if (TLI.isFPExtFree(VT)) {
7119       // fold (fsub (fpext (fmul x, y)), z)
7120       //   -> (fma (fpext x), (fpext y), (fneg z))
7121       if (N0.getOpcode() == ISD::FP_EXTEND) {
7122         SDValue N00 = N0.getOperand(0);
7123         if (N00.getOpcode() == ISD::FMUL)
7124           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7125                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7126                                          N00.getOperand(0)),
7127                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7128                                          N00.getOperand(1)),
7129                              DAG.getNode(ISD::FNEG, SDLoc(N), VT, N1));
7130       }
7132       // fold (fsub x, (fpext (fmul y, z)))
7133       //   -> (fma (fneg (fpext y)), (fpext z), x)
7134       // Note: Commutes FSUB operands.
7135       if (N1.getOpcode() == ISD::FP_EXTEND) {
7136         SDValue N10 = N1.getOperand(0);
7137         if (N10.getOpcode() == ISD::FMUL)
7138           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7139                              DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7140                                          DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7141                                                      VT, N10.getOperand(0))),
7142                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7143                                          N10.getOperand(1)),
7144                              N0);
7145       }
7147       // fold (fsub (fpext (fneg (fmul, x, y))), z)
7148       //   -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7149       if (N0.getOpcode() == ISD::FP_EXTEND) {
7150         SDValue N00 = N0.getOperand(0);
7151         if (N00.getOpcode() == ISD::FNEG) {
7152           SDValue N000 = N00.getOperand(0);
7153           if (N000.getOpcode() == ISD::FMUL) {
7154             return DAG.getNode(ISD::FMA, dl, VT,
7155                                DAG.getNode(ISD::FNEG, dl, VT,
7156                                            DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7157                                                        VT, N000.getOperand(0))),
7158                                DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7159                                            N000.getOperand(1)),
7160                                DAG.getNode(ISD::FNEG, dl, VT, N1));
7161           }
7162         }
7163       }
7165       // fold (fsub (fneg (fpext (fmul, x, y))), z)
7166       //   -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7167       if (N0.getOpcode() == ISD::FNEG) {
7168         SDValue N00 = N0.getOperand(0);
7169         if (N00.getOpcode() == ISD::FP_EXTEND) {
7170           SDValue N000 = N00.getOperand(0);
7171           if (N000.getOpcode() == ISD::FMUL) {
7172             return DAG.getNode(ISD::FMA, dl, VT,
7173                                DAG.getNode(ISD::FNEG, dl, VT,
7174                                            DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7175                                            VT, N000.getOperand(0))),
7176                                DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7177                                            N000.getOperand(1)),
7178                                DAG.getNode(ISD::FNEG, dl, VT, N1));
7179           }
7180         }
7181       }
7182     }
7184     // More folding opportunities when target permits.
7185     if (TLI.enableAggressiveFMAFusion(VT)) {
7187       // fold (fsub (fma x, y, (fmul u, v)), z)
7188       //   -> (fma x, y (fma u, v, (fneg z)))
7189       if (N0.getOpcode() == ISD::FMA &&
7190           N0.getOperand(2).getOpcode() == ISD::FMUL)
7191         return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7192                            N0.getOperand(0), N0.getOperand(1),
7193                            DAG.getNode(ISD::FMA, SDLoc(N), VT,
7194                                        N0.getOperand(2).getOperand(0),
7195                                        N0.getOperand(2).getOperand(1),
7196                                        DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7197                                                    N1)));
7199       // fold (fsub x, (fma y, z, (fmul u, v)))
7200       //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7201       if (N1.getOpcode() == ISD::FMA &&
7202           N1.getOperand(2).getOpcode() == ISD::FMUL) {
7203         SDValue N20 = N1.getOperand(2).getOperand(0);
7204         SDValue N21 = N1.getOperand(2).getOperand(1);
7205         return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7206                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7207                                        N1.getOperand(0)),
7208                            N1.getOperand(1),
7209                            DAG.getNode(ISD::FMA, SDLoc(N), VT,
7210                                        DAG.getNode(ISD::FNEG, SDLoc(N),  VT,
7211                                                    N20),
7212                                        N21, N0));
7213       }
7214     }
7215   }
7217   return SDValue();
7220 SDValue DAGCombiner::visitFMUL(SDNode *N) {
7221   SDValue N0 = N->getOperand(0);
7222   SDValue N1 = N->getOperand(1);
7223   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7224   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7225   EVT VT = N->getValueType(0);
7226   const TargetOptions &Options = DAG.getTarget().Options;
7228   // fold vector ops
7229   if (VT.isVector()) {
7230     // This just handles C1 * C2 for vectors. Other vector folds are below.
7231     SDValue FoldedVOp = SimplifyVBinOp(N);
7232     if (FoldedVOp.getNode())
7233       return FoldedVOp;
7234     // Canonicalize vector constant to RHS.
7235     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
7236         N1.getOpcode() != ISD::BUILD_VECTOR)
7237       if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
7238         if (BV0->isConstant())
7239           return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
7240   }
7242   // fold (fmul c1, c2) -> c1*c2
7243   if (N0CFP && N1CFP)
7244     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
7246   // canonicalize constant to RHS
7247   if (N0CFP && !N1CFP)
7248     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
7250   // fold (fmul A, 1.0) -> A
7251   if (N1CFP && N1CFP->isExactlyValue(1.0))
7252     return N0;
7254   if (Options.UnsafeFPMath) {
7255     // fold (fmul A, 0) -> 0
7256     if (N1CFP && N1CFP->getValueAPF().isZero())
7257       return N1;
7259     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7260     if (N0.getOpcode() == ISD::FMUL) {
7261       // Fold scalars or any vector constants (not just splats).
7262       // This fold is done in general by InstCombine, but extra fmul insts
7263       // may have been generated during lowering.
7264       SDValue N01 = N0.getOperand(1);
7265       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7266       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7267       if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7268           (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7269         SDLoc SL(N);
7270         SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7271         return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
7272       }
7273     }
7275     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7276     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7277     // during an early run of DAGCombiner can prevent folding with fmuls
7278     // inserted during lowering.
7279     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7280       SDLoc SL(N);
7281       const SDValue Two = DAG.getConstantFP(2.0, VT);
7282       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7283       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7284     }
7285   }
7287   // fold (fmul X, 2.0) -> (fadd X, X)
7288   if (N1CFP && N1CFP->isExactlyValue(+2.0))
7289     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
7291   // fold (fmul X, -1.0) -> (fneg X)
7292   if (N1CFP && N1CFP->isExactlyValue(-1.0))
7293     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7294       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
7296   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7297   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7298     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7299       // Both can be negated for free, check to see if at least one is cheaper
7300       // negated.
7301       if (LHSNeg == 2 || RHSNeg == 2)
7302         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7303                            GetNegatedExpression(N0, DAG, LegalOperations),
7304                            GetNegatedExpression(N1, DAG, LegalOperations));
7305     }
7306   }
7308   return SDValue();
7311 SDValue DAGCombiner::visitFMA(SDNode *N) {
7312   SDValue N0 = N->getOperand(0);
7313   SDValue N1 = N->getOperand(1);
7314   SDValue N2 = N->getOperand(2);
7315   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7316   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7317   EVT VT = N->getValueType(0);
7318   SDLoc dl(N);
7319   const TargetOptions &Options = DAG.getTarget().Options;
7321   // Constant fold FMA.
7322   if (isa<ConstantFPSDNode>(N0) &&
7323       isa<ConstantFPSDNode>(N1) &&
7324       isa<ConstantFPSDNode>(N2)) {
7325     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7326   }
7328   if (Options.UnsafeFPMath) {
7329     if (N0CFP && N0CFP->isZero())
7330       return N2;
7331     if (N1CFP && N1CFP->isZero())
7332       return N2;
7333   }
7334   if (N0CFP && N0CFP->isExactlyValue(1.0))
7335     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
7336   if (N1CFP && N1CFP->isExactlyValue(1.0))
7337     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
7339   // Canonicalize (fma c, x, y) -> (fma x, c, y)
7340   if (N0CFP && !N1CFP)
7341     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
7343   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
7344   if (Options.UnsafeFPMath && N1CFP &&
7345       N2.getOpcode() == ISD::FMUL &&
7346       N0 == N2.getOperand(0) &&
7347       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7348     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7349                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7350   }
7353   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
7354   if (Options.UnsafeFPMath &&
7355       N0.getOpcode() == ISD::FMUL && N1CFP &&
7356       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7357     return DAG.getNode(ISD::FMA, dl, VT,
7358                        N0.getOperand(0),
7359                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7360                        N2);
7361   }
7363   // (fma x, 1, y) -> (fadd x, y)
7364   // (fma x, -1, y) -> (fadd (fneg x), y)
7365   if (N1CFP) {
7366     if (N1CFP->isExactlyValue(1.0))
7367       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7369     if (N1CFP->isExactlyValue(-1.0) &&
7370         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7371       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
7372       AddToWorklist(RHSNeg.getNode());
7373       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7374     }
7375   }
7377   // (fma x, c, x) -> (fmul x, (c+1))
7378   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
7379     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7380                        DAG.getNode(ISD::FADD, dl, VT,
7381                                    N1, DAG.getConstantFP(1.0, VT)));
7383   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
7384   if (Options.UnsafeFPMath && N1CFP &&
7385       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7386     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7387                        DAG.getNode(ISD::FADD, dl, VT,
7388                                    N1, DAG.getConstantFP(-1.0, VT)));
7391   return SDValue();
7394 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7395   SDValue N0 = N->getOperand(0);
7396   SDValue N1 = N->getOperand(1);
7397   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7398   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7399   EVT VT = N->getValueType(0);
7400   SDLoc DL(N);
7401   const TargetOptions &Options = DAG.getTarget().Options;
7403   // fold vector ops
7404   if (VT.isVector()) {
7405     SDValue FoldedVOp = SimplifyVBinOp(N);
7406     if (FoldedVOp.getNode()) return FoldedVOp;
7407   }
7409   // fold (fdiv c1, c2) -> c1/c2
7410   if (N0CFP && N1CFP)
7411     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7413   if (Options.UnsafeFPMath) {
7414     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7415     if (N1CFP) {
7416       // Compute the reciprocal 1.0 / c2.
7417       APFloat N1APF = N1CFP->getValueAPF();
7418       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7419       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7420       // Only do the transform if the reciprocal is a legal fp immediate that
7421       // isn't too nasty (eg NaN, denormal, ...).
7422       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7423           (!LegalOperations ||
7424            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7425            // backend)... we should handle this gracefully after Legalize.
7426            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7427            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7428            TLI.isFPImmLegal(Recip, VT)))
7429         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7430                            DAG.getConstantFP(Recip, VT));
7431     }
7433     // If this FDIV is part of a reciprocal square root, it may be folded
7434     // into a target-specific square root estimate instruction.
7435     if (N1.getOpcode() == ISD::FSQRT) {
7436       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7437         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7438       }
7439     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7440                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7441       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7442         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7443         AddToWorklist(RV.getNode());
7444         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7445       }
7446     } else if (N1.getOpcode() == ISD::FP_ROUND &&
7447                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7448       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7449         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7450         AddToWorklist(RV.getNode());
7451         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7452       }
7453     } else if (N1.getOpcode() == ISD::FMUL) {
7454       // Look through an FMUL. Even though this won't remove the FDIV directly,
7455       // it's still worthwhile to get rid of the FSQRT if possible.
7456       SDValue SqrtOp;
7457       SDValue OtherOp;
7458       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7459         SqrtOp = N1.getOperand(0);
7460         OtherOp = N1.getOperand(1);
7461       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7462         SqrtOp = N1.getOperand(1);
7463         OtherOp = N1.getOperand(0);
7464       }
7465       if (SqrtOp.getNode()) {
7466         // We found a FSQRT, so try to make this fold:
7467         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7468         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7469           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7470           AddToWorklist(RV.getNode());
7471           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7472         }
7473       }
7474     }
7476     // Fold into a reciprocal estimate and multiply instead of a real divide.
7477     if (SDValue RV = BuildReciprocalEstimate(N1)) {
7478       AddToWorklist(RV.getNode());
7479       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7480     }
7481   }
7483   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7484   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7485     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7486       // Both can be negated for free, check to see if at least one is cheaper
7487       // negated.
7488       if (LHSNeg == 2 || RHSNeg == 2)
7489         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7490                            GetNegatedExpression(N0, DAG, LegalOperations),
7491                            GetNegatedExpression(N1, DAG, LegalOperations));
7492     }
7493   }
7495   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7496   // reciprocal.
7497   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
7498   // Notice that this is not always beneficial. One reason is different target
7499   // may have different costs for FDIV and FMUL, so sometimes the cost of two
7500   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
7501   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
7502   if (Options.UnsafeFPMath) {
7503     // Skip if current node is a reciprocal.
7504     if (N0CFP && N0CFP->isExactlyValue(1.0))
7505       return SDValue();
7507     SmallVector<SDNode *, 4> Users;
7508     // Find all FDIV users of the same divisor.
7509     for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
7510                               UE = N1.getNode()->use_end();
7511          UI != UE; ++UI) {
7512       SDNode *User = UI.getUse().getUser();
7513       if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
7514         Users.push_back(User);
7515     }
7517     if (TLI.combineRepeatedFPDivisors(Users.size())) {
7518       SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
7519       SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
7521       // Dividend / Divisor -> Dividend * Reciprocal
7522       for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
7523         if ((*I)->getOperand(0) != FPOne) {
7524           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
7525                                         (*I)->getOperand(0), Reciprocal);
7526           DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
7527         }
7528       }
7529       return SDValue();
7530     }
7531   }
7533   return SDValue();
7536 SDValue DAGCombiner::visitFREM(SDNode *N) {
7537   SDValue N0 = N->getOperand(0);
7538   SDValue N1 = N->getOperand(1);
7539   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7540   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7541   EVT VT = N->getValueType(0);
7543   // fold (frem c1, c2) -> fmod(c1,c2)
7544   if (N0CFP && N1CFP)
7545     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7547   return SDValue();
7550 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7551   if (DAG.getTarget().Options.UnsafeFPMath &&
7552       !TLI.isFsqrtCheap()) {
7553     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
7554     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7555       EVT VT = RV.getValueType();
7556       RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7557       AddToWorklist(RV.getNode());
7559       // Unfortunately, RV is now NaN if the input was exactly 0.
7560       // Select out this case and force the answer to 0.
7561       SDValue Zero = DAG.getConstantFP(0.0, VT);
7562       SDValue ZeroCmp =
7563         DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7564                      N->getOperand(0), Zero, ISD::SETEQ);
7565       AddToWorklist(ZeroCmp.getNode());
7566       AddToWorklist(RV.getNode());
7568       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7569                        SDLoc(N), VT, ZeroCmp, Zero, RV);
7570       return RV;
7571     }
7572   }
7573   return SDValue();
7576 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7577   SDValue N0 = N->getOperand(0);
7578   SDValue N1 = N->getOperand(1);
7579   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7580   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7581   EVT VT = N->getValueType(0);
7583   if (N0CFP && N1CFP)  // Constant fold
7584     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7586   if (N1CFP) {
7587     const APFloat& V = N1CFP->getValueAPF();
7588     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7589     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7590     if (!V.isNegative()) {
7591       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7592         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7593     } else {
7594       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7595         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7596                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7597     }
7598   }
7600   // copysign(fabs(x), y) -> copysign(x, y)
7601   // copysign(fneg(x), y) -> copysign(x, y)
7602   // copysign(copysign(x,z), y) -> copysign(x, y)
7603   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7604       N0.getOpcode() == ISD::FCOPYSIGN)
7605     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7606                        N0.getOperand(0), N1);
7608   // copysign(x, abs(y)) -> abs(x)
7609   if (N1.getOpcode() == ISD::FABS)
7610     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7612   // copysign(x, copysign(y,z)) -> copysign(x, z)
7613   if (N1.getOpcode() == ISD::FCOPYSIGN)
7614     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7615                        N0, N1.getOperand(1));
7617   // copysign(x, fp_extend(y)) -> copysign(x, y)
7618   // copysign(x, fp_round(y)) -> copysign(x, y)
7619   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7620     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7621                        N0, N1.getOperand(0));
7623   return SDValue();
7626 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7627   SDValue N0 = N->getOperand(0);
7628   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7629   EVT VT = N->getValueType(0);
7630   EVT OpVT = N0.getValueType();
7632   // fold (sint_to_fp c1) -> c1fp
7633   if (N0C &&
7634       // ...but only if the target supports immediate floating-point values
7635       (!LegalOperations ||
7636        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7637     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7639   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7640   // but UINT_TO_FP is legal on this target, try to convert.
7641   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7642       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7643     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7644     if (DAG.SignBitIsZero(N0))
7645       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7646   }
7648   // The next optimizations are desirable only if SELECT_CC can be lowered.
7649   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7650     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7651     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7652         !VT.isVector() &&
7653         (!LegalOperations ||
7654          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7655       SDValue Ops[] =
7656         { N0.getOperand(0), N0.getOperand(1),
7657           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7658           N0.getOperand(2) };
7659       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7660     }
7662     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7663     //      (select_cc x, y, 1.0, 0.0,, cc)
7664     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7665         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7666         (!LegalOperations ||
7667          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7668       SDValue Ops[] =
7669         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7670           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7671           N0.getOperand(0).getOperand(2) };
7672       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7673     }
7674   }
7676   return SDValue();
7679 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7680   SDValue N0 = N->getOperand(0);
7681   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7682   EVT VT = N->getValueType(0);
7683   EVT OpVT = N0.getValueType();
7685   // fold (uint_to_fp c1) -> c1fp
7686   if (N0C &&
7687       // ...but only if the target supports immediate floating-point values
7688       (!LegalOperations ||
7689        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7690     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7692   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7693   // but SINT_TO_FP is legal on this target, try to convert.
7694   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7695       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7696     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7697     if (DAG.SignBitIsZero(N0))
7698       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7699   }
7701   // The next optimizations are desirable only if SELECT_CC can be lowered.
7702   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7703     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7705     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7706         (!LegalOperations ||
7707          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7708       SDValue Ops[] =
7709         { N0.getOperand(0), N0.getOperand(1),
7710           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7711           N0.getOperand(2) };
7712       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7713     }
7714   }
7716   return SDValue();
7719 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7720   SDValue N0 = N->getOperand(0);
7721   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7722   EVT VT = N->getValueType(0);
7724   // fold (fp_to_sint c1fp) -> c1
7725   if (N0CFP)
7726     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7728   return SDValue();
7731 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7732   SDValue N0 = N->getOperand(0);
7733   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7734   EVT VT = N->getValueType(0);
7736   // fold (fp_to_uint c1fp) -> c1
7737   if (N0CFP)
7738     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7740   return SDValue();
7743 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7744   SDValue N0 = N->getOperand(0);
7745   SDValue N1 = N->getOperand(1);
7746   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7747   EVT VT = N->getValueType(0);
7749   // fold (fp_round c1fp) -> c1fp
7750   if (N0CFP)
7751     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7753   // fold (fp_round (fp_extend x)) -> x
7754   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7755     return N0.getOperand(0);
7757   // fold (fp_round (fp_round x)) -> (fp_round x)
7758   if (N0.getOpcode() == ISD::FP_ROUND) {
7759     // This is a value preserving truncation if both round's are.
7760     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7761                    N0.getNode()->getConstantOperandVal(1) == 1;
7762     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7763                        DAG.getIntPtrConstant(IsTrunc));
7764   }
7766   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7767   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7768     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7769                               N0.getOperand(0), N1);
7770     AddToWorklist(Tmp.getNode());
7771     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7772                        Tmp, N0.getOperand(1));
7773   }
7775   return SDValue();
7778 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7779   SDValue N0 = N->getOperand(0);
7780   EVT VT = N->getValueType(0);
7781   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7782   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7784   // fold (fp_round_inreg c1fp) -> c1fp
7785   if (N0CFP && isTypeLegal(EVT)) {
7786     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7787     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7788   }
7790   return SDValue();
7793 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7794   SDValue N0 = N->getOperand(0);
7795   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7796   EVT VT = N->getValueType(0);
7798   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7799   if (N->hasOneUse() &&
7800       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7801     return SDValue();
7803   // fold (fp_extend c1fp) -> c1fp
7804   if (N0CFP)
7805     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7807   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7808   // value of X.
7809   if (N0.getOpcode() == ISD::FP_ROUND
7810       && N0.getNode()->getConstantOperandVal(1) == 1) {
7811     SDValue In = N0.getOperand(0);
7812     if (In.getValueType() == VT) return In;
7813     if (VT.bitsLT(In.getValueType()))
7814       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7815                          In, N0.getOperand(1));
7816     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7817   }
7819   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7820   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7821        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
7822     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7823     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7824                                      LN0->getChain(),
7825                                      LN0->getBasePtr(), N0.getValueType(),
7826                                      LN0->getMemOperand());
7827     CombineTo(N, ExtLoad);
7828     CombineTo(N0.getNode(),
7829               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7830                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7831               ExtLoad.getValue(1));
7832     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7833   }
7835   return SDValue();
7838 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7839   SDValue N0 = N->getOperand(0);
7840   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7841   EVT VT = N->getValueType(0);
7843   // fold (fceil c1) -> fceil(c1)
7844   if (N0CFP)
7845     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7847   return SDValue();
7850 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7851   SDValue N0 = N->getOperand(0);
7852   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7853   EVT VT = N->getValueType(0);
7855   // fold (ftrunc c1) -> ftrunc(c1)
7856   if (N0CFP)
7857     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7859   return SDValue();
7862 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7863   SDValue N0 = N->getOperand(0);
7864   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7865   EVT VT = N->getValueType(0);
7867   // fold (ffloor c1) -> ffloor(c1)
7868   if (N0CFP)
7869     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7871   return SDValue();
7874 // FIXME: FNEG and FABS have a lot in common; refactor.
7875 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7876   SDValue N0 = N->getOperand(0);
7877   EVT VT = N->getValueType(0);
7879   if (VT.isVector()) {
7880     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7881     if (FoldedVOp.getNode()) return FoldedVOp;
7882   }
7884   // Constant fold FNEG.
7885   if (isa<ConstantFPSDNode>(N0))
7886     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7888   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7889                          &DAG.getTarget().Options))
7890     return GetNegatedExpression(N0, DAG, LegalOperations);
7892   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7893   // constant pool values.
7894   if (!TLI.isFNegFree(VT) &&
7895       N0.getOpcode() == ISD::BITCAST &&
7896       N0.getNode()->hasOneUse()) {
7897     SDValue Int = N0.getOperand(0);
7898     EVT IntVT = Int.getValueType();
7899     if (IntVT.isInteger() && !IntVT.isVector()) {
7900       APInt SignMask;
7901       if (N0.getValueType().isVector()) {
7902         // For a vector, get a mask such as 0x80... per scalar element
7903         // and splat it.
7904         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7905         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7906       } else {
7907         // For a scalar, just generate 0x80...
7908         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7909       }
7910       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7911                         DAG.getConstant(SignMask, IntVT));
7912       AddToWorklist(Int.getNode());
7913       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7914     }
7915   }
7917   // (fneg (fmul c, x)) -> (fmul -c, x)
7918   if (N0.getOpcode() == ISD::FMUL) {
7919     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7920     if (CFP1) {
7921       APFloat CVal = CFP1->getValueAPF();
7922       CVal.changeSign();
7923       if (Level >= AfterLegalizeDAG &&
7924           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7925            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7926         return DAG.getNode(
7927             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7928             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7929     }
7930   }
7932   return SDValue();
7935 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
7936   SDValue N0 = N->getOperand(0);
7937   SDValue N1 = N->getOperand(1);
7938   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7939   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7941   if (N0CFP && N1CFP) {
7942     const APFloat &C0 = N0CFP->getValueAPF();
7943     const APFloat &C1 = N1CFP->getValueAPF();
7944     return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
7945   }
7947   if (N0CFP) {
7948     EVT VT = N->getValueType(0);
7949     // Canonicalize to constant on RHS.
7950     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
7951   }
7953   return SDValue();
7956 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
7957   SDValue N0 = N->getOperand(0);
7958   SDValue N1 = N->getOperand(1);
7959   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7960   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7962   if (N0CFP && N1CFP) {
7963     const APFloat &C0 = N0CFP->getValueAPF();
7964     const APFloat &C1 = N1CFP->getValueAPF();
7965     return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
7966   }
7968   if (N0CFP) {
7969     EVT VT = N->getValueType(0);
7970     // Canonicalize to constant on RHS.
7971     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
7972   }
7974   return SDValue();
7977 SDValue DAGCombiner::visitFABS(SDNode *N) {
7978   SDValue N0 = N->getOperand(0);
7979   EVT VT = N->getValueType(0);
7981   if (VT.isVector()) {
7982     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7983     if (FoldedVOp.getNode()) return FoldedVOp;
7984   }
7986   // fold (fabs c1) -> fabs(c1)
7987   if (isa<ConstantFPSDNode>(N0))
7988     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7990   // fold (fabs (fabs x)) -> (fabs x)
7991   if (N0.getOpcode() == ISD::FABS)
7992     return N->getOperand(0);
7994   // fold (fabs (fneg x)) -> (fabs x)
7995   // fold (fabs (fcopysign x, y)) -> (fabs x)
7996   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7997     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7999   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8000   // constant pool values.
8001   if (!TLI.isFAbsFree(VT) &&
8002       N0.getOpcode() == ISD::BITCAST &&
8003       N0.getNode()->hasOneUse()) {
8004     SDValue Int = N0.getOperand(0);
8005     EVT IntVT = Int.getValueType();
8006     if (IntVT.isInteger() && !IntVT.isVector()) {
8007       APInt SignMask;
8008       if (N0.getValueType().isVector()) {
8009         // For a vector, get a mask such as 0x7f... per scalar element
8010         // and splat it.
8011         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8012         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8013       } else {
8014         // For a scalar, just generate 0x7f...
8015         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8016       }
8017       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
8018                         DAG.getConstant(SignMask, IntVT));
8019       AddToWorklist(Int.getNode());
8020       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8021     }
8022   }
8024   return SDValue();
8027 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8028   SDValue Chain = N->getOperand(0);
8029   SDValue N1 = N->getOperand(1);
8030   SDValue N2 = N->getOperand(2);
8032   // If N is a constant we could fold this into a fallthrough or unconditional
8033   // branch. However that doesn't happen very often in normal code, because
8034   // Instcombine/SimplifyCFG should have handled the available opportunities.
8035   // If we did this folding here, it would be necessary to update the
8036   // MachineBasicBlock CFG, which is awkward.
8038   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8039   // on the target.
8040   if (N1.getOpcode() == ISD::SETCC &&
8041       TLI.isOperationLegalOrCustom(ISD::BR_CC,
8042                                    N1.getOperand(0).getValueType())) {
8043     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8044                        Chain, N1.getOperand(2),
8045                        N1.getOperand(0), N1.getOperand(1), N2);
8046   }
8048   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8049       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8050        (N1.getOperand(0).hasOneUse() &&
8051         N1.getOperand(0).getOpcode() == ISD::SRL))) {
8052     SDNode *Trunc = nullptr;
8053     if (N1.getOpcode() == ISD::TRUNCATE) {
8054       // Look pass the truncate.
8055       Trunc = N1.getNode();
8056       N1 = N1.getOperand(0);
8057     }
8059     // Match this pattern so that we can generate simpler code:
8060     //
8061     //   %a = ...
8062     //   %b = and i32 %a, 2
8063     //   %c = srl i32 %b, 1
8064     //   brcond i32 %c ...
8065     //
8066     // into
8067     //
8068     //   %a = ...
8069     //   %b = and i32 %a, 2
8070     //   %c = setcc eq %b, 0
8071     //   brcond %c ...
8072     //
8073     // This applies only when the AND constant value has one bit set and the
8074     // SRL constant is equal to the log2 of the AND constant. The back-end is
8075     // smart enough to convert the result into a TEST/JMP sequence.
8076     SDValue Op0 = N1.getOperand(0);
8077     SDValue Op1 = N1.getOperand(1);
8079     if (Op0.getOpcode() == ISD::AND &&
8080         Op1.getOpcode() == ISD::Constant) {
8081       SDValue AndOp1 = Op0.getOperand(1);
8083       if (AndOp1.getOpcode() == ISD::Constant) {
8084         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8086         if (AndConst.isPowerOf2() &&
8087             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8088           SDValue SetCC =
8089             DAG.getSetCC(SDLoc(N),
8090                          getSetCCResultType(Op0.getValueType()),
8091                          Op0, DAG.getConstant(0, Op0.getValueType()),
8092                          ISD::SETNE);
8094           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
8095                                           MVT::Other, Chain, SetCC, N2);
8096           // Don't add the new BRCond into the worklist or else SimplifySelectCC
8097           // will convert it back to (X & C1) >> C2.
8098           CombineTo(N, NewBRCond, false);
8099           // Truncate is dead.
8100           if (Trunc)
8101             deleteAndRecombine(Trunc);
8102           // Replace the uses of SRL with SETCC
8103           WorklistRemover DeadNodes(*this);
8104           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8105           deleteAndRecombine(N1.getNode());
8106           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8107         }
8108       }
8109     }
8111     if (Trunc)
8112       // Restore N1 if the above transformation doesn't match.
8113       N1 = N->getOperand(1);
8114   }
8116   // Transform br(xor(x, y)) -> br(x != y)
8117   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8118   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8119     SDNode *TheXor = N1.getNode();
8120     SDValue Op0 = TheXor->getOperand(0);
8121     SDValue Op1 = TheXor->getOperand(1);
8122     if (Op0.getOpcode() == Op1.getOpcode()) {
8123       // Avoid missing important xor optimizations.
8124       SDValue Tmp = visitXOR(TheXor);
8125       if (Tmp.getNode()) {
8126         if (Tmp.getNode() != TheXor) {
8127           DEBUG(dbgs() << "\nReplacing.8 ";
8128                 TheXor->dump(&DAG);
8129                 dbgs() << "\nWith: ";
8130                 Tmp.getNode()->dump(&DAG);
8131                 dbgs() << '\n');
8132           WorklistRemover DeadNodes(*this);
8133           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8134           deleteAndRecombine(TheXor);
8135           return DAG.getNode(ISD::BRCOND, SDLoc(N),
8136                              MVT::Other, Chain, Tmp, N2);
8137         }
8139         // visitXOR has changed XOR's operands or replaced the XOR completely,
8140         // bail out.
8141         return SDValue(N, 0);
8142       }
8143     }
8145     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8146       bool Equal = false;
8147       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8148         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8149             Op0.getOpcode() == ISD::XOR) {
8150           TheXor = Op0.getNode();
8151           Equal = true;
8152         }
8154       EVT SetCCVT = N1.getValueType();
8155       if (LegalTypes)
8156         SetCCVT = getSetCCResultType(SetCCVT);
8157       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8158                                    SetCCVT,
8159                                    Op0, Op1,
8160                                    Equal ? ISD::SETEQ : ISD::SETNE);
8161       // Replace the uses of XOR with SETCC
8162       WorklistRemover DeadNodes(*this);
8163       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8164       deleteAndRecombine(N1.getNode());
8165       return DAG.getNode(ISD::BRCOND, SDLoc(N),
8166                          MVT::Other, Chain, SetCC, N2);
8167     }
8168   }
8170   return SDValue();
8173 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8174 //
8175 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
8176   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
8177   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
8179   // If N is a constant we could fold this into a fallthrough or unconditional
8180   // branch. However that doesn't happen very often in normal code, because
8181   // Instcombine/SimplifyCFG should have handled the available opportunities.
8182   // If we did this folding here, it would be necessary to update the
8183   // MachineBasicBlock CFG, which is awkward.
8185   // Use SimplifySetCC to simplify SETCC's.
8186   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
8187                                CondLHS, CondRHS, CC->get(), SDLoc(N),
8188                                false);
8189   if (Simp.getNode()) AddToWorklist(Simp.getNode());
8191   // fold to a simpler setcc
8192   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
8193     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8194                        N->getOperand(0), Simp.getOperand(2),
8195                        Simp.getOperand(0), Simp.getOperand(1),
8196                        N->getOperand(4));
8198   return SDValue();
8201 /// Return true if 'Use' is a load or a store that uses N as its base pointer
8202 /// and that N may be folded in the load / store addressing mode.
8203 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8204                                     SelectionDAG &DAG,
8205                                     const TargetLowering &TLI) {
8206   EVT VT;
8207   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
8208     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8209       return false;
8210     VT = Use->getValueType(0);
8211   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
8212     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8213       return false;
8214     VT = ST->getValue().getValueType();
8215   } else
8216     return false;
8218   TargetLowering::AddrMode AM;
8219   if (N->getOpcode() == ISD::ADD) {
8220     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8221     if (Offset)
8222       // [reg +/- imm]
8223       AM.BaseOffs = Offset->getSExtValue();
8224     else
8225       // [reg +/- reg]
8226       AM.Scale = 1;
8227   } else if (N->getOpcode() == ISD::SUB) {
8228     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8229     if (Offset)
8230       // [reg +/- imm]
8231       AM.BaseOffs = -Offset->getSExtValue();
8232     else
8233       // [reg +/- reg]
8234       AM.Scale = 1;
8235   } else
8236     return false;
8238   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8241 /// Try turning a load/store into a pre-indexed load/store when the base
8242 /// pointer is an add or subtract and it has other uses besides the load/store.
8243 /// After the transformation, the new indexed load/store has effectively folded
8244 /// the add/subtract in and all of its other uses are redirected to the
8245 /// new load/store.
8246 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8247   if (Level < AfterLegalizeDAG)
8248     return false;
8250   bool isLoad = true;
8251   SDValue Ptr;
8252   EVT VT;
8253   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8254     if (LD->isIndexed())
8255       return false;
8256     VT = LD->getMemoryVT();
8257     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8258         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8259       return false;
8260     Ptr = LD->getBasePtr();
8261   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8262     if (ST->isIndexed())
8263       return false;
8264     VT = ST->getMemoryVT();
8265     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8266         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8267       return false;
8268     Ptr = ST->getBasePtr();
8269     isLoad = false;
8270   } else {
8271     return false;
8272   }
8274   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8275   // out.  There is no reason to make this a preinc/predec.
8276   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
8277       Ptr.getNode()->hasOneUse())
8278     return false;
8280   // Ask the target to do addressing mode selection.
8281   SDValue BasePtr;
8282   SDValue Offset;
8283   ISD::MemIndexedMode AM = ISD::UNINDEXED;
8284   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8285     return false;
8287   // Backends without true r+i pre-indexed forms may need to pass a
8288   // constant base with a variable offset so that constant coercion
8289   // will work with the patterns in canonical form.
8290   bool Swapped = false;
8291   if (isa<ConstantSDNode>(BasePtr)) {
8292     std::swap(BasePtr, Offset);
8293     Swapped = true;
8294   }
8296   // Don't create a indexed load / store with zero offset.
8297   if (isa<ConstantSDNode>(Offset) &&
8298       cast<ConstantSDNode>(Offset)->isNullValue())
8299     return false;
8301   // Try turning it into a pre-indexed load / store except when:
8302   // 1) The new base ptr is a frame index.
8303   // 2) If N is a store and the new base ptr is either the same as or is a
8304   //    predecessor of the value being stored.
8305   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
8306   //    that would create a cycle.
8307   // 4) All uses are load / store ops that use it as old base ptr.
8309   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
8310   // (plus the implicit offset) to a register to preinc anyway.
8311   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8312     return false;
8314   // Check #2.
8315   if (!isLoad) {
8316     SDValue Val = cast<StoreSDNode>(N)->getValue();
8317     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
8318       return false;
8319   }
8321   // If the offset is a constant, there may be other adds of constants that
8322   // can be folded with this one. We should do this to avoid having to keep
8323   // a copy of the original base pointer.
8324   SmallVector<SDNode *, 16> OtherUses;
8325   if (isa<ConstantSDNode>(Offset))
8326     for (SDNode *Use : BasePtr.getNode()->uses()) {
8327       if (Use == Ptr.getNode())
8328         continue;
8330       if (Use->isPredecessorOf(N))
8331         continue;
8333       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8334         OtherUses.clear();
8335         break;
8336       }
8338       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8339       if (Op1.getNode() == BasePtr.getNode())
8340         std::swap(Op0, Op1);
8341       assert(Op0.getNode() == BasePtr.getNode() &&
8342              "Use of ADD/SUB but not an operand");
8344       if (!isa<ConstantSDNode>(Op1)) {
8345         OtherUses.clear();
8346         break;
8347       }
8349       // FIXME: In some cases, we can be smarter about this.
8350       if (Op1.getValueType() != Offset.getValueType()) {
8351         OtherUses.clear();
8352         break;
8353       }
8355       OtherUses.push_back(Use);
8356     }
8358   if (Swapped)
8359     std::swap(BasePtr, Offset);
8361   // Now check for #3 and #4.
8362   bool RealUse = false;
8364   // Caches for hasPredecessorHelper
8365   SmallPtrSet<const SDNode *, 32> Visited;
8366   SmallVector<const SDNode *, 16> Worklist;
8368   for (SDNode *Use : Ptr.getNode()->uses()) {
8369     if (Use == N)
8370       continue;
8371     if (N->hasPredecessorHelper(Use, Visited, Worklist))
8372       return false;
8374     // If Ptr may be folded in addressing mode of other use, then it's
8375     // not profitable to do this transformation.
8376     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
8377       RealUse = true;
8378   }
8380   if (!RealUse)
8381     return false;
8383   SDValue Result;
8384   if (isLoad)
8385     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8386                                 BasePtr, Offset, AM);
8387   else
8388     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8389                                  BasePtr, Offset, AM);
8390   ++PreIndexedNodes;
8391   ++NodesCombined;
8392   DEBUG(dbgs() << "\nReplacing.4 ";
8393         N->dump(&DAG);
8394         dbgs() << "\nWith: ";
8395         Result.getNode()->dump(&DAG);
8396         dbgs() << '\n');
8397   WorklistRemover DeadNodes(*this);
8398   if (isLoad) {
8399     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8400     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8401   } else {
8402     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8403   }
8405   // Finally, since the node is now dead, remove it from the graph.
8406   deleteAndRecombine(N);
8408   if (Swapped)
8409     std::swap(BasePtr, Offset);
8411   // Replace other uses of BasePtr that can be updated to use Ptr
8412   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8413     unsigned OffsetIdx = 1;
8414     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8415       OffsetIdx = 0;
8416     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8417            BasePtr.getNode() && "Expected BasePtr operand");
8419     // We need to replace ptr0 in the following expression:
8420     //   x0 * offset0 + y0 * ptr0 = t0
8421     // knowing that
8422     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
8423     //
8424     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8425     // indexed load/store and the expresion that needs to be re-written.
8426     //
8427     // Therefore, we have:
8428     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
8430     ConstantSDNode *CN =
8431       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
8432     int X0, X1, Y0, Y1;
8433     APInt Offset0 = CN->getAPIntValue();
8434     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8436     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8437     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8438     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8439     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8441     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8443     APInt CNV = Offset0;
8444     if (X0 < 0) CNV = -CNV;
8445     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8446     else CNV = CNV - Offset1;
8448     // We can now generate the new expression.
8449     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8450     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8452     SDValue NewUse = DAG.getNode(Opcode,
8453                                  SDLoc(OtherUses[i]),
8454                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8455     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8456     deleteAndRecombine(OtherUses[i]);
8457   }
8459   // Replace the uses of Ptr with uses of the updated base value.
8460   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8461   deleteAndRecombine(Ptr.getNode());
8463   return true;
8466 /// Try to combine a load/store with a add/sub of the base pointer node into a
8467 /// post-indexed load/store. The transformation folded the add/subtract into the
8468 /// new indexed load/store effectively and all of its uses are redirected to the
8469 /// new load/store.
8470 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
8471   if (Level < AfterLegalizeDAG)
8472     return false;
8474   bool isLoad = true;
8475   SDValue Ptr;
8476   EVT VT;
8477   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8478     if (LD->isIndexed())
8479       return false;
8480     VT = LD->getMemoryVT();
8481     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8482         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8483       return false;
8484     Ptr = LD->getBasePtr();
8485   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8486     if (ST->isIndexed())
8487       return false;
8488     VT = ST->getMemoryVT();
8489     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8490         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8491       return false;
8492     Ptr = ST->getBasePtr();
8493     isLoad = false;
8494   } else {
8495     return false;
8496   }
8498   if (Ptr.getNode()->hasOneUse())
8499     return false;
8501   for (SDNode *Op : Ptr.getNode()->uses()) {
8502     if (Op == N ||
8503         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8504       continue;
8506     SDValue BasePtr;
8507     SDValue Offset;
8508     ISD::MemIndexedMode AM = ISD::UNINDEXED;
8509     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8510       // Don't create a indexed load / store with zero offset.
8511       if (isa<ConstantSDNode>(Offset) &&
8512           cast<ConstantSDNode>(Offset)->isNullValue())
8513         continue;
8515       // Try turning it into a post-indexed load / store except when
8516       // 1) All uses are load / store ops that use it as base ptr (and
8517       //    it may be folded as addressing mmode).
8518       // 2) Op must be independent of N, i.e. Op is neither a predecessor
8519       //    nor a successor of N. Otherwise, if Op is folded that would
8520       //    create a cycle.
8522       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8523         continue;
8525       // Check for #1.
8526       bool TryNext = false;
8527       for (SDNode *Use : BasePtr.getNode()->uses()) {
8528         if (Use == Ptr.getNode())
8529           continue;
8531         // If all the uses are load / store addresses, then don't do the
8532         // transformation.
8533         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8534           bool RealUse = false;
8535           for (SDNode *UseUse : Use->uses()) {
8536             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8537               RealUse = true;
8538           }
8540           if (!RealUse) {
8541             TryNext = true;
8542             break;
8543           }
8544         }
8545       }
8547       if (TryNext)
8548         continue;
8550       // Check for #2
8551       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8552         SDValue Result = isLoad
8553           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8554                                BasePtr, Offset, AM)
8555           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8556                                 BasePtr, Offset, AM);
8557         ++PostIndexedNodes;
8558         ++NodesCombined;
8559         DEBUG(dbgs() << "\nReplacing.5 ";
8560               N->dump(&DAG);
8561               dbgs() << "\nWith: ";
8562               Result.getNode()->dump(&DAG);
8563               dbgs() << '\n');
8564         WorklistRemover DeadNodes(*this);
8565         if (isLoad) {
8566           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8567           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8568         } else {
8569           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8570         }
8572         // Finally, since the node is now dead, remove it from the graph.
8573         deleteAndRecombine(N);
8575         // Replace the uses of Use with uses of the updated base value.
8576         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8577                                       Result.getValue(isLoad ? 1 : 0));
8578         deleteAndRecombine(Op);
8579         return true;
8580       }
8581     }
8582   }
8584   return false;
8587 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8588 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8589   ISD::MemIndexedMode AM = LD->getAddressingMode();
8590   assert(AM != ISD::UNINDEXED);
8591   SDValue BP = LD->getOperand(1);
8592   SDValue Inc = LD->getOperand(2);
8594   // Some backends use TargetConstants for load offsets, but don't expect
8595   // TargetConstants in general ADD nodes. We can convert these constants into
8596   // regular Constants (if the constant is not opaque).
8597   assert((Inc.getOpcode() != ISD::TargetConstant ||
8598           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8599          "Cannot split out indexing using opaque target constants");
8600   if (Inc.getOpcode() == ISD::TargetConstant) {
8601     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8602     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8603                           ConstInc->getValueType(0));
8604   }
8606   unsigned Opc =
8607       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8608   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8611 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8612   LoadSDNode *LD  = cast<LoadSDNode>(N);
8613   SDValue Chain = LD->getChain();
8614   SDValue Ptr   = LD->getBasePtr();
8616   // If load is not volatile and there are no uses of the loaded value (and
8617   // the updated indexed value in case of indexed loads), change uses of the
8618   // chain value into uses of the chain input (i.e. delete the dead load).
8619   if (!LD->isVolatile()) {
8620     if (N->getValueType(1) == MVT::Other) {
8621       // Unindexed loads.
8622       if (!N->hasAnyUseOfValue(0)) {
8623         // It's not safe to use the two value CombineTo variant here. e.g.
8624         // v1, chain2 = load chain1, loc
8625         // v2, chain3 = load chain2, loc
8626         // v3         = add v2, c
8627         // Now we replace use of chain2 with chain1.  This makes the second load
8628         // isomorphic to the one we are deleting, and thus makes this load live.
8629         DEBUG(dbgs() << "\nReplacing.6 ";
8630               N->dump(&DAG);
8631               dbgs() << "\nWith chain: ";
8632               Chain.getNode()->dump(&DAG);
8633               dbgs() << "\n");
8634         WorklistRemover DeadNodes(*this);
8635         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8637         if (N->use_empty())
8638           deleteAndRecombine(N);
8640         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8641       }
8642     } else {
8643       // Indexed loads.
8644       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8646       // If this load has an opaque TargetConstant offset, then we cannot split
8647       // the indexing into an add/sub directly (that TargetConstant may not be
8648       // valid for a different type of node, and we cannot convert an opaque
8649       // target constant into a regular constant).
8650       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8651                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8653       if (!N->hasAnyUseOfValue(0) &&
8654           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8655         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8656         SDValue Index;
8657         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8658           Index = SplitIndexingFromLoad(LD);
8659           // Try to fold the base pointer arithmetic into subsequent loads and
8660           // stores.
8661           AddUsersToWorklist(N);
8662         } else
8663           Index = DAG.getUNDEF(N->getValueType(1));
8664         DEBUG(dbgs() << "\nReplacing.7 ";
8665               N->dump(&DAG);
8666               dbgs() << "\nWith: ";
8667               Undef.getNode()->dump(&DAG);
8668               dbgs() << " and 2 other values\n");
8669         WorklistRemover DeadNodes(*this);
8670         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8671         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8672         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8673         deleteAndRecombine(N);
8674         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8675       }
8676     }
8677   }
8679   // If this load is directly stored, replace the load value with the stored
8680   // value.
8681   // TODO: Handle store large -> read small portion.
8682   // TODO: Handle TRUNCSTORE/LOADEXT
8683   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8684     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8685       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8686       if (PrevST->getBasePtr() == Ptr &&
8687           PrevST->getValue().getValueType() == N->getValueType(0))
8688       return CombineTo(N, Chain.getOperand(1), Chain);
8689     }
8690   }
8692   // Try to infer better alignment information than the load already has.
8693   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8694     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8695       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8696         SDValue NewLoad =
8697                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8698                               LD->getValueType(0),
8699                               Chain, Ptr, LD->getPointerInfo(),
8700                               LD->getMemoryVT(),
8701                               LD->isVolatile(), LD->isNonTemporal(),
8702                               LD->isInvariant(), Align, LD->getAAInfo());
8703         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8704       }
8705     }
8706   }
8708   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
8709                                                   : DAG.getSubtarget().useAA();
8710 #ifndef NDEBUG
8711   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8712       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8713     UseAA = false;
8714 #endif
8715   if (UseAA && LD->isUnindexed()) {
8716     // Walk up chain skipping non-aliasing memory nodes.
8717     SDValue BetterChain = FindBetterChain(N, Chain);
8719     // If there is a better chain.
8720     if (Chain != BetterChain) {
8721       SDValue ReplLoad;
8723       // Replace the chain to void dependency.
8724       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8725         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8726                                BetterChain, Ptr, LD->getMemOperand());
8727       } else {
8728         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8729                                   LD->getValueType(0),
8730                                   BetterChain, Ptr, LD->getMemoryVT(),
8731                                   LD->getMemOperand());
8732       }
8734       // Create token factor to keep old chain connected.
8735       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8736                                   MVT::Other, Chain, ReplLoad.getValue(1));
8738       // Make sure the new and old chains are cleaned up.
8739       AddToWorklist(Token.getNode());
8741       // Replace uses with load result and token factor. Don't add users
8742       // to work list.
8743       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8744     }
8745   }
8747   // Try transforming N to an indexed load.
8748   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8749     return SDValue(N, 0);
8751   // Try to slice up N to more direct loads if the slices are mapped to
8752   // different register banks or pairing can take place.
8753   if (SliceUpLoad(N))
8754     return SDValue(N, 0);
8756   return SDValue();
8759 namespace {
8760 /// \brief Helper structure used to slice a load in smaller loads.
8761 /// Basically a slice is obtained from the following sequence:
8762 /// Origin = load Ty1, Base
8763 /// Shift = srl Ty1 Origin, CstTy Amount
8764 /// Inst = trunc Shift to Ty2
8765 ///
8766 /// Then, it will be rewriten into:
8767 /// Slice = load SliceTy, Base + SliceOffset
8768 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8769 ///
8770 /// SliceTy is deduced from the number of bits that are actually used to
8771 /// build Inst.
8772 struct LoadedSlice {
8773   /// \brief Helper structure used to compute the cost of a slice.
8774   struct Cost {
8775     /// Are we optimizing for code size.
8776     bool ForCodeSize;
8777     /// Various cost.
8778     unsigned Loads;
8779     unsigned Truncates;
8780     unsigned CrossRegisterBanksCopies;
8781     unsigned ZExts;
8782     unsigned Shift;
8784     Cost(bool ForCodeSize = false)
8785         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8786           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8788     /// \brief Get the cost of one isolated slice.
8789     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8790         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8791           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8792       EVT TruncType = LS.Inst->getValueType(0);
8793       EVT LoadedType = LS.getLoadedType();
8794       if (TruncType != LoadedType &&
8795           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8796         ZExts = 1;
8797     }
8799     /// \brief Account for slicing gain in the current cost.
8800     /// Slicing provide a few gains like removing a shift or a
8801     /// truncate. This method allows to grow the cost of the original
8802     /// load with the gain from this slice.
8803     void addSliceGain(const LoadedSlice &LS) {
8804       // Each slice saves a truncate.
8805       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8806       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8807                               LS.Inst->getOperand(0).getValueType()))
8808         ++Truncates;
8809       // If there is a shift amount, this slice gets rid of it.
8810       if (LS.Shift)
8811         ++Shift;
8812       // If this slice can merge a cross register bank copy, account for it.
8813       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8814         ++CrossRegisterBanksCopies;
8815     }
8817     Cost &operator+=(const Cost &RHS) {
8818       Loads += RHS.Loads;
8819       Truncates += RHS.Truncates;
8820       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8821       ZExts += RHS.ZExts;
8822       Shift += RHS.Shift;
8823       return *this;
8824     }
8826     bool operator==(const Cost &RHS) const {
8827       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8828              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8829              ZExts == RHS.ZExts && Shift == RHS.Shift;
8830     }
8832     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8834     bool operator<(const Cost &RHS) const {
8835       // Assume cross register banks copies are as expensive as loads.
8836       // FIXME: Do we want some more target hooks?
8837       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8838       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8839       // Unless we are optimizing for code size, consider the
8840       // expensive operation first.
8841       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8842         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8843       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8844              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8845     }
8847     bool operator>(const Cost &RHS) const { return RHS < *this; }
8849     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8851     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8852   };
8853   // The last instruction that represent the slice. This should be a
8854   // truncate instruction.
8855   SDNode *Inst;
8856   // The original load instruction.
8857   LoadSDNode *Origin;
8858   // The right shift amount in bits from the original load.
8859   unsigned Shift;
8860   // The DAG from which Origin came from.
8861   // This is used to get some contextual information about legal types, etc.
8862   SelectionDAG *DAG;
8864   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8865               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8866       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8868   LoadedSlice(const LoadedSlice &LS)
8869       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8871   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8872   /// \return Result is \p BitWidth and has used bits set to 1 and
8873   ///         not used bits set to 0.
8874   APInt getUsedBits() const {
8875     // Reproduce the trunc(lshr) sequence:
8876     // - Start from the truncated value.
8877     // - Zero extend to the desired bit width.
8878     // - Shift left.
8879     assert(Origin && "No original load to compare against.");
8880     unsigned BitWidth = Origin->getValueSizeInBits(0);
8881     assert(Inst && "This slice is not bound to an instruction");
8882     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8883            "Extracted slice is bigger than the whole type!");
8884     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8885     UsedBits.setAllBits();
8886     UsedBits = UsedBits.zext(BitWidth);
8887     UsedBits <<= Shift;
8888     return UsedBits;
8889   }
8891   /// \brief Get the size of the slice to be loaded in bytes.
8892   unsigned getLoadedSize() const {
8893     unsigned SliceSize = getUsedBits().countPopulation();
8894     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8895     return SliceSize / 8;
8896   }
8898   /// \brief Get the type that will be loaded for this slice.
8899   /// Note: This may not be the final type for the slice.
8900   EVT getLoadedType() const {
8901     assert(DAG && "Missing context");
8902     LLVMContext &Ctxt = *DAG->getContext();
8903     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8904   }
8906   /// \brief Get the alignment of the load used for this slice.
8907   unsigned getAlignment() const {
8908     unsigned Alignment = Origin->getAlignment();
8909     unsigned Offset = getOffsetFromBase();
8910     if (Offset != 0)
8911       Alignment = MinAlign(Alignment, Alignment + Offset);
8912     return Alignment;
8913   }
8915   /// \brief Check if this slice can be rewritten with legal operations.
8916   bool isLegal() const {
8917     // An invalid slice is not legal.
8918     if (!Origin || !Inst || !DAG)
8919       return false;
8921     // Offsets are for indexed load only, we do not handle that.
8922     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8923       return false;
8925     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8927     // Check that the type is legal.
8928     EVT SliceType = getLoadedType();
8929     if (!TLI.isTypeLegal(SliceType))
8930       return false;
8932     // Check that the load is legal for this type.
8933     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8934       return false;
8936     // Check that the offset can be computed.
8937     // 1. Check its type.
8938     EVT PtrType = Origin->getBasePtr().getValueType();
8939     if (PtrType == MVT::Untyped || PtrType.isExtended())
8940       return false;
8942     // 2. Check that it fits in the immediate.
8943     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8944       return false;
8946     // 3. Check that the computation is legal.
8947     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8948       return false;
8950     // Check that the zext is legal if it needs one.
8951     EVT TruncateType = Inst->getValueType(0);
8952     if (TruncateType != SliceType &&
8953         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8954       return false;
8956     return true;
8957   }
8959   /// \brief Get the offset in bytes of this slice in the original chunk of
8960   /// bits.
8961   /// \pre DAG != nullptr.
8962   uint64_t getOffsetFromBase() const {
8963     assert(DAG && "Missing context.");
8964     bool IsBigEndian =
8965         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8966     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8967     uint64_t Offset = Shift / 8;
8968     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8969     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8970            "The size of the original loaded type is not a multiple of a"
8971            " byte.");
8972     // If Offset is bigger than TySizeInBytes, it means we are loading all
8973     // zeros. This should have been optimized before in the process.
8974     assert(TySizeInBytes > Offset &&
8975            "Invalid shift amount for given loaded size");
8976     if (IsBigEndian)
8977       Offset = TySizeInBytes - Offset - getLoadedSize();
8978     return Offset;
8979   }
8981   /// \brief Generate the sequence of instructions to load the slice
8982   /// represented by this object and redirect the uses of this slice to
8983   /// this new sequence of instructions.
8984   /// \pre this->Inst && this->Origin are valid Instructions and this
8985   /// object passed the legal check: LoadedSlice::isLegal returned true.
8986   /// \return The last instruction of the sequence used to load the slice.
8987   SDValue loadSlice() const {
8988     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8989     const SDValue &OldBaseAddr = Origin->getBasePtr();
8990     SDValue BaseAddr = OldBaseAddr;
8991     // Get the offset in that chunk of bytes w.r.t. the endianess.
8992     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8993     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8994     if (Offset) {
8995       // BaseAddr = BaseAddr + Offset.
8996       EVT ArithType = BaseAddr.getValueType();
8997       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8998                               DAG->getConstant(Offset, ArithType));
8999     }
9001     // Create the type of the loaded slice according to its size.
9002     EVT SliceType = getLoadedType();
9004     // Create the load for the slice.
9005     SDValue LastInst = DAG->getLoad(
9006         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9007         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9008         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9009     // If the final type is not the same as the loaded type, this means that
9010     // we have to pad with zero. Create a zero extend for that.
9011     EVT FinalType = Inst->getValueType(0);
9012     if (SliceType != FinalType)
9013       LastInst =
9014           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9015     return LastInst;
9016   }
9018   /// \brief Check if this slice can be merged with an expensive cross register
9019   /// bank copy. E.g.,
9020   /// i = load i32
9021   /// f = bitcast i32 i to float
9022   bool canMergeExpensiveCrossRegisterBankCopy() const {
9023     if (!Inst || !Inst->hasOneUse())
9024       return false;
9025     SDNode *Use = *Inst->use_begin();
9026     if (Use->getOpcode() != ISD::BITCAST)
9027       return false;
9028     assert(DAG && "Missing context");
9029     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9030     EVT ResVT = Use->getValueType(0);
9031     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9032     const TargetRegisterClass *ArgRC =
9033         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9034     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9035       return false;
9037     // At this point, we know that we perform a cross-register-bank copy.
9038     // Check if it is expensive.
9039     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9040     // Assume bitcasts are cheap, unless both register classes do not
9041     // explicitly share a common sub class.
9042     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9043       return false;
9045     // Check if it will be merged with the load.
9046     // 1. Check the alignment constraint.
9047     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9048         ResVT.getTypeForEVT(*DAG->getContext()));
9050     if (RequiredAlignment > getAlignment())
9051       return false;
9053     // 2. Check that the load is a legal operation for that type.
9054     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9055       return false;
9057     // 3. Check that we do not have a zext in the way.
9058     if (Inst->getValueType(0) != getLoadedType())
9059       return false;
9061     return true;
9062   }
9063 };
9066 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9067 /// \p UsedBits looks like 0..0 1..1 0..0.
9068 static bool areUsedBitsDense(const APInt &UsedBits) {
9069   // If all the bits are one, this is dense!
9070   if (UsedBits.isAllOnesValue())
9071     return true;
9073   // Get rid of the unused bits on the right.
9074   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9075   // Get rid of the unused bits on the left.
9076   if (NarrowedUsedBits.countLeadingZeros())
9077     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9078   // Check that the chunk of bits is completely used.
9079   return NarrowedUsedBits.isAllOnesValue();
9082 /// \brief Check whether or not \p First and \p Second are next to each other
9083 /// in memory. This means that there is no hole between the bits loaded
9084 /// by \p First and the bits loaded by \p Second.
9085 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9086                                      const LoadedSlice &Second) {
9087   assert(First.Origin == Second.Origin && First.Origin &&
9088          "Unable to match different memory origins.");
9089   APInt UsedBits = First.getUsedBits();
9090   assert((UsedBits & Second.getUsedBits()) == 0 &&
9091          "Slices are not supposed to overlap.");
9092   UsedBits |= Second.getUsedBits();
9093   return areUsedBitsDense(UsedBits);
9096 /// \brief Adjust the \p GlobalLSCost according to the target
9097 /// paring capabilities and the layout of the slices.
9098 /// \pre \p GlobalLSCost should account for at least as many loads as
9099 /// there is in the slices in \p LoadedSlices.
9100 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9101                                  LoadedSlice::Cost &GlobalLSCost) {
9102   unsigned NumberOfSlices = LoadedSlices.size();
9103   // If there is less than 2 elements, no pairing is possible.
9104   if (NumberOfSlices < 2)
9105     return;
9107   // Sort the slices so that elements that are likely to be next to each
9108   // other in memory are next to each other in the list.
9109   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9110             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9111     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9112     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9113   });
9114   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9115   // First (resp. Second) is the first (resp. Second) potentially candidate
9116   // to be placed in a paired load.
9117   const LoadedSlice *First = nullptr;
9118   const LoadedSlice *Second = nullptr;
9119   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9120                 // Set the beginning of the pair.
9121                                                            First = Second) {
9123     Second = &LoadedSlices[CurrSlice];
9125     // If First is NULL, it means we start a new pair.
9126     // Get to the next slice.
9127     if (!First)
9128       continue;
9130     EVT LoadedType = First->getLoadedType();
9132     // If the types of the slices are different, we cannot pair them.
9133     if (LoadedType != Second->getLoadedType())
9134       continue;
9136     // Check if the target supplies paired loads for this type.
9137     unsigned RequiredAlignment = 0;
9138     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9139       // move to the next pair, this type is hopeless.
9140       Second = nullptr;
9141       continue;
9142     }
9143     // Check if we meet the alignment requirement.
9144     if (RequiredAlignment > First->getAlignment())
9145       continue;
9147     // Check that both loads are next to each other in memory.
9148     if (!areSlicesNextToEachOther(*First, *Second))
9149       continue;
9151     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9152     --GlobalLSCost.Loads;
9153     // Move to the next pair.
9154     Second = nullptr;
9155   }
9158 /// \brief Check the profitability of all involved LoadedSlice.
9159 /// Currently, it is considered profitable if there is exactly two
9160 /// involved slices (1) which are (2) next to each other in memory, and
9161 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9162 ///
9163 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9164 /// the elements themselves.
9165 ///
9166 /// FIXME: When the cost model will be mature enough, we can relax
9167 /// constraints (1) and (2).
9168 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9169                                 const APInt &UsedBits, bool ForCodeSize) {
9170   unsigned NumberOfSlices = LoadedSlices.size();
9171   if (StressLoadSlicing)
9172     return NumberOfSlices > 1;
9174   // Check (1).
9175   if (NumberOfSlices != 2)
9176     return false;
9178   // Check (2).
9179   if (!areUsedBitsDense(UsedBits))
9180     return false;
9182   // Check (3).
9183   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9184   // The original code has one big load.
9185   OrigCost.Loads = 1;
9186   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9187     const LoadedSlice &LS = LoadedSlices[CurrSlice];
9188     // Accumulate the cost of all the slices.
9189     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9190     GlobalSlicingCost += SliceCost;
9192     // Account as cost in the original configuration the gain obtained
9193     // with the current slices.
9194     OrigCost.addSliceGain(LS);
9195   }
9197   // If the target supports paired load, adjust the cost accordingly.
9198   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9199   return OrigCost > GlobalSlicingCost;
9202 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9203 /// operations, split it in the various pieces being extracted.
9204 ///
9205 /// This sort of thing is introduced by SROA.
9206 /// This slicing takes care not to insert overlapping loads.
9207 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
9208 bool DAGCombiner::SliceUpLoad(SDNode *N) {
9209   if (Level < AfterLegalizeDAG)
9210     return false;
9212   LoadSDNode *LD = cast<LoadSDNode>(N);
9213   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9214       !LD->getValueType(0).isInteger())
9215     return false;
9217   // Keep track of already used bits to detect overlapping values.
9218   // In that case, we will just abort the transformation.
9219   APInt UsedBits(LD->getValueSizeInBits(0), 0);
9221   SmallVector<LoadedSlice, 4> LoadedSlices;
9223   // Check if this load is used as several smaller chunks of bits.
9224   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9225   // of computation for each trunc.
9226   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9227        UI != UIEnd; ++UI) {
9228     // Skip the uses of the chain.
9229     if (UI.getUse().getResNo() != 0)
9230       continue;
9232     SDNode *User = *UI;
9233     unsigned Shift = 0;
9235     // Check if this is a trunc(lshr).
9236     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9237         isa<ConstantSDNode>(User->getOperand(1))) {
9238       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9239       User = *User->use_begin();
9240     }
9242     // At this point, User is a Truncate, iff we encountered, trunc or
9243     // trunc(lshr).
9244     if (User->getOpcode() != ISD::TRUNCATE)
9245       return false;
9247     // The width of the type must be a power of 2 and greater than 8-bits.
9248     // Otherwise the load cannot be represented in LLVM IR.
9249     // Moreover, if we shifted with a non-8-bits multiple, the slice
9250     // will be across several bytes. We do not support that.
9251     unsigned Width = User->getValueSizeInBits(0);
9252     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9253       return 0;
9255     // Build the slice for this chain of computations.
9256     LoadedSlice LS(User, LD, Shift, &DAG);
9257     APInt CurrentUsedBits = LS.getUsedBits();
9259     // Check if this slice overlaps with another.
9260     if ((CurrentUsedBits & UsedBits) != 0)
9261       return false;
9262     // Update the bits used globally.
9263     UsedBits |= CurrentUsedBits;
9265     // Check if the new slice would be legal.
9266     if (!LS.isLegal())
9267       return false;
9269     // Record the slice.
9270     LoadedSlices.push_back(LS);
9271   }
9273   // Abort slicing if it does not seem to be profitable.
9274   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9275     return false;
9277   ++SlicedLoads;
9279   // Rewrite each chain to use an independent load.
9280   // By construction, each chain can be represented by a unique load.
9282   // Prepare the argument for the new token factor for all the slices.
9283   SmallVector<SDValue, 8> ArgChains;
9284   for (SmallVectorImpl<LoadedSlice>::const_iterator
9285            LSIt = LoadedSlices.begin(),
9286            LSItEnd = LoadedSlices.end();
9287        LSIt != LSItEnd; ++LSIt) {
9288     SDValue SliceInst = LSIt->loadSlice();
9289     CombineTo(LSIt->Inst, SliceInst, true);
9290     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9291       SliceInst = SliceInst.getOperand(0);
9292     assert(SliceInst->getOpcode() == ISD::LOAD &&
9293            "It takes more than a zext to get to the loaded slice!!");
9294     ArgChains.push_back(SliceInst.getValue(1));
9295   }
9297   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
9298                               ArgChains);
9299   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9300   return true;
9303 /// Check to see if V is (and load (ptr), imm), where the load is having
9304 /// specific bytes cleared out.  If so, return the byte size being masked out
9305 /// and the shift amount.
9306 static std::pair<unsigned, unsigned>
9307 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9308   std::pair<unsigned, unsigned> Result(0, 0);
9310   // Check for the structure we're looking for.
9311   if (V->getOpcode() != ISD::AND ||
9312       !isa<ConstantSDNode>(V->getOperand(1)) ||
9313       !ISD::isNormalLoad(V->getOperand(0).getNode()))
9314     return Result;
9316   // Check the chain and pointer.
9317   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
9318   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
9320   // The store should be chained directly to the load or be an operand of a
9321   // tokenfactor.
9322   if (LD == Chain.getNode())
9323     ; // ok.
9324   else if (Chain->getOpcode() != ISD::TokenFactor)
9325     return Result; // Fail.
9326   else {
9327     bool isOk = false;
9328     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9329       if (Chain->getOperand(i).getNode() == LD) {
9330         isOk = true;
9331         break;
9332       }
9333     if (!isOk) return Result;
9334   }
9336   // This only handles simple types.
9337   if (V.getValueType() != MVT::i16 &&
9338       V.getValueType() != MVT::i32 &&
9339       V.getValueType() != MVT::i64)
9340     return Result;
9342   // Check the constant mask.  Invert it so that the bits being masked out are
9343   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
9344   // follow the sign bit for uniformity.
9345   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
9346   unsigned NotMaskLZ = countLeadingZeros(NotMask);
9347   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
9348   unsigned NotMaskTZ = countTrailingZeros(NotMask);
9349   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
9350   if (NotMaskLZ == 64) return Result;  // All zero mask.
9352   // See if we have a continuous run of bits.  If so, we have 0*1+0*
9353   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
9354     return Result;
9356   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9357   if (V.getValueType() != MVT::i64 && NotMaskLZ)
9358     NotMaskLZ -= 64-V.getValueSizeInBits();
9360   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9361   switch (MaskedBytes) {
9362   case 1:
9363   case 2:
9364   case 4: break;
9365   default: return Result; // All one mask, or 5-byte mask.
9366   }
9368   // Verify that the first bit starts at a multiple of mask so that the access
9369   // is aligned the same as the access width.
9370   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
9372   Result.first = MaskedBytes;
9373   Result.second = NotMaskTZ/8;
9374   return Result;
9378 /// Check to see if IVal is something that provides a value as specified by
9379 /// MaskInfo. If so, replace the specified store with a narrower store of
9380 /// truncated IVal.
9381 static SDNode *
9382 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9383                                 SDValue IVal, StoreSDNode *St,
9384                                 DAGCombiner *DC) {
9385   unsigned NumBytes = MaskInfo.first;
9386   unsigned ByteShift = MaskInfo.second;
9387   SelectionDAG &DAG = DC->getDAG();
9389   // Check to see if IVal is all zeros in the part being masked in by the 'or'
9390   // that uses this.  If not, this is not a replacement.
9391   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9392                                   ByteShift*8, (ByteShift+NumBytes)*8);
9393   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
9395   // Check that it is legal on the target to do this.  It is legal if the new
9396   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9397   // legalization.
9398   MVT VT = MVT::getIntegerVT(NumBytes*8);
9399   if (!DC->isTypeLegal(VT))
9400     return nullptr;
9402   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
9403   // shifted by ByteShift and truncated down to NumBytes.
9404   if (ByteShift)
9405     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
9406                        DAG.getConstant(ByteShift*8,
9407                                     DC->getShiftAmountTy(IVal.getValueType())));
9409   // Figure out the offset for the store and the alignment of the access.
9410   unsigned StOffset;
9411   unsigned NewAlign = St->getAlignment();
9413   if (DAG.getTargetLoweringInfo().isLittleEndian())
9414     StOffset = ByteShift;
9415   else
9416     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
9418   SDValue Ptr = St->getBasePtr();
9419   if (StOffset) {
9420     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
9421                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9422     NewAlign = MinAlign(NewAlign, StOffset);
9423   }
9425   // Truncate down to the new size.
9426   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
9428   ++OpsNarrowed;
9429   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
9430                       St->getPointerInfo().getWithOffset(StOffset),
9431                       false, false, NewAlign).getNode();
9435 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9436 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9437 /// narrowing the load and store if it would end up being a win for performance
9438 /// or code size.
9439 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9440   StoreSDNode *ST  = cast<StoreSDNode>(N);
9441   if (ST->isVolatile())
9442     return SDValue();
9444   SDValue Chain = ST->getChain();
9445   SDValue Value = ST->getValue();
9446   SDValue Ptr   = ST->getBasePtr();
9447   EVT VT = Value.getValueType();
9449   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9450     return SDValue();
9452   unsigned Opc = Value.getOpcode();
9454   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9455   // is a byte mask indicating a consecutive number of bytes, check to see if
9456   // Y is known to provide just those bytes.  If so, we try to replace the
9457   // load + replace + store sequence with a single (narrower) store, which makes
9458   // the load dead.
9459   if (Opc == ISD::OR) {
9460     std::pair<unsigned, unsigned> MaskedLoad;
9461     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9462     if (MaskedLoad.first)
9463       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9464                                                   Value.getOperand(1), ST,this))
9465         return SDValue(NewST, 0);
9467     // Or is commutative, so try swapping X and Y.
9468     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9469     if (MaskedLoad.first)
9470       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9471                                                   Value.getOperand(0), ST,this))
9472         return SDValue(NewST, 0);
9473   }
9475   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9476       Value.getOperand(1).getOpcode() != ISD::Constant)
9477     return SDValue();
9479   SDValue N0 = Value.getOperand(0);
9480   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9481       Chain == SDValue(N0.getNode(), 1)) {
9482     LoadSDNode *LD = cast<LoadSDNode>(N0);
9483     if (LD->getBasePtr() != Ptr ||
9484         LD->getPointerInfo().getAddrSpace() !=
9485         ST->getPointerInfo().getAddrSpace())
9486       return SDValue();
9488     // Find the type to narrow it the load / op / store to.
9489     SDValue N1 = Value.getOperand(1);
9490     unsigned BitWidth = N1.getValueSizeInBits();
9491     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9492     if (Opc == ISD::AND)
9493       Imm ^= APInt::getAllOnesValue(BitWidth);
9494     if (Imm == 0 || Imm.isAllOnesValue())
9495       return SDValue();
9496     unsigned ShAmt = Imm.countTrailingZeros();
9497     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9498     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9499     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9500     // The narowwing should be profitable, the load/store operation should be
9501     // legal (or custom) and the store size should be equal to the NewVT width.
9502     while (NewBW < BitWidth &&
9503            (NewVT.getStoreSizeInBits() != NewBW ||
9504             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
9505             !TLI.isNarrowingProfitable(VT, NewVT))) {
9506       NewBW = NextPowerOf2(NewBW);
9507       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9508     }
9509     if (NewBW >= BitWidth)
9510       return SDValue();
9512     // If the lsb changed does not start at the type bitwidth boundary,
9513     // start at the previous one.
9514     if (ShAmt % NewBW)
9515       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9516     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9517                                    std::min(BitWidth, ShAmt + NewBW));
9518     if ((Imm & Mask) == Imm) {
9519       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9520       if (Opc == ISD::AND)
9521         NewImm ^= APInt::getAllOnesValue(NewBW);
9522       uint64_t PtrOff = ShAmt / 8;
9523       // For big endian targets, we need to adjust the offset to the pointer to
9524       // load the correct bytes.
9525       if (TLI.isBigEndian())
9526         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9528       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9529       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9530       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9531         return SDValue();
9533       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9534                                    Ptr.getValueType(), Ptr,
9535                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
9536       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9537                                   LD->getChain(), NewPtr,
9538                                   LD->getPointerInfo().getWithOffset(PtrOff),
9539                                   LD->isVolatile(), LD->isNonTemporal(),
9540                                   LD->isInvariant(), NewAlign,
9541                                   LD->getAAInfo());
9542       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9543                                    DAG.getConstant(NewImm, NewVT));
9544       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9545                                    NewVal, NewPtr,
9546                                    ST->getPointerInfo().getWithOffset(PtrOff),
9547                                    false, false, NewAlign);
9549       AddToWorklist(NewPtr.getNode());
9550       AddToWorklist(NewLD.getNode());
9551       AddToWorklist(NewVal.getNode());
9552       WorklistRemover DeadNodes(*this);
9553       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9554       ++OpsNarrowed;
9555       return NewST;
9556     }
9557   }
9559   return SDValue();
9562 /// For a given floating point load / store pair, if the load value isn't used
9563 /// by any other operations, then consider transforming the pair to integer
9564 /// load / store operations if the target deems the transformation profitable.
9565 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9566   StoreSDNode *ST  = cast<StoreSDNode>(N);
9567   SDValue Chain = ST->getChain();
9568   SDValue Value = ST->getValue();
9569   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9570       Value.hasOneUse() &&
9571       Chain == SDValue(Value.getNode(), 1)) {
9572     LoadSDNode *LD = cast<LoadSDNode>(Value);
9573     EVT VT = LD->getMemoryVT();
9574     if (!VT.isFloatingPoint() ||
9575         VT != ST->getMemoryVT() ||
9576         LD->isNonTemporal() ||
9577         ST->isNonTemporal() ||
9578         LD->getPointerInfo().getAddrSpace() != 0 ||
9579         ST->getPointerInfo().getAddrSpace() != 0)
9580       return SDValue();
9582     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9583     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9584         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9585         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9586         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9587       return SDValue();
9589     unsigned LDAlign = LD->getAlignment();
9590     unsigned STAlign = ST->getAlignment();
9591     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9592     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9593     if (LDAlign < ABIAlign || STAlign < ABIAlign)
9594       return SDValue();
9596     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9597                                 LD->getChain(), LD->getBasePtr(),
9598                                 LD->getPointerInfo(),
9599                                 false, false, false, LDAlign);
9601     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9602                                  NewLD, ST->getBasePtr(),
9603                                  ST->getPointerInfo(),
9604                                  false, false, STAlign);
9606     AddToWorklist(NewLD.getNode());
9607     AddToWorklist(NewST.getNode());
9608     WorklistRemover DeadNodes(*this);
9609     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9610     ++LdStFP2Int;
9611     return NewST;
9612   }
9614   return SDValue();
9617 /// Helper struct to parse and store a memory address as base + index + offset.
9618 /// We ignore sign extensions when it is safe to do so.
9619 /// The following two expressions are not equivalent. To differentiate we need
9620 /// to store whether there was a sign extension involved in the index
9621 /// computation.
9622 ///  (load (i64 add (i64 copyfromreg %c)
9623 ///                 (i64 signextend (add (i8 load %index)
9624 ///                                      (i8 1))))
9625 /// vs
9626 ///
9627 /// (load (i64 add (i64 copyfromreg %c)
9628 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
9629 ///                                         (i32 1)))))
9630 struct BaseIndexOffset {
9631   SDValue Base;
9632   SDValue Index;
9633   int64_t Offset;
9634   bool IsIndexSignExt;
9636   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9638   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9639                   bool IsIndexSignExt) :
9640     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9642   bool equalBaseIndex(const BaseIndexOffset &Other) {
9643     return Other.Base == Base && Other.Index == Index &&
9644       Other.IsIndexSignExt == IsIndexSignExt;
9645   }
9647   /// Parses tree in Ptr for base, index, offset addresses.
9648   static BaseIndexOffset match(SDValue Ptr) {
9649     bool IsIndexSignExt = false;
9651     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9652     // instruction, then it could be just the BASE or everything else we don't
9653     // know how to handle. Just use Ptr as BASE and give up.
9654     if (Ptr->getOpcode() != ISD::ADD)
9655       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9657     // We know that we have at least an ADD instruction. Try to pattern match
9658     // the simple case of BASE + OFFSET.
9659     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9660       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9661       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9662                               IsIndexSignExt);
9663     }
9665     // Inside a loop the current BASE pointer is calculated using an ADD and a
9666     // MUL instruction. In this case Ptr is the actual BASE pointer.
9667     // (i64 add (i64 %array_ptr)
9668     //          (i64 mul (i64 %induction_var)
9669     //                   (i64 %element_size)))
9670     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9671       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9673     // Look at Base + Index + Offset cases.
9674     SDValue Base = Ptr->getOperand(0);
9675     SDValue IndexOffset = Ptr->getOperand(1);
9677     // Skip signextends.
9678     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9679       IndexOffset = IndexOffset->getOperand(0);
9680       IsIndexSignExt = true;
9681     }
9683     // Either the case of Base + Index (no offset) or something else.
9684     if (IndexOffset->getOpcode() != ISD::ADD)
9685       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9687     // Now we have the case of Base + Index + offset.
9688     SDValue Index = IndexOffset->getOperand(0);
9689     SDValue Offset = IndexOffset->getOperand(1);
9691     if (!isa<ConstantSDNode>(Offset))
9692       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9694     // Ignore signextends.
9695     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9696       Index = Index->getOperand(0);
9697       IsIndexSignExt = true;
9698     } else IsIndexSignExt = false;
9700     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9701     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9702   }
9703 };
9705 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9706 /// is located in a sequence of memory operations connected by a chain.
9707 struct MemOpLink {
9708   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9709     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9710   // Ptr to the mem node.
9711   LSBaseSDNode *MemNode;
9712   // Offset from the base ptr.
9713   int64_t OffsetFromBase;
9714   // What is the sequence number of this mem node.
9715   // Lowest mem operand in the DAG starts at zero.
9716   unsigned SequenceNum;
9717 };
9719 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9720   EVT MemVT = St->getMemoryVT();
9721   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9722   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9723     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9725   // Don't merge vectors into wider inputs.
9726   if (MemVT.isVector() || !MemVT.isSimple())
9727     return false;
9729   // Perform an early exit check. Do not bother looking at stored values that
9730   // are not constants or loads.
9731   SDValue StoredVal = St->getValue();
9732   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9733   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9734       !IsLoadSrc)
9735     return false;
9737   // Only look at ends of store sequences.
9738   SDValue Chain = SDValue(St, 0);
9739   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9740     return false;
9742   // This holds the base pointer, index, and the offset in bytes from the base
9743   // pointer.
9744   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9746   // We must have a base and an offset.
9747   if (!BasePtr.Base.getNode())
9748     return false;
9750   // Do not handle stores to undef base pointers.
9751   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9752     return false;
9754   // Save the LoadSDNodes that we find in the chain.
9755   // We need to make sure that these nodes do not interfere with
9756   // any of the store nodes.
9757   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9759   // Save the StoreSDNodes that we find in the chain.
9760   SmallVector<MemOpLink, 8> StoreNodes;
9762   // Walk up the chain and look for nodes with offsets from the same
9763   // base pointer. Stop when reaching an instruction with a different kind
9764   // or instruction which has a different base pointer.
9765   unsigned Seq = 0;
9766   StoreSDNode *Index = St;
9767   while (Index) {
9768     // If the chain has more than one use, then we can't reorder the mem ops.
9769     if (Index != St && !SDValue(Index, 0)->hasOneUse())
9770       break;
9772     // Find the base pointer and offset for this memory node.
9773     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9775     // Check that the base pointer is the same as the original one.
9776     if (!Ptr.equalBaseIndex(BasePtr))
9777       break;
9779     // Check that the alignment is the same.
9780     if (Index->getAlignment() != St->getAlignment())
9781       break;
9783     // The memory operands must not be volatile.
9784     if (Index->isVolatile() || Index->isIndexed())
9785       break;
9787     // No truncation.
9788     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9789       if (St->isTruncatingStore())
9790         break;
9792     // The stored memory type must be the same.
9793     if (Index->getMemoryVT() != MemVT)
9794       break;
9796     // We do not allow unaligned stores because we want to prevent overriding
9797     // stores.
9798     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9799       break;
9801     // We found a potential memory operand to merge.
9802     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9804     // Find the next memory operand in the chain. If the next operand in the
9805     // chain is a store then move up and continue the scan with the next
9806     // memory operand. If the next operand is a load save it and use alias
9807     // information to check if it interferes with anything.
9808     SDNode *NextInChain = Index->getChain().getNode();
9809     while (1) {
9810       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9811         // We found a store node. Use it for the next iteration.
9812         Index = STn;
9813         break;
9814       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9815         if (Ldn->isVolatile()) {
9816           Index = nullptr;
9817           break;
9818         }
9820         // Save the load node for later. Continue the scan.
9821         AliasLoadNodes.push_back(Ldn);
9822         NextInChain = Ldn->getChain().getNode();
9823         continue;
9824       } else {
9825         Index = nullptr;
9826         break;
9827       }
9828     }
9829   }
9831   // Check if there is anything to merge.
9832   if (StoreNodes.size() < 2)
9833     return false;
9835   // Sort the memory operands according to their distance from the base pointer.
9836   std::sort(StoreNodes.begin(), StoreNodes.end(),
9837             [](MemOpLink LHS, MemOpLink RHS) {
9838     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9839            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9840             LHS.SequenceNum > RHS.SequenceNum);
9841   });
9843   // Scan the memory operations on the chain and find the first non-consecutive
9844   // store memory address.
9845   unsigned LastConsecutiveStore = 0;
9846   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9847   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9849     // Check that the addresses are consecutive starting from the second
9850     // element in the list of stores.
9851     if (i > 0) {
9852       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9853       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9854         break;
9855     }
9857     bool Alias = false;
9858     // Check if this store interferes with any of the loads that we found.
9859     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9860       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9861         Alias = true;
9862         break;
9863       }
9864     // We found a load that alias with this store. Stop the sequence.
9865     if (Alias)
9866       break;
9868     // Mark this node as useful.
9869     LastConsecutiveStore = i;
9870   }
9872   // The node with the lowest store address.
9873   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9875   // Store the constants into memory as one consecutive store.
9876   if (!IsLoadSrc) {
9877     unsigned LastLegalType = 0;
9878     unsigned LastLegalVectorType = 0;
9879     bool NonZero = false;
9880     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9881       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9882       SDValue StoredVal = St->getValue();
9884       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9885         NonZero |= !C->isNullValue();
9886       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9887         NonZero |= !C->getConstantFPValue()->isNullValue();
9888       } else {
9889         // Non-constant.
9890         break;
9891       }
9893       // Find a legal type for the constant store.
9894       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9895       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9896       if (TLI.isTypeLegal(StoreTy))
9897         LastLegalType = i+1;
9898       // Or check whether a truncstore is legal.
9899       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9900                TargetLowering::TypePromoteInteger) {
9901         EVT LegalizedStoredValueTy =
9902           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9903         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9904           LastLegalType = i+1;
9905       }
9907       // Find a legal type for the vector store.
9908       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9909       if (TLI.isTypeLegal(Ty))
9910         LastLegalVectorType = i + 1;
9911     }
9913     // We only use vectors if the constant is known to be zero and the
9914     // function is not marked with the noimplicitfloat attribute.
9915     if (NonZero || NoVectors)
9916       LastLegalVectorType = 0;
9918     // Check if we found a legal integer type to store.
9919     if (LastLegalType == 0 && LastLegalVectorType == 0)
9920       return false;
9922     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9923     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9925     // Make sure we have something to merge.
9926     if (NumElem < 2)
9927       return false;
9929     unsigned EarliestNodeUsed = 0;
9930     for (unsigned i=0; i < NumElem; ++i) {
9931       // Find a chain for the new wide-store operand. Notice that some
9932       // of the store nodes that we found may not be selected for inclusion
9933       // in the wide store. The chain we use needs to be the chain of the
9934       // earliest store node which is *used* and replaced by the wide store.
9935       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9936         EarliestNodeUsed = i;
9937     }
9939     // The earliest Node in the DAG.
9940     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9941     SDLoc DL(StoreNodes[0].MemNode);
9943     SDValue StoredVal;
9944     if (UseVector) {
9945       // Find a legal type for the vector store.
9946       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9947       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9948       StoredVal = DAG.getConstant(0, Ty);
9949     } else {
9950       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9951       APInt StoreInt(StoreBW, 0);
9953       // Construct a single integer constant which is made of the smaller
9954       // constant inputs.
9955       bool IsLE = TLI.isLittleEndian();
9956       for (unsigned i = 0; i < NumElem ; ++i) {
9957         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9958         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9959         SDValue Val = St->getValue();
9960         StoreInt<<=ElementSizeBytes*8;
9961         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9962           StoreInt|=C->getAPIntValue().zext(StoreBW);
9963         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9964           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9965         } else {
9966           llvm_unreachable("Invalid constant element type");
9967         }
9968       }
9970       // Create the new Load and Store operations.
9971       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9972       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9973     }
9975     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9976                                     FirstInChain->getBasePtr(),
9977                                     FirstInChain->getPointerInfo(),
9978                                     false, false,
9979                                     FirstInChain->getAlignment());
9981     // Replace the first store with the new store
9982     CombineTo(EarliestOp, NewStore);
9983     // Erase all other stores.
9984     for (unsigned i = 0; i < NumElem ; ++i) {
9985       if (StoreNodes[i].MemNode == EarliestOp)
9986         continue;
9987       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9988       // ReplaceAllUsesWith will replace all uses that existed when it was
9989       // called, but graph optimizations may cause new ones to appear. For
9990       // example, the case in pr14333 looks like
9991       //
9992       //  St's chain -> St -> another store -> X
9993       //
9994       // And the only difference from St to the other store is the chain.
9995       // When we change it's chain to be St's chain they become identical,
9996       // get CSEed and the net result is that X is now a use of St.
9997       // Since we know that St is redundant, just iterate.
9998       while (!St->use_empty())
9999         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10000       deleteAndRecombine(St);
10001     }
10003     return true;
10004   }
10006   // Below we handle the case of multiple consecutive stores that
10007   // come from multiple consecutive loads. We merge them into a single
10008   // wide load and a single wide store.
10010   // Look for load nodes which are used by the stored values.
10011   SmallVector<MemOpLink, 8> LoadNodes;
10013   // Find acceptable loads. Loads need to have the same chain (token factor),
10014   // must not be zext, volatile, indexed, and they must be consecutive.
10015   BaseIndexOffset LdBasePtr;
10016   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10017     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10018     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10019     if (!Ld) break;
10021     // Loads must only have one use.
10022     if (!Ld->hasNUsesOfValue(1, 0))
10023       break;
10025     // Check that the alignment is the same as the stores.
10026     if (Ld->getAlignment() != St->getAlignment())
10027       break;
10029     // The memory operands must not be volatile.
10030     if (Ld->isVolatile() || Ld->isIndexed())
10031       break;
10033     // We do not accept ext loads.
10034     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10035       break;
10037     // The stored memory type must be the same.
10038     if (Ld->getMemoryVT() != MemVT)
10039       break;
10041     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10042     // If this is not the first ptr that we check.
10043     if (LdBasePtr.Base.getNode()) {
10044       // The base ptr must be the same.
10045       if (!LdPtr.equalBaseIndex(LdBasePtr))
10046         break;
10047     } else {
10048       // Check that all other base pointers are the same as this one.
10049       LdBasePtr = LdPtr;
10050     }
10052     // We found a potential memory operand to merge.
10053     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10054   }
10056   if (LoadNodes.size() < 2)
10057     return false;
10059   // If we have load/store pair instructions and we only have two values,
10060   // don't bother.
10061   unsigned RequiredAlignment;
10062   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10063       St->getAlignment() >= RequiredAlignment)
10064     return false;
10066   // Scan the memory operations on the chain and find the first non-consecutive
10067   // load memory address. These variables hold the index in the store node
10068   // array.
10069   unsigned LastConsecutiveLoad = 0;
10070   // This variable refers to the size and not index in the array.
10071   unsigned LastLegalVectorType = 0;
10072   unsigned LastLegalIntegerType = 0;
10073   StartAddress = LoadNodes[0].OffsetFromBase;
10074   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10075   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10076     // All loads much share the same chain.
10077     if (LoadNodes[i].MemNode->getChain() != FirstChain)
10078       break;
10080     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10081     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10082       break;
10083     LastConsecutiveLoad = i;
10085     // Find a legal type for the vector store.
10086     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10087     if (TLI.isTypeLegal(StoreTy))
10088       LastLegalVectorType = i + 1;
10090     // Find a legal type for the integer store.
10091     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10092     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10093     if (TLI.isTypeLegal(StoreTy))
10094       LastLegalIntegerType = i + 1;
10095     // Or check whether a truncstore and extload is legal.
10096     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10097              TargetLowering::TypePromoteInteger) {
10098       EVT LegalizedStoredValueTy =
10099         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10100       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10101           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10102           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10103           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
10104         LastLegalIntegerType = i+1;
10105     }
10106   }
10108   // Only use vector types if the vector type is larger than the integer type.
10109   // If they are the same, use integers.
10110   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
10111   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10113   // We add +1 here because the LastXXX variables refer to location while
10114   // the NumElem refers to array/index size.
10115   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10116   NumElem = std::min(LastLegalType, NumElem);
10118   if (NumElem < 2)
10119     return false;
10121   // The earliest Node in the DAG.
10122   unsigned EarliestNodeUsed = 0;
10123   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10124   for (unsigned i=1; i<NumElem; ++i) {
10125     // Find a chain for the new wide-store operand. Notice that some
10126     // of the store nodes that we found may not be selected for inclusion
10127     // in the wide store. The chain we use needs to be the chain of the
10128     // earliest store node which is *used* and replaced by the wide store.
10129     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
10130       EarliestNodeUsed = i;
10131   }
10133   // Find if it is better to use vectors or integers to load and store
10134   // to memory.
10135   EVT JointMemOpVT;
10136   if (UseVectorTy) {
10137     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10138   } else {
10139     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10140     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10141   }
10143   SDLoc LoadDL(LoadNodes[0].MemNode);
10144   SDLoc StoreDL(StoreNodes[0].MemNode);
10146   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10147   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10148                                 FirstLoad->getChain(),
10149                                 FirstLoad->getBasePtr(),
10150                                 FirstLoad->getPointerInfo(),
10151                                 false, false, false,
10152                                 FirstLoad->getAlignment());
10154   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
10155                                   FirstInChain->getBasePtr(),
10156                                   FirstInChain->getPointerInfo(), false, false,
10157                                   FirstInChain->getAlignment());
10159   // Replace one of the loads with the new load.
10160   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10161   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10162                                 SDValue(NewLoad.getNode(), 1));
10164   // Remove the rest of the load chains.
10165   for (unsigned i = 1; i < NumElem ; ++i) {
10166     // Replace all chain users of the old load nodes with the chain of the new
10167     // load node.
10168     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
10169     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10170   }
10172   // Replace the first store with the new store.
10173   CombineTo(EarliestOp, NewStore);
10174   // Erase all other stores.
10175   for (unsigned i = 0; i < NumElem ; ++i) {
10176     // Remove all Store nodes.
10177     if (StoreNodes[i].MemNode == EarliestOp)
10178       continue;
10179     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10180     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
10181     deleteAndRecombine(St);
10182   }
10184   return true;
10187 SDValue DAGCombiner::visitSTORE(SDNode *N) {
10188   StoreSDNode *ST  = cast<StoreSDNode>(N);
10189   SDValue Chain = ST->getChain();
10190   SDValue Value = ST->getValue();
10191   SDValue Ptr   = ST->getBasePtr();
10193   // If this is a store of a bit convert, store the input value if the
10194   // resultant store does not need a higher alignment than the original.
10195   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
10196       ST->isUnindexed()) {
10197     unsigned OrigAlign = ST->getAlignment();
10198     EVT SVT = Value.getOperand(0).getValueType();
10199     unsigned Align = TLI.getDataLayout()->
10200       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
10201     if (Align <= OrigAlign &&
10202         ((!LegalOperations && !ST->isVolatile()) ||
10203          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
10204       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
10205                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
10206                           ST->isNonTemporal(), OrigAlign,
10207                           ST->getAAInfo());
10208   }
10210   // Turn 'store undef, Ptr' -> nothing.
10211   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10212     return Chain;
10214   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
10215   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
10216     // NOTE: If the original store is volatile, this transform must not increase
10217     // the number of stores.  For example, on x86-32 an f64 can be stored in one
10218     // processor operation but an i64 (which is not legal) requires two.  So the
10219     // transform should not be done in this case.
10220     if (Value.getOpcode() != ISD::TargetConstantFP) {
10221       SDValue Tmp;
10222       switch (CFP->getSimpleValueType(0).SimpleTy) {
10223       default: llvm_unreachable("Unknown FP type");
10224       case MVT::f16:    // We don't do this for these yet.
10225       case MVT::f80:
10226       case MVT::f128:
10227       case MVT::ppcf128:
10228         break;
10229       case MVT::f32:
10230         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
10231             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10232           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
10233                               bitcastToAPInt().getZExtValue(), MVT::i32);
10234           return DAG.getStore(Chain, SDLoc(N), Tmp,
10235                               Ptr, ST->getMemOperand());
10236         }
10237         break;
10238       case MVT::f64:
10239         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
10240              !ST->isVolatile()) ||
10241             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
10242           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
10243                                 getZExtValue(), MVT::i64);
10244           return DAG.getStore(Chain, SDLoc(N), Tmp,
10245                               Ptr, ST->getMemOperand());
10246         }
10248         if (!ST->isVolatile() &&
10249             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10250           // Many FP stores are not made apparent until after legalize, e.g. for
10251           // argument passing.  Since this is so common, custom legalize the
10252           // 64-bit integer store into two 32-bit stores.
10253           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
10254           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10255           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
10256           if (TLI.isBigEndian()) std::swap(Lo, Hi);
10258           unsigned Alignment = ST->getAlignment();
10259           bool isVolatile = ST->isVolatile();
10260           bool isNonTemporal = ST->isNonTemporal();
10261           AAMDNodes AAInfo = ST->getAAInfo();
10263           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
10264                                      Ptr, ST->getPointerInfo(),
10265                                      isVolatile, isNonTemporal,
10266                                      ST->getAlignment(), AAInfo);
10267           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
10268                             DAG.getConstant(4, Ptr.getValueType()));
10269           Alignment = MinAlign(Alignment, 4U);
10270           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
10271                                      Ptr, ST->getPointerInfo().getWithOffset(4),
10272                                      isVolatile, isNonTemporal,
10273                                      Alignment, AAInfo);
10274           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10275                              St0, St1);
10276         }
10278         break;
10279       }
10280     }
10281   }
10283   // Try to infer better alignment information than the store already has.
10284   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
10285     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10286       if (Align > ST->getAlignment())
10287         return DAG.getTruncStore(Chain, SDLoc(N), Value,
10288                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
10289                                  ST->isVolatile(), ST->isNonTemporal(), Align,
10290                                  ST->getAAInfo());
10291     }
10292   }
10294   // Try transforming a pair floating point load / store ops to integer
10295   // load / store ops.
10296   SDValue NewST = TransformFPLoadStorePair(N);
10297   if (NewST.getNode())
10298     return NewST;
10300   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10301                                                   : DAG.getSubtarget().useAA();
10302 #ifndef NDEBUG
10303   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10304       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10305     UseAA = false;
10306 #endif
10307   if (UseAA && ST->isUnindexed()) {
10308     // Walk up chain skipping non-aliasing memory nodes.
10309     SDValue BetterChain = FindBetterChain(N, Chain);
10311     // If there is a better chain.
10312     if (Chain != BetterChain) {
10313       SDValue ReplStore;
10315       // Replace the chain to avoid dependency.
10316       if (ST->isTruncatingStore()) {
10317         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
10318                                       ST->getMemoryVT(), ST->getMemOperand());
10319       } else {
10320         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
10321                                  ST->getMemOperand());
10322       }
10324       // Create token to keep both nodes around.
10325       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10326                                   MVT::Other, Chain, ReplStore);
10328       // Make sure the new and old chains are cleaned up.
10329       AddToWorklist(Token.getNode());
10331       // Don't add users to work list.
10332       return CombineTo(N, Token, false);
10333     }
10334   }
10336   // Try transforming N to an indexed store.
10337   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10338     return SDValue(N, 0);
10340   // FIXME: is there such a thing as a truncating indexed store?
10341   if (ST->isTruncatingStore() && ST->isUnindexed() &&
10342       Value.getValueType().isInteger()) {
10343     // See if we can simplify the input to this truncstore with knowledge that
10344     // only the low bits are being used.  For example:
10345     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
10346     SDValue Shorter =
10347       GetDemandedBits(Value,
10348                       APInt::getLowBitsSet(
10349                         Value.getValueType().getScalarType().getSizeInBits(),
10350                         ST->getMemoryVT().getScalarType().getSizeInBits()));
10351     AddToWorklist(Value.getNode());
10352     if (Shorter.getNode())
10353       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
10354                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
10356     // Otherwise, see if we can simplify the operation with
10357     // SimplifyDemandedBits, which only works if the value has a single use.
10358     if (SimplifyDemandedBits(Value,
10359                         APInt::getLowBitsSet(
10360                           Value.getValueType().getScalarType().getSizeInBits(),
10361                           ST->getMemoryVT().getScalarType().getSizeInBits())))
10362       return SDValue(N, 0);
10363   }
10365   // If this is a load followed by a store to the same location, then the store
10366   // is dead/noop.
10367   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
10368     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
10369         ST->isUnindexed() && !ST->isVolatile() &&
10370         // There can't be any side effects between the load and store, such as
10371         // a call or store.
10372         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
10373       // The store is dead, remove it.
10374       return Chain;
10375     }
10376   }
10378   // If this is a store followed by a store with the same value to the same
10379   // location, then the store is dead/noop.
10380   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
10381     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
10382         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
10383         ST1->isUnindexed() && !ST1->isVolatile()) {
10384       // The store is dead, remove it.
10385       return Chain;
10386     }
10387   }
10389   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
10390   // truncating store.  We can do this even if this is already a truncstore.
10391   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
10392       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
10393       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
10394                             ST->getMemoryVT())) {
10395     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
10396                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
10397   }
10399   // Only perform this optimization before the types are legal, because we
10400   // don't want to perform this optimization on every DAGCombine invocation.
10401   if (!LegalTypes) {
10402     bool EverChanged = false;
10404     do {
10405       // There can be multiple store sequences on the same chain.
10406       // Keep trying to merge store sequences until we are unable to do so
10407       // or until we merge the last store on the chain.
10408       bool Changed = MergeConsecutiveStores(ST);
10409       EverChanged |= Changed;
10410       if (!Changed) break;
10411     } while (ST->getOpcode() != ISD::DELETED_NODE);
10413     if (EverChanged)
10414       return SDValue(N, 0);
10415   }
10417   return ReduceLoadOpStoreWidth(N);
10420 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
10421   SDValue InVec = N->getOperand(0);
10422   SDValue InVal = N->getOperand(1);
10423   SDValue EltNo = N->getOperand(2);
10424   SDLoc dl(N);
10426   // If the inserted element is an UNDEF, just use the input vector.
10427   if (InVal.getOpcode() == ISD::UNDEF)
10428     return InVec;
10430   EVT VT = InVec.getValueType();
10432   // If we can't generate a legal BUILD_VECTOR, exit
10433   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10434     return SDValue();
10436   // Check that we know which element is being inserted
10437   if (!isa<ConstantSDNode>(EltNo))
10438     return SDValue();
10439   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10441   // Canonicalize insert_vector_elt dag nodes.
10442   // Example:
10443   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10444   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10445   //
10446   // Do this only if the child insert_vector node has one use; also
10447   // do this only if indices are both constants and Idx1 < Idx0.
10448   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10449       && isa<ConstantSDNode>(InVec.getOperand(2))) {
10450     unsigned OtherElt =
10451       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10452     if (Elt < OtherElt) {
10453       // Swap nodes.
10454       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10455                                   InVec.getOperand(0), InVal, EltNo);
10456       AddToWorklist(NewOp.getNode());
10457       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10458                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10459     }
10460   }
10462   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10463   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
10464   // vector elements.
10465   SmallVector<SDValue, 8> Ops;
10466   // Do not combine these two vectors if the output vector will not replace
10467   // the input vector.
10468   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
10469     Ops.append(InVec.getNode()->op_begin(),
10470                InVec.getNode()->op_end());
10471   } else if (InVec.getOpcode() == ISD::UNDEF) {
10472     unsigned NElts = VT.getVectorNumElements();
10473     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10474   } else {
10475     return SDValue();
10476   }
10478   // Insert the element
10479   if (Elt < Ops.size()) {
10480     // All the operands of BUILD_VECTOR must have the same type;
10481     // we enforce that here.
10482     EVT OpVT = Ops[0].getValueType();
10483     if (InVal.getValueType() != OpVT)
10484       InVal = OpVT.bitsGT(InVal.getValueType()) ?
10485                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10486                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10487     Ops[Elt] = InVal;
10488   }
10490   // Return the new vector
10491   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
10494 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10495     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10496   EVT ResultVT = EVE->getValueType(0);
10497   EVT VecEltVT = InVecVT.getVectorElementType();
10498   unsigned Align = OriginalLoad->getAlignment();
10499   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10500       VecEltVT.getTypeForEVT(*DAG.getContext()));
10502   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10503     return SDValue();
10505   Align = NewAlign;
10507   SDValue NewPtr = OriginalLoad->getBasePtr();
10508   SDValue Offset;
10509   EVT PtrType = NewPtr.getValueType();
10510   MachinePointerInfo MPI;
10511   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10512     int Elt = ConstEltNo->getZExtValue();
10513     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10514     if (TLI.isBigEndian())
10515       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10516     Offset = DAG.getConstant(PtrOff, PtrType);
10517     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10518   } else {
10519     Offset = DAG.getNode(
10520         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10521         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10522     if (TLI.isBigEndian())
10523       Offset = DAG.getNode(
10524           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10525           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10526     MPI = OriginalLoad->getPointerInfo();
10527   }
10528   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10530   // The replacement we need to do here is a little tricky: we need to
10531   // replace an extractelement of a load with a load.
10532   // Use ReplaceAllUsesOfValuesWith to do the replacement.
10533   // Note that this replacement assumes that the extractvalue is the only
10534   // use of the load; that's okay because we don't want to perform this
10535   // transformation in other cases anyway.
10536   SDValue Load;
10537   SDValue Chain;
10538   if (ResultVT.bitsGT(VecEltVT)) {
10539     // If the result type of vextract is wider than the load, then issue an
10540     // extending load instead.
10541     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
10542                                                   VecEltVT)
10543                                    ? ISD::ZEXTLOAD
10544                                    : ISD::EXTLOAD;
10545     Load = DAG.getExtLoad(
10546         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10547         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10548         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10549     Chain = Load.getValue(1);
10550   } else {
10551     Load = DAG.getLoad(
10552         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10553         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10554         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10555     Chain = Load.getValue(1);
10556     if (ResultVT.bitsLT(VecEltVT))
10557       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10558     else
10559       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10560   }
10561   WorklistRemover DeadNodes(*this);
10562   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10563   SDValue To[] = { Load, Chain };
10564   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10565   // Since we're explicitly calling ReplaceAllUses, add the new node to the
10566   // worklist explicitly as well.
10567   AddToWorklist(Load.getNode());
10568   AddUsersToWorklist(Load.getNode()); // Add users too
10569   // Make sure to revisit this node to clean it up; it will usually be dead.
10570   AddToWorklist(EVE);
10571   ++OpsNarrowed;
10572   return SDValue(EVE, 0);
10575 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10576   // (vextract (scalar_to_vector val, 0) -> val
10577   SDValue InVec = N->getOperand(0);
10578   EVT VT = InVec.getValueType();
10579   EVT NVT = N->getValueType(0);
10581   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10582     // Check if the result type doesn't match the inserted element type. A
10583     // SCALAR_TO_VECTOR may truncate the inserted element and the
10584     // EXTRACT_VECTOR_ELT may widen the extracted vector.
10585     SDValue InOp = InVec.getOperand(0);
10586     if (InOp.getValueType() != NVT) {
10587       assert(InOp.getValueType().isInteger() && NVT.isInteger());
10588       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10589     }
10590     return InOp;
10591   }
10593   SDValue EltNo = N->getOperand(1);
10594   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10596   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10597   // We only perform this optimization before the op legalization phase because
10598   // we may introduce new vector instructions which are not backed by TD
10599   // patterns. For example on AVX, extracting elements from a wide vector
10600   // without using extract_subvector. However, if we can find an underlying
10601   // scalar value, then we can always use that.
10602   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10603       && ConstEltNo) {
10604     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10605     int NumElem = VT.getVectorNumElements();
10606     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10607     // Find the new index to extract from.
10608     int OrigElt = SVOp->getMaskElt(Elt);
10610     // Extracting an undef index is undef.
10611     if (OrigElt == -1)
10612       return DAG.getUNDEF(NVT);
10614     // Select the right vector half to extract from.
10615     SDValue SVInVec;
10616     if (OrigElt < NumElem) {
10617       SVInVec = InVec->getOperand(0);
10618     } else {
10619       SVInVec = InVec->getOperand(1);
10620       OrigElt -= NumElem;
10621     }
10623     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10624       SDValue InOp = SVInVec.getOperand(OrigElt);
10625       if (InOp.getValueType() != NVT) {
10626         assert(InOp.getValueType().isInteger() && NVT.isInteger());
10627         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10628       }
10630       return InOp;
10631     }
10633     // FIXME: We should handle recursing on other vector shuffles and
10634     // scalar_to_vector here as well.
10636     if (!LegalOperations) {
10637       EVT IndexTy = TLI.getVectorIdxTy();
10638       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10639                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
10640     }
10641   }
10643   bool BCNumEltsChanged = false;
10644   EVT ExtVT = VT.getVectorElementType();
10645   EVT LVT = ExtVT;
10647   // If the result of load has to be truncated, then it's not necessarily
10648   // profitable.
10649   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10650     return SDValue();
10652   if (InVec.getOpcode() == ISD::BITCAST) {
10653     // Don't duplicate a load with other uses.
10654     if (!InVec.hasOneUse())
10655       return SDValue();
10657     EVT BCVT = InVec.getOperand(0).getValueType();
10658     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10659       return SDValue();
10660     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10661       BCNumEltsChanged = true;
10662     InVec = InVec.getOperand(0);
10663     ExtVT = BCVT.getVectorElementType();
10664   }
10666   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10667   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10668       ISD::isNormalLoad(InVec.getNode()) &&
10669       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10670     SDValue Index = N->getOperand(1);
10671     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10672       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10673                                                            OrigLoad);
10674   }
10676   // Perform only after legalization to ensure build_vector / vector_shuffle
10677   // optimizations have already been done.
10678   if (!LegalOperations) return SDValue();
10680   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10681   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10682   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10684   if (ConstEltNo) {
10685     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10687     LoadSDNode *LN0 = nullptr;
10688     const ShuffleVectorSDNode *SVN = nullptr;
10689     if (ISD::isNormalLoad(InVec.getNode())) {
10690       LN0 = cast<LoadSDNode>(InVec);
10691     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10692                InVec.getOperand(0).getValueType() == ExtVT &&
10693                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10694       // Don't duplicate a load with other uses.
10695       if (!InVec.hasOneUse())
10696         return SDValue();
10698       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10699     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10700       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10701       // =>
10702       // (load $addr+1*size)
10704       // Don't duplicate a load with other uses.
10705       if (!InVec.hasOneUse())
10706         return SDValue();
10708       // If the bit convert changed the number of elements, it is unsafe
10709       // to examine the mask.
10710       if (BCNumEltsChanged)
10711         return SDValue();
10713       // Select the input vector, guarding against out of range extract vector.
10714       unsigned NumElems = VT.getVectorNumElements();
10715       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10716       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10718       if (InVec.getOpcode() == ISD::BITCAST) {
10719         // Don't duplicate a load with other uses.
10720         if (!InVec.hasOneUse())
10721           return SDValue();
10723         InVec = InVec.getOperand(0);
10724       }
10725       if (ISD::isNormalLoad(InVec.getNode())) {
10726         LN0 = cast<LoadSDNode>(InVec);
10727         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10728         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10729       }
10730     }
10732     // Make sure we found a non-volatile load and the extractelement is
10733     // the only use.
10734     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10735       return SDValue();
10737     // If Idx was -1 above, Elt is going to be -1, so just return undef.
10738     if (Elt == -1)
10739       return DAG.getUNDEF(LVT);
10741     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10742   }
10744   return SDValue();
10747 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10748 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10749   // We perform this optimization post type-legalization because
10750   // the type-legalizer often scalarizes integer-promoted vectors.
10751   // Performing this optimization before may create bit-casts which
10752   // will be type-legalized to complex code sequences.
10753   // We perform this optimization only before the operation legalizer because we
10754   // may introduce illegal operations.
10755   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10756     return SDValue();
10758   unsigned NumInScalars = N->getNumOperands();
10759   SDLoc dl(N);
10760   EVT VT = N->getValueType(0);
10762   // Check to see if this is a BUILD_VECTOR of a bunch of values
10763   // which come from any_extend or zero_extend nodes. If so, we can create
10764   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10765   // optimizations. We do not handle sign-extend because we can't fill the sign
10766   // using shuffles.
10767   EVT SourceType = MVT::Other;
10768   bool AllAnyExt = true;
10770   for (unsigned i = 0; i != NumInScalars; ++i) {
10771     SDValue In = N->getOperand(i);
10772     // Ignore undef inputs.
10773     if (In.getOpcode() == ISD::UNDEF) continue;
10775     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10776     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10778     // Abort if the element is not an extension.
10779     if (!ZeroExt && !AnyExt) {
10780       SourceType = MVT::Other;
10781       break;
10782     }
10784     // The input is a ZeroExt or AnyExt. Check the original type.
10785     EVT InTy = In.getOperand(0).getValueType();
10787     // Check that all of the widened source types are the same.
10788     if (SourceType == MVT::Other)
10789       // First time.
10790       SourceType = InTy;
10791     else if (InTy != SourceType) {
10792       // Multiple income types. Abort.
10793       SourceType = MVT::Other;
10794       break;
10795     }
10797     // Check if all of the extends are ANY_EXTENDs.
10798     AllAnyExt &= AnyExt;
10799   }
10801   // In order to have valid types, all of the inputs must be extended from the
10802   // same source type and all of the inputs must be any or zero extend.
10803   // Scalar sizes must be a power of two.
10804   EVT OutScalarTy = VT.getScalarType();
10805   bool ValidTypes = SourceType != MVT::Other &&
10806                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10807                  isPowerOf2_32(SourceType.getSizeInBits());
10809   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10810   // turn into a single shuffle instruction.
10811   if (!ValidTypes)
10812     return SDValue();
10814   bool isLE = TLI.isLittleEndian();
10815   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10816   assert(ElemRatio > 1 && "Invalid element size ratio");
10817   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10818                                DAG.getConstant(0, SourceType);
10820   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10821   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10823   // Populate the new build_vector
10824   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10825     SDValue Cast = N->getOperand(i);
10826     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10827             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10828             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10829     SDValue In;
10830     if (Cast.getOpcode() == ISD::UNDEF)
10831       In = DAG.getUNDEF(SourceType);
10832     else
10833       In = Cast->getOperand(0);
10834     unsigned Index = isLE ? (i * ElemRatio) :
10835                             (i * ElemRatio + (ElemRatio - 1));
10837     assert(Index < Ops.size() && "Invalid index");
10838     Ops[Index] = In;
10839   }
10841   // The type of the new BUILD_VECTOR node.
10842   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10843   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10844          "Invalid vector size");
10845   // Check if the new vector type is legal.
10846   if (!isTypeLegal(VecVT)) return SDValue();
10848   // Make the new BUILD_VECTOR.
10849   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10851   // The new BUILD_VECTOR node has the potential to be further optimized.
10852   AddToWorklist(BV.getNode());
10853   // Bitcast to the desired type.
10854   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10857 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10858   EVT VT = N->getValueType(0);
10860   unsigned NumInScalars = N->getNumOperands();
10861   SDLoc dl(N);
10863   EVT SrcVT = MVT::Other;
10864   unsigned Opcode = ISD::DELETED_NODE;
10865   unsigned NumDefs = 0;
10867   for (unsigned i = 0; i != NumInScalars; ++i) {
10868     SDValue In = N->getOperand(i);
10869     unsigned Opc = In.getOpcode();
10871     if (Opc == ISD::UNDEF)
10872       continue;
10874     // If all scalar values are floats and converted from integers.
10875     if (Opcode == ISD::DELETED_NODE &&
10876         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10877       Opcode = Opc;
10878     }
10880     if (Opc != Opcode)
10881       return SDValue();
10883     EVT InVT = In.getOperand(0).getValueType();
10885     // If all scalar values are typed differently, bail out. It's chosen to
10886     // simplify BUILD_VECTOR of integer types.
10887     if (SrcVT == MVT::Other)
10888       SrcVT = InVT;
10889     if (SrcVT != InVT)
10890       return SDValue();
10891     NumDefs++;
10892   }
10894   // If the vector has just one element defined, it's not worth to fold it into
10895   // a vectorized one.
10896   if (NumDefs < 2)
10897     return SDValue();
10899   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10900          && "Should only handle conversion from integer to float.");
10901   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10903   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10905   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10906     return SDValue();
10908   SmallVector<SDValue, 8> Opnds;
10909   for (unsigned i = 0; i != NumInScalars; ++i) {
10910     SDValue In = N->getOperand(i);
10912     if (In.getOpcode() == ISD::UNDEF)
10913       Opnds.push_back(DAG.getUNDEF(SrcVT));
10914     else
10915       Opnds.push_back(In.getOperand(0));
10916   }
10917   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10918   AddToWorklist(BV.getNode());
10920   return DAG.getNode(Opcode, dl, VT, BV);
10923 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10924   unsigned NumInScalars = N->getNumOperands();
10925   SDLoc dl(N);
10926   EVT VT = N->getValueType(0);
10928   // A vector built entirely of undefs is undef.
10929   if (ISD::allOperandsUndef(N))
10930     return DAG.getUNDEF(VT);
10932   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10933   if (V.getNode())
10934     return V;
10936   V = reduceBuildVecConvertToConvertBuildVec(N);
10937   if (V.getNode())
10938     return V;
10940   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10941   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10942   // at most two distinct vectors, turn this into a shuffle node.
10944   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10945   if (!isTypeLegal(VT))
10946     return SDValue();
10948   // May only combine to shuffle after legalize if shuffle is legal.
10949   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
10950     return SDValue();
10952   SDValue VecIn1, VecIn2;
10953   bool UsesZeroVector = false;
10954   for (unsigned i = 0; i != NumInScalars; ++i) {
10955     SDValue Op = N->getOperand(i);
10956     // Ignore undef inputs.
10957     if (Op.getOpcode() == ISD::UNDEF) continue;
10959     // See if we can combine this build_vector into a blend with a zero vector.
10960     if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
10961         cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
10962         (Op.getOpcode() == ISD::ConstantFP &&
10963         cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
10964       UsesZeroVector = true;
10965       continue;
10966     }
10968     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10969     // constant index, bail out.
10970     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10971         !isa<ConstantSDNode>(Op.getOperand(1))) {
10972       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10973       break;
10974     }
10976     // We allow up to two distinct input vectors.
10977     SDValue ExtractedFromVec = Op.getOperand(0);
10978     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10979       continue;
10981     if (!VecIn1.getNode()) {
10982       VecIn1 = ExtractedFromVec;
10983     } else if (!VecIn2.getNode() && !UsesZeroVector) {
10984       VecIn2 = ExtractedFromVec;
10985     } else {
10986       // Too many inputs.
10987       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10988       break;
10989     }
10990   }
10992   // If everything is good, we can make a shuffle operation.
10993   if (VecIn1.getNode()) {
10994     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
10995     SmallVector<int, 8> Mask;
10996     for (unsigned i = 0; i != NumInScalars; ++i) {
10997       unsigned Opcode = N->getOperand(i).getOpcode();
10998       if (Opcode == ISD::UNDEF) {
10999         Mask.push_back(-1);
11000         continue;
11001       }
11003       // Operands can also be zero.
11004       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11005         assert(UsesZeroVector &&
11006                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11007                "Unexpected node found!");
11008         Mask.push_back(NumInScalars+i);
11009         continue;
11010       }
11012       // If extracting from the first vector, just use the index directly.
11013       SDValue Extract = N->getOperand(i);
11014       SDValue ExtVal = Extract.getOperand(1);
11015       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11016       if (Extract.getOperand(0) == VecIn1) {
11017         Mask.push_back(ExtIndex);
11018         continue;
11019       }
11021       // Otherwise, use InIdx + InputVecSize
11022       Mask.push_back(InNumElements + ExtIndex);
11023     }
11025     // Avoid introducing illegal shuffles with zero.
11026     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11027       return SDValue();
11029     // We can't generate a shuffle node with mismatched input and output types.
11030     // Attempt to transform a single input vector to the correct type.
11031     if ((VT != VecIn1.getValueType())) {
11032       // If the input vector type has a different base type to the output
11033       // vector type, bail out.
11034       EVT VTElemType = VT.getVectorElementType();
11035       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11036           (VecIn2.getNode() &&
11037            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11038         return SDValue();
11040       // If the input vector is too small, widen it.
11041       // We only support widening of vectors which are half the size of the
11042       // output registers. For example XMM->YMM widening on X86 with AVX.
11043       EVT VecInT = VecIn1.getValueType();
11044       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11045         // If we only have one small input, widen it by adding undef values.
11046         if (!VecIn2.getNode())
11047           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11048                                DAG.getUNDEF(VecIn1.getValueType()));
11049         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11050           // If we have two small inputs of the same type, try to concat them.
11051           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11052           VecIn2 = SDValue(nullptr, 0);
11053         } else
11054           return SDValue();
11055       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11056         // If the input vector is too large, try to split it.
11057         // We don't support having two input vectors that are too large.
11058         if (VecIn2.getNode())
11059           return SDValue();
11061         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11062           return SDValue();
11063         
11064         // Try to replace VecIn1 with two extract_subvectors
11065         // No need to update the masks, they should still be correct.
11066         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 
11067           DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy()));
11068         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11069           DAG.getConstant(0, TLI.getVectorIdxTy()));
11070         UsesZeroVector = false;
11071       } else
11072         return SDValue();
11073     }
11075     if (UsesZeroVector)
11076       VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
11077                                 DAG.getConstantFP(0.0, VT);
11078     else
11079       // If VecIn2 is unused then change it to undef.
11080       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11082     // Check that we were able to transform all incoming values to the same
11083     // type.
11084     if (VecIn2.getValueType() != VecIn1.getValueType() ||
11085         VecIn1.getValueType() != VT)
11086           return SDValue();
11088     // Return the new VECTOR_SHUFFLE node.
11089     SDValue Ops[2];
11090     Ops[0] = VecIn1;
11091     Ops[1] = VecIn2;
11092     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
11093   }
11095   return SDValue();
11098 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
11099   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11100   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
11101   // inputs come from at most two distinct vectors, turn this into a shuffle
11102   // node.
11104   // If we only have one input vector, we don't need to do any concatenation.
11105   if (N->getNumOperands() == 1)
11106     return N->getOperand(0);
11108   // Check if all of the operands are undefs.
11109   EVT VT = N->getValueType(0);
11110   if (ISD::allOperandsUndef(N))
11111     return DAG.getUNDEF(VT);
11113   // Optimize concat_vectors where one of the vectors is undef.
11114   if (N->getNumOperands() == 2 &&
11115       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
11116     SDValue In = N->getOperand(0);
11117     assert(In.getValueType().isVector() && "Must concat vectors");
11119     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11120     if (In->getOpcode() == ISD::BITCAST &&
11121         !In->getOperand(0)->getValueType(0).isVector()) {
11122       SDValue Scalar = In->getOperand(0);
11123       EVT SclTy = Scalar->getValueType(0);
11125       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
11126         return SDValue();
11128       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
11129                                  VT.getSizeInBits() / SclTy.getSizeInBits());
11130       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
11131         return SDValue();
11133       SDLoc dl = SDLoc(N);
11134       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
11135       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
11136     }
11137   }
11139   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
11140   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
11141   if (N->getNumOperands() == 2 &&
11142       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
11143       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
11144     EVT VT = N->getValueType(0);
11145     SDValue N0 = N->getOperand(0);
11146     SDValue N1 = N->getOperand(1);
11147     SmallVector<SDValue, 8> Opnds;
11148     unsigned BuildVecNumElts =  N0.getNumOperands();
11150     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
11151     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
11152     if (SclTy0.isFloatingPoint()) {
11153       for (unsigned i = 0; i != BuildVecNumElts; ++i)
11154         Opnds.push_back(N0.getOperand(i));
11155       for (unsigned i = 0; i != BuildVecNumElts; ++i)
11156         Opnds.push_back(N1.getOperand(i));
11157     } else {
11158       // If BUILD_VECTOR are from built from integer, they may have different
11159       // operand types. Get the smaller type and truncate all operands to it.
11160       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
11161       for (unsigned i = 0; i != BuildVecNumElts; ++i)
11162         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
11163                         N0.getOperand(i)));
11164       for (unsigned i = 0; i != BuildVecNumElts; ++i)
11165         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
11166                         N1.getOperand(i)));
11167     }
11169     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
11170   }
11172   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
11173   // nodes often generate nop CONCAT_VECTOR nodes.
11174   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
11175   // place the incoming vectors at the exact same location.
11176   SDValue SingleSource = SDValue();
11177   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
11179   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11180     SDValue Op = N->getOperand(i);
11182     if (Op.getOpcode() == ISD::UNDEF)
11183       continue;
11185     // Check if this is the identity extract:
11186     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
11187       return SDValue();
11189     // Find the single incoming vector for the extract_subvector.
11190     if (SingleSource.getNode()) {
11191       if (Op.getOperand(0) != SingleSource)
11192         return SDValue();
11193     } else {
11194       SingleSource = Op.getOperand(0);
11196       // Check the source type is the same as the type of the result.
11197       // If not, this concat may extend the vector, so we can not
11198       // optimize it away.
11199       if (SingleSource.getValueType() != N->getValueType(0))
11200         return SDValue();
11201     }
11203     unsigned IdentityIndex = i * PartNumElem;
11204     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11205     // The extract index must be constant.
11206     if (!CS)
11207       return SDValue();
11209     // Check that we are reading from the identity index.
11210     if (CS->getZExtValue() != IdentityIndex)
11211       return SDValue();
11212   }
11214   if (SingleSource.getNode())
11215     return SingleSource;
11217   return SDValue();
11220 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
11221   EVT NVT = N->getValueType(0);
11222   SDValue V = N->getOperand(0);
11224   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
11225     // Combine:
11226     //    (extract_subvec (concat V1, V2, ...), i)
11227     // Into:
11228     //    Vi if possible
11229     // Only operand 0 is checked as 'concat' assumes all inputs of the same
11230     // type.
11231     if (V->getOperand(0).getValueType() != NVT)
11232       return SDValue();
11233     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11234     unsigned NumElems = NVT.getVectorNumElements();
11235     assert((Idx % NumElems) == 0 &&
11236            "IDX in concat is not a multiple of the result vector length.");
11237     return V->getOperand(Idx / NumElems);
11238   }
11240   // Skip bitcasting
11241   if (V->getOpcode() == ISD::BITCAST)
11242     V = V.getOperand(0);
11244   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
11245     SDLoc dl(N);
11246     // Handle only simple case where vector being inserted and vector
11247     // being extracted are of same type, and are half size of larger vectors.
11248     EVT BigVT = V->getOperand(0).getValueType();
11249     EVT SmallVT = V->getOperand(1).getValueType();
11250     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
11251       return SDValue();
11253     // Only handle cases where both indexes are constants with the same type.
11254     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11255     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
11257     if (InsIdx && ExtIdx &&
11258         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
11259         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
11260       // Combine:
11261       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
11262       // Into:
11263       //    indices are equal or bit offsets are equal => V1
11264       //    otherwise => (extract_subvec V1, ExtIdx)
11265       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
11266           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
11267         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
11268       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
11269                          DAG.getNode(ISD::BITCAST, dl,
11270                                      N->getOperand(0).getValueType(),
11271                                      V->getOperand(0)), N->getOperand(1));
11272     }
11273   }
11275   return SDValue();
11278 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
11279                                                  SDValue V, SelectionDAG &DAG) {
11280   SDLoc DL(V);
11281   EVT VT = V.getValueType();
11283   switch (V.getOpcode()) {
11284   default:
11285     return V;
11287   case ISD::CONCAT_VECTORS: {
11288     EVT OpVT = V->getOperand(0).getValueType();
11289     int OpSize = OpVT.getVectorNumElements();
11290     SmallBitVector OpUsedElements(OpSize, false);
11291     bool FoundSimplification = false;
11292     SmallVector<SDValue, 4> NewOps;
11293     NewOps.reserve(V->getNumOperands());
11294     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
11295       SDValue Op = V->getOperand(i);
11296       bool OpUsed = false;
11297       for (int j = 0; j < OpSize; ++j)
11298         if (UsedElements[i * OpSize + j]) {
11299           OpUsedElements[j] = true;
11300           OpUsed = true;
11301         }
11302       NewOps.push_back(
11303           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
11304                  : DAG.getUNDEF(OpVT));
11305       FoundSimplification |= Op == NewOps.back();
11306       OpUsedElements.reset();
11307     }
11308     if (FoundSimplification)
11309       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
11310     return V;
11311   }
11313   case ISD::INSERT_SUBVECTOR: {
11314     SDValue BaseV = V->getOperand(0);
11315     SDValue SubV = V->getOperand(1);
11316     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
11317     if (!IdxN)
11318       return V;
11320     int SubSize = SubV.getValueType().getVectorNumElements();
11321     int Idx = IdxN->getZExtValue();
11322     bool SubVectorUsed = false;
11323     SmallBitVector SubUsedElements(SubSize, false);
11324     for (int i = 0; i < SubSize; ++i)
11325       if (UsedElements[i + Idx]) {
11326         SubVectorUsed = true;
11327         SubUsedElements[i] = true;
11328         UsedElements[i + Idx] = false;
11329       }
11331     // Now recurse on both the base and sub vectors.
11332     SDValue SimplifiedSubV =
11333         SubVectorUsed
11334             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
11335             : DAG.getUNDEF(SubV.getValueType());
11336     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
11337     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
11338       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
11339                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
11340     return V;
11341   }
11342   }
11345 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
11346                                        SDValue N1, SelectionDAG &DAG) {
11347   EVT VT = SVN->getValueType(0);
11348   int NumElts = VT.getVectorNumElements();
11349   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
11350   for (int M : SVN->getMask())
11351     if (M >= 0 && M < NumElts)
11352       N0UsedElements[M] = true;
11353     else if (M >= NumElts)
11354       N1UsedElements[M - NumElts] = true;
11356   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
11357   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
11358   if (S0 == N0 && S1 == N1)
11359     return SDValue();
11361   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
11364 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
11365 // or turn a shuffle of a single concat into simpler shuffle then concat.
11366 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
11367   EVT VT = N->getValueType(0);
11368   unsigned NumElts = VT.getVectorNumElements();
11370   SDValue N0 = N->getOperand(0);
11371   SDValue N1 = N->getOperand(1);
11372   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11374   SmallVector<SDValue, 4> Ops;
11375   EVT ConcatVT = N0.getOperand(0).getValueType();
11376   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
11377   unsigned NumConcats = NumElts / NumElemsPerConcat;
11379   // Special case: shuffle(concat(A,B)) can be more efficiently represented
11380   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
11381   // half vector elements.
11382   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
11383       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
11384                   SVN->getMask().end(), [](int i) { return i == -1; })) {
11385     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
11386                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
11387     N1 = DAG.getUNDEF(ConcatVT);
11388     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
11389   }
11391   // Look at every vector that's inserted. We're looking for exact
11392   // subvector-sized copies from a concatenated vector
11393   for (unsigned I = 0; I != NumConcats; ++I) {
11394     // Make sure we're dealing with a copy.
11395     unsigned Begin = I * NumElemsPerConcat;
11396     bool AllUndef = true, NoUndef = true;
11397     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
11398       if (SVN->getMaskElt(J) >= 0)
11399         AllUndef = false;
11400       else
11401         NoUndef = false;
11402     }
11404     if (NoUndef) {
11405       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
11406         return SDValue();
11408       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
11409         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
11410           return SDValue();
11412       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
11413       if (FirstElt < N0.getNumOperands())
11414         Ops.push_back(N0.getOperand(FirstElt));
11415       else
11416         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
11418     } else if (AllUndef) {
11419       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
11420     } else { // Mixed with general masks and undefs, can't do optimization.
11421       return SDValue();
11422     }
11423   }
11425   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
11428 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
11429   EVT VT = N->getValueType(0);
11430   unsigned NumElts = VT.getVectorNumElements();
11432   SDValue N0 = N->getOperand(0);
11433   SDValue N1 = N->getOperand(1);
11435   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
11437   // Canonicalize shuffle undef, undef -> undef
11438   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
11439     return DAG.getUNDEF(VT);
11441   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11443   // Canonicalize shuffle v, v -> v, undef
11444   if (N0 == N1) {
11445     SmallVector<int, 8> NewMask;
11446     for (unsigned i = 0; i != NumElts; ++i) {
11447       int Idx = SVN->getMaskElt(i);
11448       if (Idx >= (int)NumElts) Idx -= NumElts;
11449       NewMask.push_back(Idx);
11450     }
11451     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
11452                                 &NewMask[0]);
11453   }
11455   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
11456   if (N0.getOpcode() == ISD::UNDEF) {
11457     SmallVector<int, 8> NewMask;
11458     for (unsigned i = 0; i != NumElts; ++i) {
11459       int Idx = SVN->getMaskElt(i);
11460       if (Idx >= 0) {
11461         if (Idx >= (int)NumElts)
11462           Idx -= NumElts;
11463         else
11464           Idx = -1; // remove reference to lhs
11465       }
11466       NewMask.push_back(Idx);
11467     }
11468     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
11469                                 &NewMask[0]);
11470   }
11472   // Remove references to rhs if it is undef
11473   if (N1.getOpcode() == ISD::UNDEF) {
11474     bool Changed = false;
11475     SmallVector<int, 8> NewMask;
11476     for (unsigned i = 0; i != NumElts; ++i) {
11477       int Idx = SVN->getMaskElt(i);
11478       if (Idx >= (int)NumElts) {
11479         Idx = -1;
11480         Changed = true;
11481       }
11482       NewMask.push_back(Idx);
11483     }
11484     if (Changed)
11485       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
11486   }
11488   // If it is a splat, check if the argument vector is another splat or a
11489   // build_vector with all scalar elements the same.
11490   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
11491     SDNode *V = N0.getNode();
11493     // If this is a bit convert that changes the element type of the vector but
11494     // not the number of vector elements, look through it.  Be careful not to
11495     // look though conversions that change things like v4f32 to v2f64.
11496     if (V->getOpcode() == ISD::BITCAST) {
11497       SDValue ConvInput = V->getOperand(0);
11498       if (ConvInput.getValueType().isVector() &&
11499           ConvInput.getValueType().getVectorNumElements() == NumElts)
11500         V = ConvInput.getNode();
11501     }
11503     if (V->getOpcode() == ISD::BUILD_VECTOR) {
11504       assert(V->getNumOperands() == NumElts &&
11505              "BUILD_VECTOR has wrong number of operands");
11506       SDValue Base;
11507       bool AllSame = true;
11508       for (unsigned i = 0; i != NumElts; ++i) {
11509         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11510           Base = V->getOperand(i);
11511           break;
11512         }
11513       }
11514       // Splat of <u, u, u, u>, return <u, u, u, u>
11515       if (!Base.getNode())
11516         return N0;
11517       for (unsigned i = 0; i != NumElts; ++i) {
11518         if (V->getOperand(i) != Base) {
11519           AllSame = false;
11520           break;
11521         }
11522       }
11523       // Splat of <x, x, x, x>, return <x, x, x, x>
11524       if (AllSame)
11525         return N0;
11526     }
11527   }
11529   // There are various patterns used to build up a vector from smaller vectors,
11530   // subvectors, or elements. Scan chains of these and replace unused insertions
11531   // or components with undef.
11532   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11533     return S;
11535   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11536       Level < AfterLegalizeVectorOps &&
11537       (N1.getOpcode() == ISD::UNDEF ||
11538       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11539        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11540     SDValue V = partitionShuffleOfConcats(N, DAG);
11542     if (V.getNode())
11543       return V;
11544   }
11546   // Canonicalize shuffles according to rules:
11547   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
11548   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
11549   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
11550   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
11551       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11552       TLI.isTypeLegal(VT)) {
11553     // The incoming shuffle must be of the same type as the result of the
11554     // current shuffle.
11555     assert(N1->getOperand(0).getValueType() == VT &&
11556            "Shuffle types don't match");
11558     SDValue SV0 = N1->getOperand(0);
11559     SDValue SV1 = N1->getOperand(1);
11560     bool HasSameOp0 = N0 == SV0;
11561     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11562     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
11563       // Commute the operands of this shuffle so that next rule
11564       // will trigger.
11565       return DAG.getCommutedVectorShuffle(*SVN);
11566   }
11568   // Try to fold according to rules:
11569   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11570   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11571   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11572   // Don't try to fold shuffles with illegal type.
11573   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11574       TLI.isTypeLegal(VT)) {
11575     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11577     // The incoming shuffle must be of the same type as the result of the
11578     // current shuffle.
11579     assert(OtherSV->getOperand(0).getValueType() == VT &&
11580            "Shuffle types don't match");
11582     SDValue SV0, SV1;
11583     SmallVector<int, 4> Mask;
11584     // Compute the combined shuffle mask for a shuffle with SV0 as the first
11585     // operand, and SV1 as the second operand.
11586     for (unsigned i = 0; i != NumElts; ++i) {
11587       int Idx = SVN->getMaskElt(i);
11588       if (Idx < 0) {
11589         // Propagate Undef.
11590         Mask.push_back(Idx);
11591         continue;
11592       }
11594       SDValue CurrentVec;
11595       if (Idx < (int)NumElts) {
11596         // This shuffle index refers to the inner shuffle N0. Lookup the inner
11597         // shuffle mask to identify which vector is actually referenced.
11598         Idx = OtherSV->getMaskElt(Idx);
11599         if (Idx < 0) {
11600           // Propagate Undef.
11601           Mask.push_back(Idx);
11602           continue;
11603         }
11605         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
11606                                            : OtherSV->getOperand(1);
11607       } else {
11608         // This shuffle index references an element within N1.
11609         CurrentVec = N1;
11610       }
11612       // Simple case where 'CurrentVec' is UNDEF.
11613       if (CurrentVec.getOpcode() == ISD::UNDEF) {
11614         Mask.push_back(-1);
11615         continue;
11616       }
11618       // Canonicalize the shuffle index. We don't know yet if CurrentVec
11619       // will be the first or second operand of the combined shuffle.
11620       Idx = Idx % NumElts;
11621       if (!SV0.getNode() || SV0 == CurrentVec) {
11622         // Ok. CurrentVec is the left hand side.
11623         // Update the mask accordingly.
11624         SV0 = CurrentVec;
11625         Mask.push_back(Idx);
11626         continue;
11627       }
11629       // Bail out if we cannot convert the shuffle pair into a single shuffle.
11630       if (SV1.getNode() && SV1 != CurrentVec)
11631         return SDValue();
11633       // Ok. CurrentVec is the right hand side.
11634       // Update the mask accordingly.
11635       SV1 = CurrentVec;
11636       Mask.push_back(Idx + NumElts);
11637     }
11639     // Check if all indices in Mask are Undef. In case, propagate Undef.
11640     bool isUndefMask = true;
11641     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11642       isUndefMask &= Mask[i] < 0;
11644     if (isUndefMask)
11645       return DAG.getUNDEF(VT);
11647     if (!SV0.getNode())
11648       SV0 = DAG.getUNDEF(VT);
11649     if (!SV1.getNode())
11650       SV1 = DAG.getUNDEF(VT);
11652     // Avoid introducing shuffles with illegal mask.
11653     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
11654       // Compute the commuted shuffle mask and test again.
11655       for (unsigned i = 0; i != NumElts; ++i) {
11656         int idx = Mask[i];
11657         if (idx < 0)
11658           continue;
11659         else if (idx < (int)NumElts)
11660           Mask[i] = idx + NumElts;
11661         else
11662           Mask[i] = idx - NumElts;
11663       }
11665       if (!TLI.isShuffleMaskLegal(Mask, VT))
11666         return SDValue();
11668       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
11669       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
11670       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
11671       std::swap(SV0, SV1);
11672     }
11674     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11675     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11676     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11677     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
11678   }
11680   return SDValue();
11683 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11684   SDValue N0 = N->getOperand(0);
11685   SDValue N2 = N->getOperand(2);
11687   // If the input vector is a concatenation, and the insert replaces
11688   // one of the halves, we can optimize into a single concat_vectors.
11689   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11690       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11691     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11692     EVT VT = N->getValueType(0);
11694     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11695     // (concat_vectors Z, Y)
11696     if (InsIdx == 0)
11697       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11698                          N->getOperand(1), N0.getOperand(1));
11700     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11701     // (concat_vectors X, Z)
11702     if (InsIdx == VT.getVectorNumElements()/2)
11703       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11704                          N0.getOperand(0), N->getOperand(1));
11705   }
11707   return SDValue();
11710 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11711 /// with the destination vector and a zero vector.
11712 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11713 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
11714 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11715   EVT VT = N->getValueType(0);
11716   SDLoc dl(N);
11717   SDValue LHS = N->getOperand(0);
11718   SDValue RHS = N->getOperand(1);
11719   if (N->getOpcode() == ISD::AND) {
11720     if (RHS.getOpcode() == ISD::BITCAST)
11721       RHS = RHS.getOperand(0);
11722     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11723       SmallVector<int, 8> Indices;
11724       unsigned NumElts = RHS.getNumOperands();
11725       for (unsigned i = 0; i != NumElts; ++i) {
11726         SDValue Elt = RHS.getOperand(i);
11727         if (!isa<ConstantSDNode>(Elt))
11728           return SDValue();
11730         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11731           Indices.push_back(i);
11732         else if (cast<ConstantSDNode>(Elt)->isNullValue())
11733           Indices.push_back(NumElts+i);
11734         else
11735           return SDValue();
11736       }
11738       // Let's see if the target supports this vector_shuffle.
11739       EVT RVT = RHS.getValueType();
11740       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11741         return SDValue();
11743       // Return the new VECTOR_SHUFFLE node.
11744       EVT EltVT = RVT.getVectorElementType();
11745       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11746                                      DAG.getConstant(0, EltVT));
11747       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11748       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11749       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11750       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11751     }
11752   }
11754   return SDValue();
11757 /// Visit a binary vector operation, like ADD.
11758 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11759   assert(N->getValueType(0).isVector() &&
11760          "SimplifyVBinOp only works on vectors!");
11762   SDValue LHS = N->getOperand(0);
11763   SDValue RHS = N->getOperand(1);
11764   SDValue Shuffle = XformToShuffleWithZero(N);
11765   if (Shuffle.getNode()) return Shuffle;
11767   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11768   // this operation.
11769   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11770       RHS.getOpcode() == ISD::BUILD_VECTOR) {
11771     // Check if both vectors are constants. If not bail out.
11772     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11773           cast<BuildVectorSDNode>(RHS)->isConstant()))
11774       return SDValue();
11776     SmallVector<SDValue, 8> Ops;
11777     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11778       SDValue LHSOp = LHS.getOperand(i);
11779       SDValue RHSOp = RHS.getOperand(i);
11781       // Can't fold divide by zero.
11782       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11783           N->getOpcode() == ISD::FDIV) {
11784         if ((RHSOp.getOpcode() == ISD::Constant &&
11785              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11786             (RHSOp.getOpcode() == ISD::ConstantFP &&
11787              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11788           break;
11789       }
11791       EVT VT = LHSOp.getValueType();
11792       EVT RVT = RHSOp.getValueType();
11793       if (RVT != VT) {
11794         // Integer BUILD_VECTOR operands may have types larger than the element
11795         // size (e.g., when the element type is not legal).  Prior to type
11796         // legalization, the types may not match between the two BUILD_VECTORS.
11797         // Truncate one of the operands to make them match.
11798         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11799           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11800         } else {
11801           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11802           VT = RVT;
11803         }
11804       }
11805       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11806                                    LHSOp, RHSOp);
11807       if (FoldOp.getOpcode() != ISD::UNDEF &&
11808           FoldOp.getOpcode() != ISD::Constant &&
11809           FoldOp.getOpcode() != ISD::ConstantFP)
11810         break;
11811       Ops.push_back(FoldOp);
11812       AddToWorklist(FoldOp.getNode());
11813     }
11815     if (Ops.size() == LHS.getNumOperands())
11816       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11817   }
11819   // Type legalization might introduce new shuffles in the DAG.
11820   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11821   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
11822   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11823       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11824       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11825       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11826     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11827     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11829     if (SVN0->getMask().equals(SVN1->getMask())) {
11830       EVT VT = N->getValueType(0);
11831       SDValue UndefVector = LHS.getOperand(1);
11832       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11833                                      LHS.getOperand(0), RHS.getOperand(0));
11834       AddUsersToWorklist(N);
11835       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11836                                   &SVN0->getMask()[0]);
11837     }
11838   }
11840   return SDValue();
11843 /// Visit a binary vector operation, like FABS/FNEG.
11844 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11845   assert(N->getValueType(0).isVector() &&
11846          "SimplifyVUnaryOp only works on vectors!");
11848   SDValue N0 = N->getOperand(0);
11850   if (N0.getOpcode() != ISD::BUILD_VECTOR)
11851     return SDValue();
11853   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11854   SmallVector<SDValue, 8> Ops;
11855   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11856     SDValue Op = N0.getOperand(i);
11857     if (Op.getOpcode() != ISD::UNDEF &&
11858         Op.getOpcode() != ISD::ConstantFP)
11859       break;
11860     EVT EltVT = Op.getValueType();
11861     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11862     if (FoldOp.getOpcode() != ISD::UNDEF &&
11863         FoldOp.getOpcode() != ISD::ConstantFP)
11864       break;
11865     Ops.push_back(FoldOp);
11866     AddToWorklist(FoldOp.getNode());
11867   }
11869   if (Ops.size() != N0.getNumOperands())
11870     return SDValue();
11872   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11875 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11876                                     SDValue N1, SDValue N2){
11877   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11879   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11880                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11882   // If we got a simplified select_cc node back from SimplifySelectCC, then
11883   // break it down into a new SETCC node, and a new SELECT node, and then return
11884   // the SELECT node, since we were called with a SELECT node.
11885   if (SCC.getNode()) {
11886     // Check to see if we got a select_cc back (to turn into setcc/select).
11887     // Otherwise, just return whatever node we got back, like fabs.
11888     if (SCC.getOpcode() == ISD::SELECT_CC) {
11889       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11890                                   N0.getValueType(),
11891                                   SCC.getOperand(0), SCC.getOperand(1),
11892                                   SCC.getOperand(4));
11893       AddToWorklist(SETCC.getNode());
11894       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11895                            SCC.getOperand(2), SCC.getOperand(3));
11896     }
11898     return SCC;
11899   }
11900   return SDValue();
11903 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11904 /// being selected between, see if we can simplify the select.  Callers of this
11905 /// should assume that TheSelect is deleted if this returns true.  As such, they
11906 /// should return the appropriate thing (e.g. the node) back to the top-level of
11907 /// the DAG combiner loop to avoid it being looked at.
11908 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11909                                     SDValue RHS) {
11911   // Cannot simplify select with vector condition
11912   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11914   // If this is a select from two identical things, try to pull the operation
11915   // through the select.
11916   if (LHS.getOpcode() != RHS.getOpcode() ||
11917       !LHS.hasOneUse() || !RHS.hasOneUse())
11918     return false;
11920   // If this is a load and the token chain is identical, replace the select
11921   // of two loads with a load through a select of the address to load from.
11922   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11923   // constants have been dropped into the constant pool.
11924   if (LHS.getOpcode() == ISD::LOAD) {
11925     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11926     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11928     // Token chains must be identical.
11929     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11930         // Do not let this transformation reduce the number of volatile loads.
11931         LLD->isVolatile() || RLD->isVolatile() ||
11932         // If this is an EXTLOAD, the VT's must match.
11933         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11934         // If this is an EXTLOAD, the kind of extension must match.
11935         (LLD->getExtensionType() != RLD->getExtensionType() &&
11936          // The only exception is if one of the extensions is anyext.
11937          LLD->getExtensionType() != ISD::EXTLOAD &&
11938          RLD->getExtensionType() != ISD::EXTLOAD) ||
11939         // FIXME: this discards src value information.  This is
11940         // over-conservative. It would be beneficial to be able to remember
11941         // both potential memory locations.  Since we are discarding
11942         // src value info, don't do the transformation if the memory
11943         // locations are not in the default address space.
11944         LLD->getPointerInfo().getAddrSpace() != 0 ||
11945         RLD->getPointerInfo().getAddrSpace() != 0 ||
11946         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11947                                       LLD->getBasePtr().getValueType()))
11948       return false;
11950     // Check that the select condition doesn't reach either load.  If so,
11951     // folding this will induce a cycle into the DAG.  If not, this is safe to
11952     // xform, so create a select of the addresses.
11953     SDValue Addr;
11954     if (TheSelect->getOpcode() == ISD::SELECT) {
11955       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11956       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11957           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11958         return false;
11959       // The loads must not depend on one another.
11960       if (LLD->isPredecessorOf(RLD) ||
11961           RLD->isPredecessorOf(LLD))
11962         return false;
11963       Addr = DAG.getSelect(SDLoc(TheSelect),
11964                            LLD->getBasePtr().getValueType(),
11965                            TheSelect->getOperand(0), LLD->getBasePtr(),
11966                            RLD->getBasePtr());
11967     } else {  // Otherwise SELECT_CC
11968       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11969       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11971       if ((LLD->hasAnyUseOfValue(1) &&
11972            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11973           (RLD->hasAnyUseOfValue(1) &&
11974            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11975         return false;
11977       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11978                          LLD->getBasePtr().getValueType(),
11979                          TheSelect->getOperand(0),
11980                          TheSelect->getOperand(1),
11981                          LLD->getBasePtr(), RLD->getBasePtr(),
11982                          TheSelect->getOperand(4));
11983     }
11985     SDValue Load;
11986     // It is safe to replace the two loads if they have different alignments,
11987     // but the new load must be the minimum (most restrictive) alignment of the
11988     // inputs.
11989     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
11990     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11991     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11992       Load = DAG.getLoad(TheSelect->getValueType(0),
11993                          SDLoc(TheSelect),
11994                          // FIXME: Discards pointer and AA info.
11995                          LLD->getChain(), Addr, MachinePointerInfo(),
11996                          LLD->isVolatile(), LLD->isNonTemporal(),
11997                          isInvariant, Alignment);
11998     } else {
11999       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
12000                             RLD->getExtensionType() : LLD->getExtensionType(),
12001                             SDLoc(TheSelect),
12002                             TheSelect->getValueType(0),
12003                             // FIXME: Discards pointer and AA info.
12004                             LLD->getChain(), Addr, MachinePointerInfo(),
12005                             LLD->getMemoryVT(), LLD->isVolatile(),
12006                             LLD->isNonTemporal(), isInvariant, Alignment);
12007     }
12009     // Users of the select now use the result of the load.
12010     CombineTo(TheSelect, Load);
12012     // Users of the old loads now use the new load's chain.  We know the
12013     // old-load value is dead now.
12014     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
12015     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
12016     return true;
12017   }
12019   return false;
12022 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
12023 /// where 'cond' is the comparison specified by CC.
12024 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
12025                                       SDValue N2, SDValue N3,
12026                                       ISD::CondCode CC, bool NotExtCompare) {
12027   // (x ? y : y) -> y.
12028   if (N2 == N3) return N2;
12030   EVT VT = N2.getValueType();
12031   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
12032   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
12033   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
12035   // Determine if the condition we're dealing with is constant
12036   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
12037                               N0, N1, CC, DL, false);
12038   if (SCC.getNode()) AddToWorklist(SCC.getNode());
12039   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
12041   // fold select_cc true, x, y -> x
12042   if (SCCC && !SCCC->isNullValue())
12043     return N2;
12044   // fold select_cc false, x, y -> y
12045   if (SCCC && SCCC->isNullValue())
12046     return N3;
12048   // Check to see if we can simplify the select into an fabs node
12049   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
12050     // Allow either -0.0 or 0.0
12051     if (CFP->getValueAPF().isZero()) {
12052       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
12053       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
12054           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
12055           N2 == N3.getOperand(0))
12056         return DAG.getNode(ISD::FABS, DL, VT, N0);
12058       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
12059       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
12060           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
12061           N2.getOperand(0) == N3)
12062         return DAG.getNode(ISD::FABS, DL, VT, N3);
12063     }
12064   }
12066   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
12067   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
12068   // in it.  This is a win when the constant is not otherwise available because
12069   // it replaces two constant pool loads with one.  We only do this if the FP
12070   // type is known to be legal, because if it isn't, then we are before legalize
12071   // types an we want the other legalization to happen first (e.g. to avoid
12072   // messing with soft float) and if the ConstantFP is not legal, because if
12073   // it is legal, we may not need to store the FP constant in a constant pool.
12074   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
12075     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
12076       if (TLI.isTypeLegal(N2.getValueType()) &&
12077           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
12078                TargetLowering::Legal &&
12079            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
12080            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
12081           // If both constants have multiple uses, then we won't need to do an
12082           // extra load, they are likely around in registers for other users.
12083           (TV->hasOneUse() || FV->hasOneUse())) {
12084         Constant *Elts[] = {
12085           const_cast<ConstantFP*>(FV->getConstantFPValue()),
12086           const_cast<ConstantFP*>(TV->getConstantFPValue())
12087         };
12088         Type *FPTy = Elts[0]->getType();
12089         const DataLayout &TD = *TLI.getDataLayout();
12091         // Create a ConstantArray of the two constants.
12092         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
12093         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
12094                                             TD.getPrefTypeAlignment(FPTy));
12095         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12097         // Get the offsets to the 0 and 1 element of the array so that we can
12098         // select between them.
12099         SDValue Zero = DAG.getIntPtrConstant(0);
12100         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
12101         SDValue One = DAG.getIntPtrConstant(EltSize);
12103         SDValue Cond = DAG.getSetCC(DL,
12104                                     getSetCCResultType(N0.getValueType()),
12105                                     N0, N1, CC);
12106         AddToWorklist(Cond.getNode());
12107         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
12108                                           Cond, One, Zero);
12109         AddToWorklist(CstOffset.getNode());
12110         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
12111                             CstOffset);
12112         AddToWorklist(CPIdx.getNode());
12113         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
12114                            MachinePointerInfo::getConstantPool(), false,
12115                            false, false, Alignment);
12117       }
12118     }
12120   // Check to see if we can perform the "gzip trick", transforming
12121   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
12122   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
12123       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
12124        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
12125     EVT XType = N0.getValueType();
12126     EVT AType = N2.getValueType();
12127     if (XType.bitsGE(AType)) {
12128       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
12129       // single-bit constant.
12130       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
12131         unsigned ShCtV = N2C->getAPIntValue().logBase2();
12132         ShCtV = XType.getSizeInBits()-ShCtV-1;
12133         SDValue ShCt = DAG.getConstant(ShCtV,
12134                                        getShiftAmountTy(N0.getValueType()));
12135         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
12136                                     XType, N0, ShCt);
12137         AddToWorklist(Shift.getNode());
12139         if (XType.bitsGT(AType)) {
12140           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12141           AddToWorklist(Shift.getNode());
12142         }
12144         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12145       }
12147       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
12148                                   XType, N0,
12149                                   DAG.getConstant(XType.getSizeInBits()-1,
12150                                          getShiftAmountTy(N0.getValueType())));
12151       AddToWorklist(Shift.getNode());
12153       if (XType.bitsGT(AType)) {
12154         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12155         AddToWorklist(Shift.getNode());
12156       }
12158       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12159     }
12160   }
12162   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
12163   // where y is has a single bit set.
12164   // A plaintext description would be, we can turn the SELECT_CC into an AND
12165   // when the condition can be materialized as an all-ones register.  Any
12166   // single bit-test can be materialized as an all-ones register with
12167   // shift-left and shift-right-arith.
12168   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
12169       N0->getValueType(0) == VT &&
12170       N1C && N1C->isNullValue() &&
12171       N2C && N2C->isNullValue()) {
12172     SDValue AndLHS = N0->getOperand(0);
12173     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12174     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
12175       // Shift the tested bit over the sign bit.
12176       APInt AndMask = ConstAndRHS->getAPIntValue();
12177       SDValue ShlAmt =
12178         DAG.getConstant(AndMask.countLeadingZeros(),
12179                         getShiftAmountTy(AndLHS.getValueType()));
12180       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
12182       // Now arithmetic right shift it all the way over, so the result is either
12183       // all-ones, or zero.
12184       SDValue ShrAmt =
12185         DAG.getConstant(AndMask.getBitWidth()-1,
12186                         getShiftAmountTy(Shl.getValueType()));
12187       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
12189       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
12190     }
12191   }
12193   // fold select C, 16, 0 -> shl C, 4
12194   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
12195       TLI.getBooleanContents(N0.getValueType()) ==
12196           TargetLowering::ZeroOrOneBooleanContent) {
12198     // If the caller doesn't want us to simplify this into a zext of a compare,
12199     // don't do it.
12200     if (NotExtCompare && N2C->getAPIntValue() == 1)
12201       return SDValue();
12203     // Get a SetCC of the condition
12204     // NOTE: Don't create a SETCC if it's not legal on this target.
12205     if (!LegalOperations ||
12206         TLI.isOperationLegal(ISD::SETCC,
12207           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
12208       SDValue Temp, SCC;
12209       // cast from setcc result type to select result type
12210       if (LegalTypes) {
12211         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
12212                             N0, N1, CC);
12213         if (N2.getValueType().bitsLT(SCC.getValueType()))
12214           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
12215                                         N2.getValueType());
12216         else
12217           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12218                              N2.getValueType(), SCC);
12219       } else {
12220         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
12221         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12222                            N2.getValueType(), SCC);
12223       }
12225       AddToWorklist(SCC.getNode());
12226       AddToWorklist(Temp.getNode());
12228       if (N2C->getAPIntValue() == 1)
12229         return Temp;
12231       // shl setcc result by log2 n2c
12232       return DAG.getNode(
12233           ISD::SHL, DL, N2.getValueType(), Temp,
12234           DAG.getConstant(N2C->getAPIntValue().logBase2(),
12235                           getShiftAmountTy(Temp.getValueType())));
12236     }
12237   }
12239   // Check to see if this is the equivalent of setcc
12240   // FIXME: Turn all of these into setcc if setcc if setcc is legal
12241   // otherwise, go ahead with the folds.
12242   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
12243     EVT XType = N0.getValueType();
12244     if (!LegalOperations ||
12245         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
12246       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
12247       if (Res.getValueType() != VT)
12248         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
12249       return Res;
12250     }
12252     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
12253     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
12254         (!LegalOperations ||
12255          TLI.isOperationLegal(ISD::CTLZ, XType))) {
12256       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
12257       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
12258                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
12259                                        getShiftAmountTy(Ctlz.getValueType())));
12260     }
12261     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
12262     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
12263       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
12264                                   XType, DAG.getConstant(0, XType), N0);
12265       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
12266       return DAG.getNode(ISD::SRL, DL, XType,
12267                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
12268                          DAG.getConstant(XType.getSizeInBits()-1,
12269                                          getShiftAmountTy(XType)));
12270     }
12271     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
12272     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
12273       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
12274                                  DAG.getConstant(XType.getSizeInBits()-1,
12275                                          getShiftAmountTy(N0.getValueType())));
12276       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
12277     }
12278   }
12280   // Check to see if this is an integer abs.
12281   // select_cc setg[te] X,  0,  X, -X ->
12282   // select_cc setgt    X, -1,  X, -X ->
12283   // select_cc setl[te] X,  0, -X,  X ->
12284   // select_cc setlt    X,  1, -X,  X ->
12285   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
12286   if (N1C) {
12287     ConstantSDNode *SubC = nullptr;
12288     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
12289          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
12290         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
12291       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
12292     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
12293               (N1C->isOne() && CC == ISD::SETLT)) &&
12294              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
12295       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
12297     EVT XType = N0.getValueType();
12298     if (SubC && SubC->isNullValue() && XType.isInteger()) {
12299       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
12300                                   N0,
12301                                   DAG.getConstant(XType.getSizeInBits()-1,
12302                                          getShiftAmountTy(N0.getValueType())));
12303       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
12304                                 XType, N0, Shift);
12305       AddToWorklist(Shift.getNode());
12306       AddToWorklist(Add.getNode());
12307       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
12308     }
12309   }
12311   return SDValue();
12314 /// This is a stub for TargetLowering::SimplifySetCC.
12315 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
12316                                    SDValue N1, ISD::CondCode Cond,
12317                                    SDLoc DL, bool foldBooleans) {
12318   TargetLowering::DAGCombinerInfo
12319     DagCombineInfo(DAG, Level, false, this);
12320   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
12323 /// Given an ISD::SDIV node expressing a divide by constant, return
12324 /// a DAG expression to select that will generate the same value by multiplying
12325 /// by a magic number.
12326 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12327 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
12328   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12329   if (!C)
12330     return SDValue();
12332   // Avoid division by zero.
12333   if (!C->getAPIntValue())
12334     return SDValue();
12336   std::vector<SDNode*> Built;
12337   SDValue S =
12338       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12340   for (SDNode *N : Built)
12341     AddToWorklist(N);
12342   return S;
12345 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
12346 /// DAG expression that will generate the same value by right shifting.
12347 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
12348   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12349   if (!C)
12350     return SDValue();
12352   // Avoid division by zero.
12353   if (!C->getAPIntValue())
12354     return SDValue();
12356   std::vector<SDNode *> Built;
12357   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
12359   for (SDNode *N : Built)
12360     AddToWorklist(N);
12361   return S;
12364 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
12365 /// expression that will generate the same value by multiplying by a magic
12366 /// number.
12367 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12368 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
12369   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12370   if (!C)
12371     return SDValue();
12373   // Avoid division by zero.
12374   if (!C->getAPIntValue())
12375     return SDValue();
12377   std::vector<SDNode*> Built;
12378   SDValue S =
12379       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12381   for (SDNode *N : Built)
12382     AddToWorklist(N);
12383   return S;
12386 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
12387   if (Level >= AfterLegalizeDAG)
12388     return SDValue();
12390   // Expose the DAG combiner to the target combiner implementations.
12391   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12393   unsigned Iterations = 0;
12394   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
12395     if (Iterations) {
12396       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12397       // For the reciprocal, we need to find the zero of the function:
12398       //   F(X) = A X - 1 [which has a zero at X = 1/A]
12399       //     =>
12400       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
12401       //     does not require additional intermediate precision]
12402       EVT VT = Op.getValueType();
12403       SDLoc DL(Op);
12404       SDValue FPOne = DAG.getConstantFP(1.0, VT);
12406       AddToWorklist(Est.getNode());
12408       // Newton iterations: Est = Est + Est (1 - Arg * Est)
12409       for (unsigned i = 0; i < Iterations; ++i) {
12410         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
12411         AddToWorklist(NewEst.getNode());
12413         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
12414         AddToWorklist(NewEst.getNode());
12416         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12417         AddToWorklist(NewEst.getNode());
12419         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
12420         AddToWorklist(Est.getNode());
12421       }
12422     }
12423     return Est;
12424   }
12426   return SDValue();
12429 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12430 /// For the reciprocal sqrt, we need to find the zero of the function:
12431 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12432 ///     =>
12433 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12434 /// As a result, we precompute A/2 prior to the iteration loop.
12435 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
12436                                           unsigned Iterations) {
12437   EVT VT = Arg.getValueType();
12438   SDLoc DL(Arg);
12439   SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
12441   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12442   // this entire sequence requires only one FP constant.
12443   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12444   AddToWorklist(HalfArg.getNode());
12446   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12447   AddToWorklist(HalfArg.getNode());
12449   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12450   for (unsigned i = 0; i < Iterations; ++i) {
12451     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12452     AddToWorklist(NewEst.getNode());
12454     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12455     AddToWorklist(NewEst.getNode());
12457     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
12458     AddToWorklist(NewEst.getNode());
12460     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12461     AddToWorklist(Est.getNode());
12462   }
12463   return Est;
12466 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12467 /// For the reciprocal sqrt, we need to find the zero of the function:
12468 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12469 ///     =>
12470 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
12471 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
12472                                           unsigned Iterations) {
12473   EVT VT = Arg.getValueType();
12474   SDLoc DL(Arg);
12475   SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
12476   SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
12478   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
12479   for (unsigned i = 0; i < Iterations; ++i) {
12480     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
12481     AddToWorklist(HalfEst.getNode());
12483     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12484     AddToWorklist(Est.getNode());
12486     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
12487     AddToWorklist(Est.getNode());
12489     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
12490     AddToWorklist(Est.getNode());
12492     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
12493     AddToWorklist(Est.getNode());
12494   }
12495   return Est;
12498 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
12499   if (Level >= AfterLegalizeDAG)
12500     return SDValue();
12502   // Expose the DAG combiner to the target combiner implementations.
12503   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12504   unsigned Iterations = 0;
12505   bool UseOneConstNR = false;
12506   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
12507     AddToWorklist(Est.getNode());
12508     if (Iterations) {
12509       Est = UseOneConstNR ?
12510         BuildRsqrtNROneConst(Op, Est, Iterations) :
12511         BuildRsqrtNRTwoConst(Op, Est, Iterations);
12512     }
12513     return Est;
12514   }
12516   return SDValue();
12519 /// Return true if base is a frame index, which is known not to alias with
12520 /// anything but itself.  Provides base object and offset as results.
12521 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
12522                            const GlobalValue *&GV, const void *&CV) {
12523   // Assume it is a primitive operation.
12524   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
12526   // If it's an adding a simple constant then integrate the offset.
12527   if (Base.getOpcode() == ISD::ADD) {
12528     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
12529       Base = Base.getOperand(0);
12530       Offset += C->getZExtValue();
12531     }
12532   }
12534   // Return the underlying GlobalValue, and update the Offset.  Return false
12535   // for GlobalAddressSDNode since the same GlobalAddress may be represented
12536   // by multiple nodes with different offsets.
12537   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
12538     GV = G->getGlobal();
12539     Offset += G->getOffset();
12540     return false;
12541   }
12543   // Return the underlying Constant value, and update the Offset.  Return false
12544   // for ConstantSDNodes since the same constant pool entry may be represented
12545   // by multiple nodes with different offsets.
12546   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
12547     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
12548                                          : (const void *)C->getConstVal();
12549     Offset += C->getOffset();
12550     return false;
12551   }
12552   // If it's any of the following then it can't alias with anything but itself.
12553   return isa<FrameIndexSDNode>(Base);
12556 /// Return true if there is any possibility that the two addresses overlap.
12557 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
12558   // If they are the same then they must be aliases.
12559   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
12561   // If they are both volatile then they cannot be reordered.
12562   if (Op0->isVolatile() && Op1->isVolatile()) return true;
12564   // Gather base node and offset information.
12565   SDValue Base1, Base2;
12566   int64_t Offset1, Offset2;
12567   const GlobalValue *GV1, *GV2;
12568   const void *CV1, *CV2;
12569   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
12570                                       Base1, Offset1, GV1, CV1);
12571   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
12572                                       Base2, Offset2, GV2, CV2);
12574   // If they have a same base address then check to see if they overlap.
12575   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
12576     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12577              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12579   // It is possible for different frame indices to alias each other, mostly
12580   // when tail call optimization reuses return address slots for arguments.
12581   // To catch this case, look up the actual index of frame indices to compute
12582   // the real alias relationship.
12583   if (isFrameIndex1 && isFrameIndex2) {
12584     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12585     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
12586     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
12587     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12588              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12589   }
12591   // Otherwise, if we know what the bases are, and they aren't identical, then
12592   // we know they cannot alias.
12593   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
12594     return false;
12596   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
12597   // compared to the size and offset of the access, we may be able to prove they
12598   // do not alias.  This check is conservative for now to catch cases created by
12599   // splitting vector types.
12600   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
12601       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
12602       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
12603        Op1->getMemoryVT().getSizeInBits() >> 3) &&
12604       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
12605     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
12606     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
12608     // There is no overlap between these relatively aligned accesses of similar
12609     // size, return no alias.
12610     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
12611         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
12612       return false;
12613   }
12615   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
12616                    ? CombinerGlobalAA
12617                    : DAG.getSubtarget().useAA();
12618 #ifndef NDEBUG
12619   if (CombinerAAOnlyFunc.getNumOccurrences() &&
12620       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12621     UseAA = false;
12622 #endif
12623   if (UseAA &&
12624       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
12625     // Use alias analysis information.
12626     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
12627                                  Op1->getSrcValueOffset());
12628     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
12629         Op0->getSrcValueOffset() - MinOffset;
12630     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
12631         Op1->getSrcValueOffset() - MinOffset;
12632     AliasAnalysis::AliasResult AAResult =
12633         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
12634                                          Overlap1,
12635                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
12636                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
12637                                          Overlap2,
12638                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
12639     if (AAResult == AliasAnalysis::NoAlias)
12640       return false;
12641   }
12643   // Otherwise we have to assume they alias.
12644   return true;
12647 /// Walk up chain skipping non-aliasing memory nodes,
12648 /// looking for aliasing nodes and adding them to the Aliases vector.
12649 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
12650                                    SmallVectorImpl<SDValue> &Aliases) {
12651   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
12652   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
12654   // Get alias information for node.
12655   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
12657   // Starting off.
12658   Chains.push_back(OriginalChain);
12659   unsigned Depth = 0;
12661   // Look at each chain and determine if it is an alias.  If so, add it to the
12662   // aliases list.  If not, then continue up the chain looking for the next
12663   // candidate.
12664   while (!Chains.empty()) {
12665     SDValue Chain = Chains.back();
12666     Chains.pop_back();
12668     // For TokenFactor nodes, look at each operand and only continue up the
12669     // chain until we find two aliases.  If we've seen two aliases, assume we'll
12670     // find more and revert to original chain since the xform is unlikely to be
12671     // profitable.
12672     //
12673     // FIXME: The depth check could be made to return the last non-aliasing
12674     // chain we found before we hit a tokenfactor rather than the original
12675     // chain.
12676     if (Depth > 6 || Aliases.size() == 2) {
12677       Aliases.clear();
12678       Aliases.push_back(OriginalChain);
12679       return;
12680     }
12682     // Don't bother if we've been before.
12683     if (!Visited.insert(Chain.getNode()).second)
12684       continue;
12686     switch (Chain.getOpcode()) {
12687     case ISD::EntryToken:
12688       // Entry token is ideal chain operand, but handled in FindBetterChain.
12689       break;
12691     case ISD::LOAD:
12692     case ISD::STORE: {
12693       // Get alias information for Chain.
12694       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
12695           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
12697       // If chain is alias then stop here.
12698       if (!(IsLoad && IsOpLoad) &&
12699           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
12700         Aliases.push_back(Chain);
12701       } else {
12702         // Look further up the chain.
12703         Chains.push_back(Chain.getOperand(0));
12704         ++Depth;
12705       }
12706       break;
12707     }
12709     case ISD::TokenFactor:
12710       // We have to check each of the operands of the token factor for "small"
12711       // token factors, so we queue them up.  Adding the operands to the queue
12712       // (stack) in reverse order maintains the original order and increases the
12713       // likelihood that getNode will find a matching token factor (CSE.)
12714       if (Chain.getNumOperands() > 16) {
12715         Aliases.push_back(Chain);
12716         break;
12717       }
12718       for (unsigned n = Chain.getNumOperands(); n;)
12719         Chains.push_back(Chain.getOperand(--n));
12720       ++Depth;
12721       break;
12723     default:
12724       // For all other instructions we will just have to take what we can get.
12725       Aliases.push_back(Chain);
12726       break;
12727     }
12728   }
12730   // We need to be careful here to also search for aliases through the
12731   // value operand of a store, etc. Consider the following situation:
12732   //   Token1 = ...
12733   //   L1 = load Token1, %52
12734   //   S1 = store Token1, L1, %51
12735   //   L2 = load Token1, %52+8
12736   //   S2 = store Token1, L2, %51+8
12737   //   Token2 = Token(S1, S2)
12738   //   L3 = load Token2, %53
12739   //   S3 = store Token2, L3, %52
12740   //   L4 = load Token2, %53+8
12741   //   S4 = store Token2, L4, %52+8
12742   // If we search for aliases of S3 (which loads address %52), and we look
12743   // only through the chain, then we'll miss the trivial dependence on L1
12744   // (which also loads from %52). We then might change all loads and
12745   // stores to use Token1 as their chain operand, which could result in
12746   // copying %53 into %52 before copying %52 into %51 (which should
12747   // happen first).
12748   //
12749   // The problem is, however, that searching for such data dependencies
12750   // can become expensive, and the cost is not directly related to the
12751   // chain depth. Instead, we'll rule out such configurations here by
12752   // insisting that we've visited all chain users (except for users
12753   // of the original chain, which is not necessary). When doing this,
12754   // we need to look through nodes we don't care about (otherwise, things
12755   // like register copies will interfere with trivial cases).
12757   SmallVector<const SDNode *, 16> Worklist;
12758   for (const SDNode *N : Visited)
12759     if (N != OriginalChain.getNode())
12760       Worklist.push_back(N);
12762   while (!Worklist.empty()) {
12763     const SDNode *M = Worklist.pop_back_val();
12765     // We have already visited M, and want to make sure we've visited any uses
12766     // of M that we care about. For uses that we've not visisted, and don't
12767     // care about, queue them to the worklist.
12769     for (SDNode::use_iterator UI = M->use_begin(),
12770          UIE = M->use_end(); UI != UIE; ++UI)
12771       if (UI.getUse().getValueType() == MVT::Other &&
12772           Visited.insert(*UI).second) {
12773         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
12774           // We've not visited this use, and we care about it (it could have an
12775           // ordering dependency with the original node).
12776           Aliases.clear();
12777           Aliases.push_back(OriginalChain);
12778           return;
12779         }
12781         // We've not visited this use, but we don't care about it. Mark it as
12782         // visited and enqueue it to the worklist.
12783         Worklist.push_back(*UI);
12784       }
12785   }
12788 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
12789 /// (aliasing node.)
12790 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
12791   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
12793   // Accumulate all the aliases to this node.
12794   GatherAllAliases(N, OldChain, Aliases);
12796   // If no operands then chain to entry token.
12797   if (Aliases.size() == 0)
12798     return DAG.getEntryNode();
12800   // If a single operand then chain to it.  We don't need to revisit it.
12801   if (Aliases.size() == 1)
12802     return Aliases[0];
12804   // Construct a custom tailored token factor.
12805   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
12808 /// This is the entry point for the file.
12809 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
12810                            CodeGenOpt::Level OptLevel) {
12811   /// This is the main entry point to this class.
12812   DAGCombiner(*this, AA, OptLevel).Run(Level);