]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - opencl/llvm.git/blob - lib/CodeGen/SelectionDAG/DAGCombiner.cpp
Fixed a bug in type legalizer for masked load/store intrinsics.
[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->getValue();
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, LoMemVT, MMO,
4900                             MST->isTruncatingStore());
4902     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4903     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4904                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
4906     MMO = DAG.getMachineFunction().
4907       getMachineMemOperand(MST->getPointerInfo(), 
4908                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
4909                            SecondHalfAlignment, MST->getAAInfo(),
4910                            MST->getRanges());
4912     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
4913                             MST->isTruncatingStore());
4915     AddToWorklist(Lo.getNode());
4916     AddToWorklist(Hi.getNode());
4918     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
4919   }
4920   return SDValue();
4923 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
4925   if (Level >= AfterLegalizeTypes)
4926     return SDValue();
4928   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
4929   SDValue Mask = MLD->getMask();
4930   SDLoc DL(N);
4932   // If the MLOAD result requires splitting and the mask is provided by a
4933   // SETCC, then split both nodes and its operands before legalization. This
4934   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4935   // and enables future optimizations (e.g. min/max pattern matching on X86).
4937   if (Mask.getOpcode() == ISD::SETCC) {
4938     EVT VT = N->getValueType(0);
4940     // Check if any splitting is required.
4941     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4942         TargetLowering::TypeSplitVector)
4943       return SDValue();
4945     SDValue MaskLo, MaskHi, Lo, Hi;
4946     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4948     SDValue Src0 = MLD->getSrc0();
4949     SDValue Src0Lo, Src0Hi;
4950     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
4952     EVT LoVT, HiVT;
4953     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
4955     SDValue Chain = MLD->getChain();
4956     SDValue Ptr   = MLD->getBasePtr();
4957     EVT MemoryVT = MLD->getMemoryVT();
4958     unsigned Alignment = MLD->getOriginalAlignment();
4960     // if Alignment is equal to the vector size,
4961     // take the half of it for the second part
4962     unsigned SecondHalfAlignment =
4963       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
4964          Alignment/2 : Alignment;
4966     EVT LoMemVT, HiMemVT;
4967     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4969     MachineMemOperand *MMO = DAG.getMachineFunction().
4970     getMachineMemOperand(MLD->getPointerInfo(), 
4971                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
4972                          Alignment, MLD->getAAInfo(), MLD->getRanges());
4974     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
4975                            ISD::NON_EXTLOAD);
4977     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4978     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4979                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
4981     MMO = DAG.getMachineFunction().
4982     getMachineMemOperand(MLD->getPointerInfo(), 
4983                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
4984                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
4986     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
4987                            ISD::NON_EXTLOAD);
4989     AddToWorklist(Lo.getNode());
4990     AddToWorklist(Hi.getNode());
4992     // Build a factor node to remember that this load is independent of the
4993     // other one.
4994     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
4995                         Hi.getValue(1));
4997     // Legalized the chain result - switch anything that used the old chain to
4998     // use the new one.
4999     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5001     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5003     SDValue RetOps[] = { LoadRes, Chain };
5004     return DAG.getMergeValues(RetOps, DL);
5005   }
5006   return SDValue();
5009 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5010   SDValue N0 = N->getOperand(0);
5011   SDValue N1 = N->getOperand(1);
5012   SDValue N2 = N->getOperand(2);
5013   SDLoc DL(N);
5015   // Canonicalize integer abs.
5016   // vselect (setg[te] X,  0),  X, -X ->
5017   // vselect (setgt    X, -1),  X, -X ->
5018   // vselect (setl[te] X,  0), -X,  X ->
5019   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5020   if (N0.getOpcode() == ISD::SETCC) {
5021     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5022     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5023     bool isAbs = false;
5024     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5026     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5027          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5028         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5029       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5030     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5031              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5032       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5034     if (isAbs) {
5035       EVT VT = LHS.getValueType();
5036       SDValue Shift = DAG.getNode(
5037           ISD::SRA, DL, VT, LHS,
5038           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
5039       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5040       AddToWorklist(Shift.getNode());
5041       AddToWorklist(Add.getNode());
5042       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5043     }
5044   }
5046   // If the VSELECT result requires splitting and the mask is provided by a
5047   // SETCC, then split both nodes and its operands before legalization. This
5048   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5049   // and enables future optimizations (e.g. min/max pattern matching on X86).
5050   if (N0.getOpcode() == ISD::SETCC) {
5051     EVT VT = N->getValueType(0);
5053     // Check if any splitting is required.
5054     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5055         TargetLowering::TypeSplitVector)
5056       return SDValue();
5058     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5059     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5060     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5061     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5063     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5064     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5066     // Add the new VSELECT nodes to the work list in case they need to be split
5067     // again.
5068     AddToWorklist(Lo.getNode());
5069     AddToWorklist(Hi.getNode());
5071     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5072   }
5074   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5075   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5076     return N1;
5077   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5078   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5079     return N2;
5081   // The ConvertSelectToConcatVector function is assuming both the above
5082   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5083   // and addressed.
5084   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5085       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5086       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5087     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5088     if (CV.getNode())
5089       return CV;
5090   }
5092   return SDValue();
5095 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5096   SDValue N0 = N->getOperand(0);
5097   SDValue N1 = N->getOperand(1);
5098   SDValue N2 = N->getOperand(2);
5099   SDValue N3 = N->getOperand(3);
5100   SDValue N4 = N->getOperand(4);
5101   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5103   // fold select_cc lhs, rhs, x, x, cc -> x
5104   if (N2 == N3)
5105     return N2;
5107   // Determine if the condition we're dealing with is constant
5108   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5109                               N0, N1, CC, SDLoc(N), false);
5110   if (SCC.getNode()) {
5111     AddToWorklist(SCC.getNode());
5113     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5114       if (!SCCC->isNullValue())
5115         return N2;    // cond always true -> true val
5116       else
5117         return N3;    // cond always false -> false val
5118     } else if (SCC->getOpcode() == ISD::UNDEF) {
5119       // When the condition is UNDEF, just return the first operand. This is
5120       // coherent the DAG creation, no setcc node is created in this case
5121       return N2;
5122     } else if (SCC.getOpcode() == ISD::SETCC) {
5123       // Fold to a simpler select_cc
5124       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5125                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5126                          SCC.getOperand(2));
5127     }
5128   }
5130   // If we can fold this based on the true/false value, do so.
5131   if (SimplifySelectOps(N, N2, N3))
5132     return SDValue(N, 0);  // Don't revisit N.
5134   // fold select_cc into other things, such as min/max/abs
5135   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5138 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5139   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5140                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5141                        SDLoc(N));
5144 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5145 // dag node into a ConstantSDNode or a build_vector of constants.
5146 // This function is called by the DAGCombiner when visiting sext/zext/aext
5147 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5148 // Vector extends are not folded if operations are legal; this is to
5149 // avoid introducing illegal build_vector dag nodes.
5150 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5151                                          SelectionDAG &DAG, bool LegalTypes,
5152                                          bool LegalOperations) {
5153   unsigned Opcode = N->getOpcode();
5154   SDValue N0 = N->getOperand(0);
5155   EVT VT = N->getValueType(0);
5157   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5158          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5160   // fold (sext c1) -> c1
5161   // fold (zext c1) -> c1
5162   // fold (aext c1) -> c1
5163   if (isa<ConstantSDNode>(N0))
5164     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5166   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5167   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5168   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5169   EVT SVT = VT.getScalarType();
5170   if (!(VT.isVector() &&
5171       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5172       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5173     return nullptr;
5175   // We can fold this node into a build_vector.
5176   unsigned VTBits = SVT.getSizeInBits();
5177   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5178   unsigned ShAmt = VTBits - EVTBits;
5179   SmallVector<SDValue, 8> Elts;
5180   unsigned NumElts = N0->getNumOperands();
5181   SDLoc DL(N);
5183   for (unsigned i=0; i != NumElts; ++i) {
5184     SDValue Op = N0->getOperand(i);
5185     if (Op->getOpcode() == ISD::UNDEF) {
5186       Elts.push_back(DAG.getUNDEF(SVT));
5187       continue;
5188     }
5190     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5191     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5192     if (Opcode == ISD::SIGN_EXTEND)
5193       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5194                                      SVT));
5195     else
5196       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5197                                      SVT));
5198   }
5200   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5203 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5204 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5205 // transformation. Returns true if extension are possible and the above
5206 // mentioned transformation is profitable.
5207 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5208                                     unsigned ExtOpc,
5209                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5210                                     const TargetLowering &TLI) {
5211   bool HasCopyToRegUses = false;
5212   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5213   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5214                             UE = N0.getNode()->use_end();
5215        UI != UE; ++UI) {
5216     SDNode *User = *UI;
5217     if (User == N)
5218       continue;
5219     if (UI.getUse().getResNo() != N0.getResNo())
5220       continue;
5221     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5222     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5223       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5224       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5225         // Sign bits will be lost after a zext.
5226         return false;
5227       bool Add = false;
5228       for (unsigned i = 0; i != 2; ++i) {
5229         SDValue UseOp = User->getOperand(i);
5230         if (UseOp == N0)
5231           continue;
5232         if (!isa<ConstantSDNode>(UseOp))
5233           return false;
5234         Add = true;
5235       }
5236       if (Add)
5237         ExtendNodes.push_back(User);
5238       continue;
5239     }
5240     // If truncates aren't free and there are users we can't
5241     // extend, it isn't worthwhile.
5242     if (!isTruncFree)
5243       return false;
5244     // Remember if this value is live-out.
5245     if (User->getOpcode() == ISD::CopyToReg)
5246       HasCopyToRegUses = true;
5247   }
5249   if (HasCopyToRegUses) {
5250     bool BothLiveOut = false;
5251     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5252          UI != UE; ++UI) {
5253       SDUse &Use = UI.getUse();
5254       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5255         BothLiveOut = true;
5256         break;
5257       }
5258     }
5259     if (BothLiveOut)
5260       // Both unextended and extended values are live out. There had better be
5261       // a good reason for the transformation.
5262       return ExtendNodes.size();
5263   }
5264   return true;
5267 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5268                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5269                                   ISD::NodeType ExtType) {
5270   // Extend SetCC uses if necessary.
5271   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5272     SDNode *SetCC = SetCCs[i];
5273     SmallVector<SDValue, 4> Ops;
5275     for (unsigned j = 0; j != 2; ++j) {
5276       SDValue SOp = SetCC->getOperand(j);
5277       if (SOp == Trunc)
5278         Ops.push_back(ExtLoad);
5279       else
5280         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5281     }
5283     Ops.push_back(SetCC->getOperand(2));
5284     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5285   }
5288 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5289   SDValue N0 = N->getOperand(0);
5290   EVT VT = N->getValueType(0);
5292   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5293                                               LegalOperations))
5294     return SDValue(Res, 0);
5296   // fold (sext (sext x)) -> (sext x)
5297   // fold (sext (aext x)) -> (sext x)
5298   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5299     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5300                        N0.getOperand(0));
5302   if (N0.getOpcode() == ISD::TRUNCATE) {
5303     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5304     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5305     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5306     if (NarrowLoad.getNode()) {
5307       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5308       if (NarrowLoad.getNode() != N0.getNode()) {
5309         CombineTo(N0.getNode(), NarrowLoad);
5310         // CombineTo deleted the truncate, if needed, but not what's under it.
5311         AddToWorklist(oye);
5312       }
5313       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5314     }
5316     // See if the value being truncated is already sign extended.  If so, just
5317     // eliminate the trunc/sext pair.
5318     SDValue Op = N0.getOperand(0);
5319     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5320     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5321     unsigned DestBits = VT.getScalarType().getSizeInBits();
5322     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5324     if (OpBits == DestBits) {
5325       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5326       // bits, it is already ready.
5327       if (NumSignBits > DestBits-MidBits)
5328         return Op;
5329     } else if (OpBits < DestBits) {
5330       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5331       // bits, just sext from i32.
5332       if (NumSignBits > OpBits-MidBits)
5333         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5334     } else {
5335       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5336       // bits, just truncate to i32.
5337       if (NumSignBits > OpBits-MidBits)
5338         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5339     }
5341     // fold (sext (truncate x)) -> (sextinreg x).
5342     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5343                                                  N0.getValueType())) {
5344       if (OpBits < DestBits)
5345         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5346       else if (OpBits > DestBits)
5347         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5348       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5349                          DAG.getValueType(N0.getValueType()));
5350     }
5351   }
5353   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5354   // None of the supported targets knows how to perform load and sign extend
5355   // on vectors in one instruction.  We only perform this transformation on
5356   // scalars.
5357   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5358       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5359       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5360        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5361     bool DoXform = true;
5362     SmallVector<SDNode*, 4> SetCCs;
5363     if (!N0.hasOneUse())
5364       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5365     if (DoXform) {
5366       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5367       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5368                                        LN0->getChain(),
5369                                        LN0->getBasePtr(), N0.getValueType(),
5370                                        LN0->getMemOperand());
5371       CombineTo(N, ExtLoad);
5372       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5373                                   N0.getValueType(), ExtLoad);
5374       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5375       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5376                       ISD::SIGN_EXTEND);
5377       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5378     }
5379   }
5381   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5382   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5383   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5384       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5385     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5386     EVT MemVT = LN0->getMemoryVT();
5387     if ((!LegalOperations && !LN0->isVolatile()) ||
5388         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5389       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5390                                        LN0->getChain(),
5391                                        LN0->getBasePtr(), MemVT,
5392                                        LN0->getMemOperand());
5393       CombineTo(N, ExtLoad);
5394       CombineTo(N0.getNode(),
5395                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5396                             N0.getValueType(), ExtLoad),
5397                 ExtLoad.getValue(1));
5398       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5399     }
5400   }
5402   // fold (sext (and/or/xor (load x), cst)) ->
5403   //      (and/or/xor (sextload x), (sext cst))
5404   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5405        N0.getOpcode() == ISD::XOR) &&
5406       isa<LoadSDNode>(N0.getOperand(0)) &&
5407       N0.getOperand(1).getOpcode() == ISD::Constant &&
5408       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5409       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5410     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5411     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5412       bool DoXform = true;
5413       SmallVector<SDNode*, 4> SetCCs;
5414       if (!N0.hasOneUse())
5415         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5416                                           SetCCs, TLI);
5417       if (DoXform) {
5418         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5419                                          LN0->getChain(), LN0->getBasePtr(),
5420                                          LN0->getMemoryVT(),
5421                                          LN0->getMemOperand());
5422         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5423         Mask = Mask.sext(VT.getSizeInBits());
5424         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5425                                   ExtLoad, DAG.getConstant(Mask, VT));
5426         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5427                                     SDLoc(N0.getOperand(0)),
5428                                     N0.getOperand(0).getValueType(), ExtLoad);
5429         CombineTo(N, And);
5430         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5431         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5432                         ISD::SIGN_EXTEND);
5433         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5434       }
5435     }
5436   }
5438   if (N0.getOpcode() == ISD::SETCC) {
5439     EVT N0VT = N0.getOperand(0).getValueType();
5440     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5441     // Only do this before legalize for now.
5442     if (VT.isVector() && !LegalOperations &&
5443         TLI.getBooleanContents(N0VT) ==
5444             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5445       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5446       // of the same size as the compared operands. Only optimize sext(setcc())
5447       // if this is the case.
5448       EVT SVT = getSetCCResultType(N0VT);
5450       // We know that the # elements of the results is the same as the
5451       // # elements of the compare (and the # elements of the compare result
5452       // for that matter).  Check to see that they are the same size.  If so,
5453       // we know that the element size of the sext'd result matches the
5454       // element size of the compare operands.
5455       if (VT.getSizeInBits() == SVT.getSizeInBits())
5456         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5457                              N0.getOperand(1),
5458                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5460       // If the desired elements are smaller or larger than the source
5461       // elements we can use a matching integer vector type and then
5462       // truncate/sign extend
5463       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5464       if (SVT == MatchingVectorType) {
5465         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5466                                N0.getOperand(0), N0.getOperand(1),
5467                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5468         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5469       }
5470     }
5472     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5473     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5474     SDValue NegOne =
5475       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5476     SDValue SCC =
5477       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5478                        NegOne, DAG.getConstant(0, VT),
5479                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5480     if (SCC.getNode()) return SCC;
5482     if (!VT.isVector()) {
5483       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5484       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5485         SDLoc DL(N);
5486         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5487         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5488                                      N0.getOperand(0), N0.getOperand(1), CC);
5489         return DAG.getSelect(DL, VT, SetCC,
5490                              NegOne, DAG.getConstant(0, VT));
5491       }
5492     }
5493   }
5495   // fold (sext x) -> (zext x) if the sign bit is known zero.
5496   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5497       DAG.SignBitIsZero(N0))
5498     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5500   return SDValue();
5503 // isTruncateOf - If N is a truncate of some other value, return true, record
5504 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5505 // This function computes KnownZero to avoid a duplicated call to
5506 // computeKnownBits in the caller.
5507 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5508                          APInt &KnownZero) {
5509   APInt KnownOne;
5510   if (N->getOpcode() == ISD::TRUNCATE) {
5511     Op = N->getOperand(0);
5512     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5513     return true;
5514   }
5516   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5517       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5518     return false;
5520   SDValue Op0 = N->getOperand(0);
5521   SDValue Op1 = N->getOperand(1);
5522   assert(Op0.getValueType() == Op1.getValueType());
5524   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5525   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5526   if (COp0 && COp0->isNullValue())
5527     Op = Op1;
5528   else if (COp1 && COp1->isNullValue())
5529     Op = Op0;
5530   else
5531     return false;
5533   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5535   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5536     return false;
5538   return true;
5541 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5542   SDValue N0 = N->getOperand(0);
5543   EVT VT = N->getValueType(0);
5545   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5546                                               LegalOperations))
5547     return SDValue(Res, 0);
5549   // fold (zext (zext x)) -> (zext x)
5550   // fold (zext (aext x)) -> (zext x)
5551   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5552     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5553                        N0.getOperand(0));
5555   // fold (zext (truncate x)) -> (zext x) or
5556   //      (zext (truncate x)) -> (truncate x)
5557   // This is valid when the truncated bits of x are already zero.
5558   // FIXME: We should extend this to work for vectors too.
5559   SDValue Op;
5560   APInt KnownZero;
5561   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5562     APInt TruncatedBits =
5563       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5564       APInt(Op.getValueSizeInBits(), 0) :
5565       APInt::getBitsSet(Op.getValueSizeInBits(),
5566                         N0.getValueSizeInBits(),
5567                         std::min(Op.getValueSizeInBits(),
5568                                  VT.getSizeInBits()));
5569     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5570       if (VT.bitsGT(Op.getValueType()))
5571         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5572       if (VT.bitsLT(Op.getValueType()))
5573         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5575       return Op;
5576     }
5577   }
5579   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5580   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5581   if (N0.getOpcode() == ISD::TRUNCATE) {
5582     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5583     if (NarrowLoad.getNode()) {
5584       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5585       if (NarrowLoad.getNode() != N0.getNode()) {
5586         CombineTo(N0.getNode(), NarrowLoad);
5587         // CombineTo deleted the truncate, if needed, but not what's under it.
5588         AddToWorklist(oye);
5589       }
5590       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5591     }
5592   }
5594   // fold (zext (truncate x)) -> (and x, mask)
5595   if (N0.getOpcode() == ISD::TRUNCATE &&
5596       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5598     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5599     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5600     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5601     if (NarrowLoad.getNode()) {
5602       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5603       if (NarrowLoad.getNode() != N0.getNode()) {
5604         CombineTo(N0.getNode(), NarrowLoad);
5605         // CombineTo deleted the truncate, if needed, but not what's under it.
5606         AddToWorklist(oye);
5607       }
5608       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5609     }
5611     SDValue Op = N0.getOperand(0);
5612     if (Op.getValueType().bitsLT(VT)) {
5613       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5614       AddToWorklist(Op.getNode());
5615     } else if (Op.getValueType().bitsGT(VT)) {
5616       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5617       AddToWorklist(Op.getNode());
5618     }
5619     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5620                                   N0.getValueType().getScalarType());
5621   }
5623   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5624   // if either of the casts is not free.
5625   if (N0.getOpcode() == ISD::AND &&
5626       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5627       N0.getOperand(1).getOpcode() == ISD::Constant &&
5628       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5629                            N0.getValueType()) ||
5630        !TLI.isZExtFree(N0.getValueType(), VT))) {
5631     SDValue X = N0.getOperand(0).getOperand(0);
5632     if (X.getValueType().bitsLT(VT)) {
5633       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5634     } else if (X.getValueType().bitsGT(VT)) {
5635       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5636     }
5637     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5638     Mask = Mask.zext(VT.getSizeInBits());
5639     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5640                        X, DAG.getConstant(Mask, VT));
5641   }
5643   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5644   // None of the supported targets knows how to perform load and vector_zext
5645   // on vectors in one instruction.  We only perform this transformation on
5646   // scalars.
5647   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5648       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5649       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5650        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
5651     bool DoXform = true;
5652     SmallVector<SDNode*, 4> SetCCs;
5653     if (!N0.hasOneUse())
5654       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5655     if (DoXform) {
5656       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5657       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5658                                        LN0->getChain(),
5659                                        LN0->getBasePtr(), N0.getValueType(),
5660                                        LN0->getMemOperand());
5661       CombineTo(N, ExtLoad);
5662       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5663                                   N0.getValueType(), ExtLoad);
5664       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5666       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5667                       ISD::ZERO_EXTEND);
5668       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5669     }
5670   }
5672   // fold (zext (and/or/xor (load x), cst)) ->
5673   //      (and/or/xor (zextload x), (zext cst))
5674   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5675        N0.getOpcode() == ISD::XOR) &&
5676       isa<LoadSDNode>(N0.getOperand(0)) &&
5677       N0.getOperand(1).getOpcode() == ISD::Constant &&
5678       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
5679       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5680     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5681     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5682       bool DoXform = true;
5683       SmallVector<SDNode*, 4> SetCCs;
5684       if (!N0.hasOneUse())
5685         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5686                                           SetCCs, TLI);
5687       if (DoXform) {
5688         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5689                                          LN0->getChain(), LN0->getBasePtr(),
5690                                          LN0->getMemoryVT(),
5691                                          LN0->getMemOperand());
5692         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5693         Mask = Mask.zext(VT.getSizeInBits());
5694         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5695                                   ExtLoad, DAG.getConstant(Mask, VT));
5696         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5697                                     SDLoc(N0.getOperand(0)),
5698                                     N0.getOperand(0).getValueType(), ExtLoad);
5699         CombineTo(N, And);
5700         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5701         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5702                         ISD::ZERO_EXTEND);
5703         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5704       }
5705     }
5706   }
5708   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5709   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5710   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5711       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5712     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5713     EVT MemVT = LN0->getMemoryVT();
5714     if ((!LegalOperations && !LN0->isVolatile()) ||
5715         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
5716       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5717                                        LN0->getChain(),
5718                                        LN0->getBasePtr(), MemVT,
5719                                        LN0->getMemOperand());
5720       CombineTo(N, ExtLoad);
5721       CombineTo(N0.getNode(),
5722                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5723                             ExtLoad),
5724                 ExtLoad.getValue(1));
5725       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5726     }
5727   }
5729   if (N0.getOpcode() == ISD::SETCC) {
5730     if (!LegalOperations && VT.isVector() &&
5731         N0.getValueType().getVectorElementType() == MVT::i1) {
5732       EVT N0VT = N0.getOperand(0).getValueType();
5733       if (getSetCCResultType(N0VT) == N0.getValueType())
5734         return SDValue();
5736       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5737       // Only do this before legalize for now.
5738       EVT EltVT = VT.getVectorElementType();
5739       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5740                                     DAG.getConstant(1, EltVT));
5741       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5742         // We know that the # elements of the results is the same as the
5743         // # elements of the compare (and the # elements of the compare result
5744         // for that matter).  Check to see that they are the same size.  If so,
5745         // we know that the element size of the sext'd result matches the
5746         // element size of the compare operands.
5747         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5748                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5749                                          N0.getOperand(1),
5750                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5751                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5752                                        OneOps));
5754       // If the desired elements are smaller or larger than the source
5755       // elements we can use a matching integer vector type and then
5756       // truncate/sign extend
5757       EVT MatchingElementType =
5758         EVT::getIntegerVT(*DAG.getContext(),
5759                           N0VT.getScalarType().getSizeInBits());
5760       EVT MatchingVectorType =
5761         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5762                          N0VT.getVectorNumElements());
5763       SDValue VsetCC =
5764         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5765                       N0.getOperand(1),
5766                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5767       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5768                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5769                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5770     }
5772     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5773     SDValue SCC =
5774       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5775                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5776                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5777     if (SCC.getNode()) return SCC;
5778   }
5780   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5781   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5782       isa<ConstantSDNode>(N0.getOperand(1)) &&
5783       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5784       N0.hasOneUse()) {
5785     SDValue ShAmt = N0.getOperand(1);
5786     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5787     if (N0.getOpcode() == ISD::SHL) {
5788       SDValue InnerZExt = N0.getOperand(0);
5789       // If the original shl may be shifting out bits, do not perform this
5790       // transformation.
5791       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5792         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5793       if (ShAmtVal > KnownZeroBits)
5794         return SDValue();
5795     }
5797     SDLoc DL(N);
5799     // Ensure that the shift amount is wide enough for the shifted value.
5800     if (VT.getSizeInBits() >= 256)
5801       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5803     return DAG.getNode(N0.getOpcode(), DL, VT,
5804                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5805                        ShAmt);
5806   }
5808   return SDValue();
5811 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5812   SDValue N0 = N->getOperand(0);
5813   EVT VT = N->getValueType(0);
5815   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5816                                               LegalOperations))
5817     return SDValue(Res, 0);
5819   // fold (aext (aext x)) -> (aext x)
5820   // fold (aext (zext x)) -> (zext x)
5821   // fold (aext (sext x)) -> (sext x)
5822   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5823       N0.getOpcode() == ISD::ZERO_EXTEND ||
5824       N0.getOpcode() == ISD::SIGN_EXTEND)
5825     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5827   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5828   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5829   if (N0.getOpcode() == ISD::TRUNCATE) {
5830     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5831     if (NarrowLoad.getNode()) {
5832       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5833       if (NarrowLoad.getNode() != N0.getNode()) {
5834         CombineTo(N0.getNode(), NarrowLoad);
5835         // CombineTo deleted the truncate, if needed, but not what's under it.
5836         AddToWorklist(oye);
5837       }
5838       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5839     }
5840   }
5842   // fold (aext (truncate x))
5843   if (N0.getOpcode() == ISD::TRUNCATE) {
5844     SDValue TruncOp = N0.getOperand(0);
5845     if (TruncOp.getValueType() == VT)
5846       return TruncOp; // x iff x size == zext size.
5847     if (TruncOp.getValueType().bitsGT(VT))
5848       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5849     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5850   }
5852   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5853   // if the trunc is not free.
5854   if (N0.getOpcode() == ISD::AND &&
5855       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5856       N0.getOperand(1).getOpcode() == ISD::Constant &&
5857       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5858                           N0.getValueType())) {
5859     SDValue X = N0.getOperand(0).getOperand(0);
5860     if (X.getValueType().bitsLT(VT)) {
5861       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5862     } else if (X.getValueType().bitsGT(VT)) {
5863       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5864     }
5865     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5866     Mask = Mask.zext(VT.getSizeInBits());
5867     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5868                        X, DAG.getConstant(Mask, VT));
5869   }
5871   // fold (aext (load x)) -> (aext (truncate (extload x)))
5872   // None of the supported targets knows how to perform load and any_ext
5873   // on vectors in one instruction.  We only perform this transformation on
5874   // scalars.
5875   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5876       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5877       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
5878     bool DoXform = true;
5879     SmallVector<SDNode*, 4> SetCCs;
5880     if (!N0.hasOneUse())
5881       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5882     if (DoXform) {
5883       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5884       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5885                                        LN0->getChain(),
5886                                        LN0->getBasePtr(), N0.getValueType(),
5887                                        LN0->getMemOperand());
5888       CombineTo(N, ExtLoad);
5889       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5890                                   N0.getValueType(), ExtLoad);
5891       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5892       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5893                       ISD::ANY_EXTEND);
5894       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5895     }
5896   }
5898   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5899   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5900   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5901   if (N0.getOpcode() == ISD::LOAD &&
5902       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5903       N0.hasOneUse()) {
5904     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5905     ISD::LoadExtType ExtType = LN0->getExtensionType();
5906     EVT MemVT = LN0->getMemoryVT();
5907     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
5908       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5909                                        VT, LN0->getChain(), LN0->getBasePtr(),
5910                                        MemVT, LN0->getMemOperand());
5911       CombineTo(N, ExtLoad);
5912       CombineTo(N0.getNode(),
5913                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5914                             N0.getValueType(), ExtLoad),
5915                 ExtLoad.getValue(1));
5916       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5917     }
5918   }
5920   if (N0.getOpcode() == ISD::SETCC) {
5921     // For vectors:
5922     // aext(setcc) -> vsetcc
5923     // aext(setcc) -> truncate(vsetcc)
5924     // aext(setcc) -> aext(vsetcc)
5925     // Only do this before legalize for now.
5926     if (VT.isVector() && !LegalOperations) {
5927       EVT N0VT = N0.getOperand(0).getValueType();
5928         // We know that the # elements of the results is the same as the
5929         // # elements of the compare (and the # elements of the compare result
5930         // for that matter).  Check to see that they are the same size.  If so,
5931         // we know that the element size of the sext'd result matches the
5932         // element size of the compare operands.
5933       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5934         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5935                              N0.getOperand(1),
5936                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5937       // If the desired elements are smaller or larger than the source
5938       // elements we can use a matching integer vector type and then
5939       // truncate/any extend
5940       else {
5941         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5942         SDValue VsetCC =
5943           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5944                         N0.getOperand(1),
5945                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5946         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5947       }
5948     }
5950     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5951     SDValue SCC =
5952       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5953                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5954                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5955     if (SCC.getNode())
5956       return SCC;
5957   }
5959   return SDValue();
5962 /// See if the specified operand can be simplified with the knowledge that only
5963 /// the bits specified by Mask are used.  If so, return the simpler operand,
5964 /// otherwise return a null SDValue.
5965 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5966   switch (V.getOpcode()) {
5967   default: break;
5968   case ISD::Constant: {
5969     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5970     assert(CV && "Const value should be ConstSDNode.");
5971     const APInt &CVal = CV->getAPIntValue();
5972     APInt NewVal = CVal & Mask;
5973     if (NewVal != CVal)
5974       return DAG.getConstant(NewVal, V.getValueType());
5975     break;
5976   }
5977   case ISD::OR:
5978   case ISD::XOR:
5979     // If the LHS or RHS don't contribute bits to the or, drop them.
5980     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5981       return V.getOperand(1);
5982     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5983       return V.getOperand(0);
5984     break;
5985   case ISD::SRL:
5986     // Only look at single-use SRLs.
5987     if (!V.getNode()->hasOneUse())
5988       break;
5989     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5990       // See if we can recursively simplify the LHS.
5991       unsigned Amt = RHSC->getZExtValue();
5993       // Watch out for shift count overflow though.
5994       if (Amt >= Mask.getBitWidth()) break;
5995       APInt NewMask = Mask << Amt;
5996       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5997       if (SimplifyLHS.getNode())
5998         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5999                            SimplifyLHS, V.getOperand(1));
6000     }
6001   }
6002   return SDValue();
6005 /// If the result of a wider load is shifted to right of N  bits and then
6006 /// truncated to a narrower type and where N is a multiple of number of bits of
6007 /// the narrower type, transform it to a narrower load from address + N / num of
6008 /// bits of new type. If the result is to be extended, also fold the extension
6009 /// to form a extending load.
6010 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6011   unsigned Opc = N->getOpcode();
6013   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6014   SDValue N0 = N->getOperand(0);
6015   EVT VT = N->getValueType(0);
6016   EVT ExtVT = VT;
6018   // This transformation isn't valid for vector loads.
6019   if (VT.isVector())
6020     return SDValue();
6022   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6023   // extended to VT.
6024   if (Opc == ISD::SIGN_EXTEND_INREG) {
6025     ExtType = ISD::SEXTLOAD;
6026     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6027   } else if (Opc == ISD::SRL) {
6028     // Another special-case: SRL is basically zero-extending a narrower value.
6029     ExtType = ISD::ZEXTLOAD;
6030     N0 = SDValue(N, 0);
6031     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6032     if (!N01) return SDValue();
6033     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6034                               VT.getSizeInBits() - N01->getZExtValue());
6035   }
6036   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6037     return SDValue();
6039   unsigned EVTBits = ExtVT.getSizeInBits();
6041   // Do not generate loads of non-round integer types since these can
6042   // be expensive (and would be wrong if the type is not byte sized).
6043   if (!ExtVT.isRound())
6044     return SDValue();
6046   unsigned ShAmt = 0;
6047   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6048     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6049       ShAmt = N01->getZExtValue();
6050       // Is the shift amount a multiple of size of VT?
6051       if ((ShAmt & (EVTBits-1)) == 0) {
6052         N0 = N0.getOperand(0);
6053         // Is the load width a multiple of size of VT?
6054         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6055           return SDValue();
6056       }
6058       // At this point, we must have a load or else we can't do the transform.
6059       if (!isa<LoadSDNode>(N0)) return SDValue();
6061       // Because a SRL must be assumed to *need* to zero-extend the high bits
6062       // (as opposed to anyext the high bits), we can't combine the zextload
6063       // lowering of SRL and an sextload.
6064       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6065         return SDValue();
6067       // If the shift amount is larger than the input type then we're not
6068       // accessing any of the loaded bytes.  If the load was a zextload/extload
6069       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6070       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6071         return SDValue();
6072     }
6073   }
6075   // If the load is shifted left (and the result isn't shifted back right),
6076   // we can fold the truncate through the shift.
6077   unsigned ShLeftAmt = 0;
6078   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6079       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6080     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6081       ShLeftAmt = N01->getZExtValue();
6082       N0 = N0.getOperand(0);
6083     }
6084   }
6086   // If we haven't found a load, we can't narrow it.  Don't transform one with
6087   // multiple uses, this would require adding a new load.
6088   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6089     return SDValue();
6091   // Don't change the width of a volatile load.
6092   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6093   if (LN0->isVolatile())
6094     return SDValue();
6096   // Verify that we are actually reducing a load width here.
6097   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6098     return SDValue();
6100   // For the transform to be legal, the load must produce only two values
6101   // (the value loaded and the chain).  Don't transform a pre-increment
6102   // load, for example, which produces an extra value.  Otherwise the
6103   // transformation is not equivalent, and the downstream logic to replace
6104   // uses gets things wrong.
6105   if (LN0->getNumValues() > 2)
6106     return SDValue();
6108   // If the load that we're shrinking is an extload and we're not just
6109   // discarding the extension we can't simply shrink the load. Bail.
6110   // TODO: It would be possible to merge the extensions in some cases.
6111   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6112       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6113     return SDValue();
6115   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6116     return SDValue();
6118   EVT PtrType = N0.getOperand(1).getValueType();
6120   if (PtrType == MVT::Untyped || PtrType.isExtended())
6121     // It's not possible to generate a constant of extended or untyped type.
6122     return SDValue();
6124   // For big endian targets, we need to adjust the offset to the pointer to
6125   // load the correct bytes.
6126   if (TLI.isBigEndian()) {
6127     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6128     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6129     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6130   }
6132   uint64_t PtrOff = ShAmt / 8;
6133   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6134   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
6135                                PtrType, LN0->getBasePtr(),
6136                                DAG.getConstant(PtrOff, PtrType));
6137   AddToWorklist(NewPtr.getNode());
6139   SDValue Load;
6140   if (ExtType == ISD::NON_EXTLOAD)
6141     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6142                         LN0->getPointerInfo().getWithOffset(PtrOff),
6143                         LN0->isVolatile(), LN0->isNonTemporal(),
6144                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6145   else
6146     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6147                           LN0->getPointerInfo().getWithOffset(PtrOff),
6148                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6149                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6151   // Replace the old load's chain with the new load's chain.
6152   WorklistRemover DeadNodes(*this);
6153   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6155   // Shift the result left, if we've swallowed a left shift.
6156   SDValue Result = Load;
6157   if (ShLeftAmt != 0) {
6158     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6159     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6160       ShImmTy = VT;
6161     // If the shift amount is as large as the result size (but, presumably,
6162     // no larger than the source) then the useful bits of the result are
6163     // zero; we can't simply return the shortened shift, because the result
6164     // of that operation is undefined.
6165     if (ShLeftAmt >= VT.getSizeInBits())
6166       Result = DAG.getConstant(0, VT);
6167     else
6168       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
6169                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
6170   }
6172   // Return the new loaded value.
6173   return Result;
6176 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6177   SDValue N0 = N->getOperand(0);
6178   SDValue N1 = N->getOperand(1);
6179   EVT VT = N->getValueType(0);
6180   EVT EVT = cast<VTSDNode>(N1)->getVT();
6181   unsigned VTBits = VT.getScalarType().getSizeInBits();
6182   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6184   // fold (sext_in_reg c1) -> c1
6185   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6186     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6188   // If the input is already sign extended, just drop the extension.
6189   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6190     return N0;
6192   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6193   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6194       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6195     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6196                        N0.getOperand(0), N1);
6198   // fold (sext_in_reg (sext x)) -> (sext x)
6199   // fold (sext_in_reg (aext x)) -> (sext x)
6200   // if x is small enough.
6201   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6202     SDValue N00 = N0.getOperand(0);
6203     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6204         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6205       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6206   }
6208   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6209   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6210     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6212   // fold operands of sext_in_reg based on knowledge that the top bits are not
6213   // demanded.
6214   if (SimplifyDemandedBits(SDValue(N, 0)))
6215     return SDValue(N, 0);
6217   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6218   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6219   SDValue NarrowLoad = ReduceLoadWidth(N);
6220   if (NarrowLoad.getNode())
6221     return NarrowLoad;
6223   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6224   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6225   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6226   if (N0.getOpcode() == ISD::SRL) {
6227     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6228       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6229         // We can turn this into an SRA iff the input to the SRL is already sign
6230         // extended enough.
6231         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6232         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6233           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6234                              N0.getOperand(0), N0.getOperand(1));
6235       }
6236   }
6238   // fold (sext_inreg (extload x)) -> (sextload x)
6239   if (ISD::isEXTLoad(N0.getNode()) &&
6240       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6241       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6242       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6243        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6244     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6245     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6246                                      LN0->getChain(),
6247                                      LN0->getBasePtr(), EVT,
6248                                      LN0->getMemOperand());
6249     CombineTo(N, ExtLoad);
6250     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6251     AddToWorklist(ExtLoad.getNode());
6252     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6253   }
6254   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6255   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6256       N0.hasOneUse() &&
6257       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6258       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6259        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6260     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6261     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6262                                      LN0->getChain(),
6263                                      LN0->getBasePtr(), EVT,
6264                                      LN0->getMemOperand());
6265     CombineTo(N, ExtLoad);
6266     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6267     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6268   }
6270   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6271   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6272     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6273                                        N0.getOperand(1), false);
6274     if (BSwap.getNode())
6275       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6276                          BSwap, N1);
6277   }
6279   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6280   // into a build_vector.
6281   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6282     SmallVector<SDValue, 8> Elts;
6283     unsigned NumElts = N0->getNumOperands();
6284     unsigned ShAmt = VTBits - EVTBits;
6286     for (unsigned i = 0; i != NumElts; ++i) {
6287       SDValue Op = N0->getOperand(i);
6288       if (Op->getOpcode() == ISD::UNDEF) {
6289         Elts.push_back(Op);
6290         continue;
6291       }
6293       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6294       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6295       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6296                                      Op.getValueType()));
6297     }
6299     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6300   }
6302   return SDValue();
6305 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6306   SDValue N0 = N->getOperand(0);
6307   EVT VT = N->getValueType(0);
6308   bool isLE = TLI.isLittleEndian();
6310   // noop truncate
6311   if (N0.getValueType() == N->getValueType(0))
6312     return N0;
6313   // fold (truncate c1) -> c1
6314   if (isa<ConstantSDNode>(N0))
6315     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6316   // fold (truncate (truncate x)) -> (truncate x)
6317   if (N0.getOpcode() == ISD::TRUNCATE)
6318     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6319   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6320   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6321       N0.getOpcode() == ISD::SIGN_EXTEND ||
6322       N0.getOpcode() == ISD::ANY_EXTEND) {
6323     if (N0.getOperand(0).getValueType().bitsLT(VT))
6324       // if the source is smaller than the dest, we still need an extend
6325       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6326                          N0.getOperand(0));
6327     if (N0.getOperand(0).getValueType().bitsGT(VT))
6328       // if the source is larger than the dest, than we just need the truncate
6329       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6330     // if the source and dest are the same type, we can drop both the extend
6331     // and the truncate.
6332     return N0.getOperand(0);
6333   }
6335   // Fold extract-and-trunc into a narrow extract. For example:
6336   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6337   //   i32 y = TRUNCATE(i64 x)
6338   //        -- becomes --
6339   //   v16i8 b = BITCAST (v2i64 val)
6340   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6341   //
6342   // Note: We only run this optimization after type legalization (which often
6343   // creates this pattern) and before operation legalization after which
6344   // we need to be more careful about the vector instructions that we generate.
6345   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6346       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6348     EVT VecTy = N0.getOperand(0).getValueType();
6349     EVT ExTy = N0.getValueType();
6350     EVT TrTy = N->getValueType(0);
6352     unsigned NumElem = VecTy.getVectorNumElements();
6353     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6355     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6356     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6358     SDValue EltNo = N0->getOperand(1);
6359     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6360       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6361       EVT IndexTy = TLI.getVectorIdxTy();
6362       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6364       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6365                               NVT, N0.getOperand(0));
6367       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6368                          SDLoc(N), TrTy, V,
6369                          DAG.getConstant(Index, IndexTy));
6370     }
6371   }
6373   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6374   if (N0.getOpcode() == ISD::SELECT) {
6375     EVT SrcVT = N0.getValueType();
6376     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6377         TLI.isTruncateFree(SrcVT, VT)) {
6378       SDLoc SL(N0);
6379       SDValue Cond = N0.getOperand(0);
6380       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6381       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6382       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6383     }
6384   }
6386   // Fold a series of buildvector, bitcast, and truncate if possible.
6387   // For example fold
6388   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6389   //   (2xi32 (buildvector x, y)).
6390   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6391       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6392       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6393       N0.getOperand(0).hasOneUse()) {
6395     SDValue BuildVect = N0.getOperand(0);
6396     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6397     EVT TruncVecEltTy = VT.getVectorElementType();
6399     // Check that the element types match.
6400     if (BuildVectEltTy == TruncVecEltTy) {
6401       // Now we only need to compute the offset of the truncated elements.
6402       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6403       unsigned TruncVecNumElts = VT.getVectorNumElements();
6404       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6406       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6407              "Invalid number of elements");
6409       SmallVector<SDValue, 8> Opnds;
6410       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6411         Opnds.push_back(BuildVect.getOperand(i));
6413       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6414     }
6415   }
6417   // See if we can simplify the input to this truncate through knowledge that
6418   // only the low bits are being used.
6419   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6420   // Currently we only perform this optimization on scalars because vectors
6421   // may have different active low bits.
6422   if (!VT.isVector()) {
6423     SDValue Shorter =
6424       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6425                                                VT.getSizeInBits()));
6426     if (Shorter.getNode())
6427       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6428   }
6429   // fold (truncate (load x)) -> (smaller load x)
6430   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6431   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6432     SDValue Reduced = ReduceLoadWidth(N);
6433     if (Reduced.getNode())
6434       return Reduced;
6435     // Handle the case where the load remains an extending load even
6436     // after truncation.
6437     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6438       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6439       if (!LN0->isVolatile() &&
6440           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6441         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6442                                          VT, LN0->getChain(), LN0->getBasePtr(),
6443                                          LN0->getMemoryVT(),
6444                                          LN0->getMemOperand());
6445         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6446         return NewLoad;
6447       }
6448     }
6449   }
6450   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6451   // where ... are all 'undef'.
6452   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6453     SmallVector<EVT, 8> VTs;
6454     SDValue V;
6455     unsigned Idx = 0;
6456     unsigned NumDefs = 0;
6458     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6459       SDValue X = N0.getOperand(i);
6460       if (X.getOpcode() != ISD::UNDEF) {
6461         V = X;
6462         Idx = i;
6463         NumDefs++;
6464       }
6465       // Stop if more than one members are non-undef.
6466       if (NumDefs > 1)
6467         break;
6468       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6469                                      VT.getVectorElementType(),
6470                                      X.getValueType().getVectorNumElements()));
6471     }
6473     if (NumDefs == 0)
6474       return DAG.getUNDEF(VT);
6476     if (NumDefs == 1) {
6477       assert(V.getNode() && "The single defined operand is empty!");
6478       SmallVector<SDValue, 8> Opnds;
6479       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6480         if (i != Idx) {
6481           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6482           continue;
6483         }
6484         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6485         AddToWorklist(NV.getNode());
6486         Opnds.push_back(NV);
6487       }
6488       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6489     }
6490   }
6492   // Simplify the operands using demanded-bits information.
6493   if (!VT.isVector() &&
6494       SimplifyDemandedBits(SDValue(N, 0)))
6495     return SDValue(N, 0);
6497   return SDValue();
6500 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6501   SDValue Elt = N->getOperand(i);
6502   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6503     return Elt.getNode();
6504   return Elt.getOperand(Elt.getResNo()).getNode();
6507 /// build_pair (load, load) -> load
6508 /// if load locations are consecutive.
6509 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6510   assert(N->getOpcode() == ISD::BUILD_PAIR);
6512   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6513   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6514   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6515       LD1->getAddressSpace() != LD2->getAddressSpace())
6516     return SDValue();
6517   EVT LD1VT = LD1->getValueType(0);
6519   if (ISD::isNON_EXTLoad(LD2) &&
6520       LD2->hasOneUse() &&
6521       // If both are volatile this would reduce the number of volatile loads.
6522       // If one is volatile it might be ok, but play conservative and bail out.
6523       !LD1->isVolatile() &&
6524       !LD2->isVolatile() &&
6525       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6526     unsigned Align = LD1->getAlignment();
6527     unsigned NewAlign = TLI.getDataLayout()->
6528       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6530     if (NewAlign <= Align &&
6531         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6532       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6533                          LD1->getBasePtr(), LD1->getPointerInfo(),
6534                          false, false, false, Align);
6535   }
6537   return SDValue();
6540 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6541   SDValue N0 = N->getOperand(0);
6542   EVT VT = N->getValueType(0);
6544   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6545   // Only do this before legalize, since afterward the target may be depending
6546   // on the bitconvert.
6547   // First check to see if this is all constant.
6548   if (!LegalTypes &&
6549       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6550       VT.isVector()) {
6551     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6553     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6554     assert(!DestEltVT.isVector() &&
6555            "Element type of vector ValueType must not be vector!");
6556     if (isSimple)
6557       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6558   }
6560   // If the input is a constant, let getNode fold it.
6561   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6562     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6563     if (Res.getNode() != N) {
6564       if (!LegalOperations ||
6565           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6566         return Res;
6568       // Folding it resulted in an illegal node, and it's too late to
6569       // do that. Clean up the old node and forego the transformation.
6570       // Ideally this won't happen very often, because instcombine
6571       // and the earlier dagcombine runs (where illegal nodes are
6572       // permitted) should have folded most of them already.
6573       deleteAndRecombine(Res.getNode());
6574     }
6575   }
6577   // (conv (conv x, t1), t2) -> (conv x, t2)
6578   if (N0.getOpcode() == ISD::BITCAST)
6579     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6580                        N0.getOperand(0));
6582   // fold (conv (load x)) -> (load (conv*)x)
6583   // If the resultant load doesn't need a higher alignment than the original!
6584   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6585       // Do not change the width of a volatile load.
6586       !cast<LoadSDNode>(N0)->isVolatile() &&
6587       // Do not remove the cast if the types differ in endian layout.
6588       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6589       TLI.hasBigEndianPartOrdering(VT) &&
6590       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6591       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6592     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6593     unsigned Align = TLI.getDataLayout()->
6594       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6595     unsigned OrigAlign = LN0->getAlignment();
6597     if (Align <= OrigAlign) {
6598       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6599                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6600                                  LN0->isVolatile(), LN0->isNonTemporal(),
6601                                  LN0->isInvariant(), OrigAlign,
6602                                  LN0->getAAInfo());
6603       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6604       return Load;
6605     }
6606   }
6608   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6609   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6610   // This often reduces constant pool loads.
6611   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6612        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6613       N0.getNode()->hasOneUse() && VT.isInteger() &&
6614       !VT.isVector() && !N0.getValueType().isVector()) {
6615     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6616                                   N0.getOperand(0));
6617     AddToWorklist(NewConv.getNode());
6619     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6620     if (N0.getOpcode() == ISD::FNEG)
6621       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6622                          NewConv, DAG.getConstant(SignBit, VT));
6623     assert(N0.getOpcode() == ISD::FABS);
6624     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6625                        NewConv, DAG.getConstant(~SignBit, VT));
6626   }
6628   // fold (bitconvert (fcopysign cst, x)) ->
6629   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6630   // Note that we don't handle (copysign x, cst) because this can always be
6631   // folded to an fneg or fabs.
6632   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6633       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6634       VT.isInteger() && !VT.isVector()) {
6635     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6636     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6637     if (isTypeLegal(IntXVT)) {
6638       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6639                               IntXVT, N0.getOperand(1));
6640       AddToWorklist(X.getNode());
6642       // If X has a different width than the result/lhs, sext it or truncate it.
6643       unsigned VTWidth = VT.getSizeInBits();
6644       if (OrigXWidth < VTWidth) {
6645         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6646         AddToWorklist(X.getNode());
6647       } else if (OrigXWidth > VTWidth) {
6648         // To get the sign bit in the right place, we have to shift it right
6649         // before truncating.
6650         X = DAG.getNode(ISD::SRL, SDLoc(X),
6651                         X.getValueType(), X,
6652                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6653         AddToWorklist(X.getNode());
6654         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6655         AddToWorklist(X.getNode());
6656       }
6658       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6659       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6660                       X, DAG.getConstant(SignBit, VT));
6661       AddToWorklist(X.getNode());
6663       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6664                                 VT, N0.getOperand(0));
6665       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6666                         Cst, DAG.getConstant(~SignBit, VT));
6667       AddToWorklist(Cst.getNode());
6669       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6670     }
6671   }
6673   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6674   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6675     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6676     if (CombineLD.getNode())
6677       return CombineLD;
6678   }
6680   return SDValue();
6683 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6684   EVT VT = N->getValueType(0);
6685   return CombineConsecutiveLoads(N, VT);
6688 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6689 /// operands. DstEltVT indicates the destination element value type.
6690 SDValue DAGCombiner::
6691 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6692   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6694   // If this is already the right type, we're done.
6695   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6697   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6698   unsigned DstBitSize = DstEltVT.getSizeInBits();
6700   // If this is a conversion of N elements of one type to N elements of another
6701   // type, convert each element.  This handles FP<->INT cases.
6702   if (SrcBitSize == DstBitSize) {
6703     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6704                               BV->getValueType(0).getVectorNumElements());
6706     // Due to the FP element handling below calling this routine recursively,
6707     // we can end up with a scalar-to-vector node here.
6708     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6709       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6710                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6711                                      DstEltVT, BV->getOperand(0)));
6713     SmallVector<SDValue, 8> Ops;
6714     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6715       SDValue Op = BV->getOperand(i);
6716       // If the vector element type is not legal, the BUILD_VECTOR operands
6717       // are promoted and implicitly truncated.  Make that explicit here.
6718       if (Op.getValueType() != SrcEltVT)
6719         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6720       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6721                                 DstEltVT, Op));
6722       AddToWorklist(Ops.back().getNode());
6723     }
6724     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6725   }
6727   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6728   // handle annoying details of growing/shrinking FP values, we convert them to
6729   // int first.
6730   if (SrcEltVT.isFloatingPoint()) {
6731     // Convert the input float vector to a int vector where the elements are the
6732     // same sizes.
6733     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6734     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6735     SrcEltVT = IntVT;
6736   }
6738   // Now we know the input is an integer vector.  If the output is a FP type,
6739   // convert to integer first, then to FP of the right size.
6740   if (DstEltVT.isFloatingPoint()) {
6741     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6742     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6744     // Next, convert to FP elements of the same size.
6745     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6746   }
6748   // Okay, we know the src/dst types are both integers of differing types.
6749   // Handling growing first.
6750   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6751   if (SrcBitSize < DstBitSize) {
6752     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6754     SmallVector<SDValue, 8> Ops;
6755     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6756          i += NumInputsPerOutput) {
6757       bool isLE = TLI.isLittleEndian();
6758       APInt NewBits = APInt(DstBitSize, 0);
6759       bool EltIsUndef = true;
6760       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6761         // Shift the previously computed bits over.
6762         NewBits <<= SrcBitSize;
6763         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6764         if (Op.getOpcode() == ISD::UNDEF) continue;
6765         EltIsUndef = false;
6767         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6768                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6769       }
6771       if (EltIsUndef)
6772         Ops.push_back(DAG.getUNDEF(DstEltVT));
6773       else
6774         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6775     }
6777     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6778     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6779   }
6781   // Finally, this must be the case where we are shrinking elements: each input
6782   // turns into multiple outputs.
6783   bool isS2V = ISD::isScalarToVector(BV);
6784   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6785   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6786                             NumOutputsPerInput*BV->getNumOperands());
6787   SmallVector<SDValue, 8> Ops;
6789   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6790     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6791       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6792         Ops.push_back(DAG.getUNDEF(DstEltVT));
6793       continue;
6794     }
6796     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6797                   getAPIntValue().zextOrTrunc(SrcBitSize);
6799     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6800       APInt ThisVal = OpVal.trunc(DstBitSize);
6801       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6802       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6803         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6804         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6805                            Ops[0]);
6806       OpVal = OpVal.lshr(DstBitSize);
6807     }
6809     // For big endian targets, swap the order of the pieces of each element.
6810     if (TLI.isBigEndian())
6811       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6812   }
6814   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6817 SDValue DAGCombiner::visitFADD(SDNode *N) {
6818   SDValue N0 = N->getOperand(0);
6819   SDValue N1 = N->getOperand(1);
6820   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6821   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6822   EVT VT = N->getValueType(0);
6823   const TargetOptions &Options = DAG.getTarget().Options;
6825   // fold vector ops
6826   if (VT.isVector()) {
6827     SDValue FoldedVOp = SimplifyVBinOp(N);
6828     if (FoldedVOp.getNode()) return FoldedVOp;
6829   }
6831   // fold (fadd c1, c2) -> c1 + c2
6832   if (N0CFP && N1CFP)
6833     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6835   // canonicalize constant to RHS
6836   if (N0CFP && !N1CFP)
6837     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6839   // fold (fadd A, (fneg B)) -> (fsub A, B)
6840   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6841       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6842     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6843                        GetNegatedExpression(N1, DAG, LegalOperations));
6845   // fold (fadd (fneg A), B) -> (fsub B, A)
6846   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6847       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6848     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6849                        GetNegatedExpression(N0, DAG, LegalOperations));
6851   // If 'unsafe math' is enabled, fold lots of things.
6852   if (Options.UnsafeFPMath) {
6853     // No FP constant should be created after legalization as Instruction
6854     // Selection pass has a hard time dealing with FP constants.
6855     bool AllowNewConst = (Level < AfterLegalizeDAG);
6857     // fold (fadd A, 0) -> A
6858     if (N1CFP && N1CFP->getValueAPF().isZero())
6859       return N0;
6861     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6862     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6863         isa<ConstantFPSDNode>(N0.getOperand(1)))
6864       return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6865                          DAG.getNode(ISD::FADD, SDLoc(N), VT,
6866                                      N0.getOperand(1), N1));
6868     // If allowed, fold (fadd (fneg x), x) -> 0.0
6869     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6870       return DAG.getConstantFP(0.0, VT);
6872     // If allowed, fold (fadd x, (fneg x)) -> 0.0
6873     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6874       return DAG.getConstantFP(0.0, VT);
6876     // We can fold chains of FADD's of the same value into multiplications.
6877     // This transform is not safe in general because we are reducing the number
6878     // of rounding steps.
6879     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
6880       if (N0.getOpcode() == ISD::FMUL) {
6881         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6882         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6884         // (fadd (fmul x, c), x) -> (fmul x, c+1)
6885         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6886           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6887                                        SDValue(CFP01, 0),
6888                                        DAG.getConstantFP(1.0, VT));
6889           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
6890         }
6892         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6893         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6894             N1.getOperand(0) == N1.getOperand(1) &&
6895             N0.getOperand(0) == N1.getOperand(0)) {
6896           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6897                                        SDValue(CFP01, 0),
6898                                        DAG.getConstantFP(2.0, VT));
6899           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6900                              N0.getOperand(0), NewCFP);
6901         }
6902       }
6904       if (N1.getOpcode() == ISD::FMUL) {
6905         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6906         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6908         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6909         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6910           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6911                                        SDValue(CFP11, 0),
6912                                        DAG.getConstantFP(1.0, VT));
6913           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
6914         }
6916         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6917         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6918             N0.getOperand(0) == N0.getOperand(1) &&
6919             N1.getOperand(0) == N0.getOperand(0)) {
6920           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6921                                        SDValue(CFP11, 0),
6922                                        DAG.getConstantFP(2.0, VT));
6923           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
6924         }
6925       }
6927       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
6928         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6929         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6930         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6931             (N0.getOperand(0) == N1))
6932           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6933                              N1, DAG.getConstantFP(3.0, VT));
6934       }
6936       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
6937         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6938         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6939         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6940             N1.getOperand(0) == N0)
6941           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6942                              N0, DAG.getConstantFP(3.0, VT));
6943       }
6945       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6946       if (AllowNewConst &&
6947           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6948           N0.getOperand(0) == N0.getOperand(1) &&
6949           N1.getOperand(0) == N1.getOperand(1) &&
6950           N0.getOperand(0) == N1.getOperand(0))
6951         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6952                            N0.getOperand(0), DAG.getConstantFP(4.0, VT));
6953     }
6954   } // enable-unsafe-fp-math
6956   // FADD -> FMA combines:
6957   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6958       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6959       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6961     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6962     if (N0.getOpcode() == ISD::FMUL &&
6963         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6964       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6965                          N0.getOperand(0), N0.getOperand(1), N1);
6967     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6968     // Note: Commutes FADD operands.
6969     if (N1.getOpcode() == ISD::FMUL &&
6970         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6971       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6972                          N1.getOperand(0), N1.getOperand(1), N0);
6974     // When FP_EXTEND nodes are free on the target, and there is an opportunity
6975     // to combine into FMA, arrange such nodes accordingly.
6976     if (TLI.isFPExtFree(VT)) {
6978       // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
6979       if (N0.getOpcode() == ISD::FP_EXTEND) {
6980         SDValue N00 = N0.getOperand(0);
6981         if (N00.getOpcode() == ISD::FMUL)
6982           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6983                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
6984                                          N00.getOperand(0)),
6985                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
6986                                          N00.getOperand(1)), N1);
6987       }
6989       // fold (fadd x, (fpext (fmul y, z)), z) -> (fma (fpext y), (fpext z), x)
6990       // Note: Commutes FADD operands.
6991       if (N1.getOpcode() == ISD::FP_EXTEND) {
6992         SDValue N10 = N1.getOperand(0);
6993         if (N10.getOpcode() == ISD::FMUL)
6994           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6995                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
6996                                          N10.getOperand(0)),
6997                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
6998                                          N10.getOperand(1)), N0);
6999       }
7000     }
7002     // More folding opportunities when target permits.
7003     if (TLI.enableAggressiveFMAFusion(VT)) {
7005       // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7006       if (N0.getOpcode() == ISD::FMA &&
7007           N0.getOperand(2).getOpcode() == ISD::FMUL)
7008         return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7009                            N0.getOperand(0), N0.getOperand(1),
7010                            DAG.getNode(ISD::FMA, SDLoc(N), VT,
7011                                        N0.getOperand(2).getOperand(0),
7012                                        N0.getOperand(2).getOperand(1),
7013                                        N1));
7015       // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7016       if (N1->getOpcode() == ISD::FMA &&
7017           N1.getOperand(2).getOpcode() == ISD::FMUL)
7018         return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7019                            N1.getOperand(0), N1.getOperand(1),
7020                            DAG.getNode(ISD::FMA, SDLoc(N), VT,
7021                                        N1.getOperand(2).getOperand(0),
7022                                        N1.getOperand(2).getOperand(1),
7023                                        N0));
7024     }
7025   }
7027   return SDValue();
7030 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7031   SDValue N0 = N->getOperand(0);
7032   SDValue N1 = N->getOperand(1);
7033   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7034   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7035   EVT VT = N->getValueType(0);
7036   SDLoc dl(N);
7037   const TargetOptions &Options = DAG.getTarget().Options;
7039   // fold vector ops
7040   if (VT.isVector()) {
7041     SDValue FoldedVOp = SimplifyVBinOp(N);
7042     if (FoldedVOp.getNode()) return FoldedVOp;
7043   }
7045   // fold (fsub c1, c2) -> c1-c2
7046   if (N0CFP && N1CFP)
7047     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
7049   // fold (fsub A, (fneg B)) -> (fadd A, B)
7050   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7051     return DAG.getNode(ISD::FADD, dl, VT, N0,
7052                        GetNegatedExpression(N1, DAG, LegalOperations));
7054   // If 'unsafe math' is enabled, fold lots of things.
7055   if (Options.UnsafeFPMath) {
7056     // (fsub A, 0) -> A
7057     if (N1CFP && N1CFP->getValueAPF().isZero())
7058       return N0;
7060     // (fsub 0, B) -> -B
7061     if (N0CFP && N0CFP->getValueAPF().isZero()) {
7062       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7063         return GetNegatedExpression(N1, DAG, LegalOperations);
7064       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7065         return DAG.getNode(ISD::FNEG, dl, VT, N1);
7066     }
7068     // (fsub x, x) -> 0.0
7069     if (N0 == N1)
7070       return DAG.getConstantFP(0.0f, VT);
7072     // (fsub x, (fadd x, y)) -> (fneg y)
7073     // (fsub x, (fadd y, x)) -> (fneg y)
7074     if (N1.getOpcode() == ISD::FADD) {
7075       SDValue N10 = N1->getOperand(0);
7076       SDValue N11 = N1->getOperand(1);
7078       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7079         return GetNegatedExpression(N11, DAG, LegalOperations);
7081       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7082         return GetNegatedExpression(N10, DAG, LegalOperations);
7083     }
7084   }
7086   // FSUB -> FMA combines:
7087   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
7088       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7089       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
7091     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7092     if (N0.getOpcode() == ISD::FMUL &&
7093         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
7094       return DAG.getNode(ISD::FMA, dl, VT,
7095                          N0.getOperand(0), N0.getOperand(1),
7096                          DAG.getNode(ISD::FNEG, dl, VT, N1));
7098     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7099     // Note: Commutes FSUB operands.
7100     if (N1.getOpcode() == ISD::FMUL &&
7101         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
7102       return DAG.getNode(ISD::FMA, dl, VT,
7103                          DAG.getNode(ISD::FNEG, dl, VT,
7104                          N1.getOperand(0)),
7105                          N1.getOperand(1), N0);
7107     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7108     if (N0.getOpcode() == ISD::FNEG &&
7109         N0.getOperand(0).getOpcode() == ISD::FMUL &&
7110         ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
7111             TLI.enableAggressiveFMAFusion(VT))) {
7112       SDValue N00 = N0.getOperand(0).getOperand(0);
7113       SDValue N01 = N0.getOperand(0).getOperand(1);
7114       return DAG.getNode(ISD::FMA, dl, VT,
7115                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
7116                          DAG.getNode(ISD::FNEG, dl, VT, N1));
7117     }
7119     // When FP_EXTEND nodes are free on the target, and there is an opportunity
7120     // to combine into FMA, arrange such nodes accordingly.
7121     if (TLI.isFPExtFree(VT)) {
7123       // fold (fsub (fpext (fmul x, y)), z)
7124       //   -> (fma (fpext x), (fpext y), (fneg z))
7125       if (N0.getOpcode() == ISD::FP_EXTEND) {
7126         SDValue N00 = N0.getOperand(0);
7127         if (N00.getOpcode() == ISD::FMUL)
7128           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7129                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7130                                          N00.getOperand(0)),
7131                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7132                                          N00.getOperand(1)),
7133                              DAG.getNode(ISD::FNEG, SDLoc(N), VT, N1));
7134       }
7136       // fold (fsub x, (fpext (fmul y, z)))
7137       //   -> (fma (fneg (fpext y)), (fpext z), x)
7138       // Note: Commutes FSUB operands.
7139       if (N1.getOpcode() == ISD::FP_EXTEND) {
7140         SDValue N10 = N1.getOperand(0);
7141         if (N10.getOpcode() == ISD::FMUL)
7142           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7143                              DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7144                                          DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7145                                                      VT, N10.getOperand(0))),
7146                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7147                                          N10.getOperand(1)),
7148                              N0);
7149       }
7151       // fold (fsub (fpext (fneg (fmul, x, y))), z)
7152       //   -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7153       if (N0.getOpcode() == ISD::FP_EXTEND) {
7154         SDValue N00 = N0.getOperand(0);
7155         if (N00.getOpcode() == ISD::FNEG) {
7156           SDValue N000 = N00.getOperand(0);
7157           if (N000.getOpcode() == ISD::FMUL) {
7158             return DAG.getNode(ISD::FMA, dl, VT,
7159                                DAG.getNode(ISD::FNEG, dl, VT,
7160                                            DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7161                                                        VT, N000.getOperand(0))),
7162                                DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7163                                            N000.getOperand(1)),
7164                                DAG.getNode(ISD::FNEG, dl, VT, N1));
7165           }
7166         }
7167       }
7169       // fold (fsub (fneg (fpext (fmul, x, y))), z)
7170       //   -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7171       if (N0.getOpcode() == ISD::FNEG) {
7172         SDValue N00 = N0.getOperand(0);
7173         if (N00.getOpcode() == ISD::FP_EXTEND) {
7174           SDValue N000 = N00.getOperand(0);
7175           if (N000.getOpcode() == ISD::FMUL) {
7176             return DAG.getNode(ISD::FMA, dl, VT,
7177                                DAG.getNode(ISD::FNEG, dl, VT,
7178                                            DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7179                                            VT, N000.getOperand(0))),
7180                                DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7181                                            N000.getOperand(1)),
7182                                DAG.getNode(ISD::FNEG, dl, VT, N1));
7183           }
7184         }
7185       }
7186     }
7188     // More folding opportunities when target permits.
7189     if (TLI.enableAggressiveFMAFusion(VT)) {
7191       // fold (fsub (fma x, y, (fmul u, v)), z)
7192       //   -> (fma x, y (fma u, v, (fneg z)))
7193       if (N0.getOpcode() == ISD::FMA &&
7194           N0.getOperand(2).getOpcode() == ISD::FMUL)
7195         return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7196                            N0.getOperand(0), N0.getOperand(1),
7197                            DAG.getNode(ISD::FMA, SDLoc(N), VT,
7198                                        N0.getOperand(2).getOperand(0),
7199                                        N0.getOperand(2).getOperand(1),
7200                                        DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7201                                                    N1)));
7203       // fold (fsub x, (fma y, z, (fmul u, v)))
7204       //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7205       if (N1.getOpcode() == ISD::FMA &&
7206           N1.getOperand(2).getOpcode() == ISD::FMUL) {
7207         SDValue N20 = N1.getOperand(2).getOperand(0);
7208         SDValue N21 = N1.getOperand(2).getOperand(1);
7209         return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7210                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7211                                        N1.getOperand(0)),
7212                            N1.getOperand(1),
7213                            DAG.getNode(ISD::FMA, SDLoc(N), VT,
7214                                        DAG.getNode(ISD::FNEG, SDLoc(N),  VT,
7215                                                    N20),
7216                                        N21, N0));
7217       }
7218     }
7219   }
7221   return SDValue();
7224 SDValue DAGCombiner::visitFMUL(SDNode *N) {
7225   SDValue N0 = N->getOperand(0);
7226   SDValue N1 = N->getOperand(1);
7227   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7228   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7229   EVT VT = N->getValueType(0);
7230   const TargetOptions &Options = DAG.getTarget().Options;
7232   // fold vector ops
7233   if (VT.isVector()) {
7234     // This just handles C1 * C2 for vectors. Other vector folds are below.
7235     SDValue FoldedVOp = SimplifyVBinOp(N);
7236     if (FoldedVOp.getNode())
7237       return FoldedVOp;
7238     // Canonicalize vector constant to RHS.
7239     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
7240         N1.getOpcode() != ISD::BUILD_VECTOR)
7241       if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
7242         if (BV0->isConstant())
7243           return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
7244   }
7246   // fold (fmul c1, c2) -> c1*c2
7247   if (N0CFP && N1CFP)
7248     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
7250   // canonicalize constant to RHS
7251   if (N0CFP && !N1CFP)
7252     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
7254   // fold (fmul A, 1.0) -> A
7255   if (N1CFP && N1CFP->isExactlyValue(1.0))
7256     return N0;
7258   if (Options.UnsafeFPMath) {
7259     // fold (fmul A, 0) -> 0
7260     if (N1CFP && N1CFP->getValueAPF().isZero())
7261       return N1;
7263     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7264     if (N0.getOpcode() == ISD::FMUL) {
7265       // Fold scalars or any vector constants (not just splats).
7266       // This fold is done in general by InstCombine, but extra fmul insts
7267       // may have been generated during lowering.
7268       SDValue N01 = N0.getOperand(1);
7269       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7270       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7271       if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7272           (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7273         SDLoc SL(N);
7274         SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7275         return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
7276       }
7277     }
7279     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7280     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7281     // during an early run of DAGCombiner can prevent folding with fmuls
7282     // inserted during lowering.
7283     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7284       SDLoc SL(N);
7285       const SDValue Two = DAG.getConstantFP(2.0, VT);
7286       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7287       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7288     }
7289   }
7291   // fold (fmul X, 2.0) -> (fadd X, X)
7292   if (N1CFP && N1CFP->isExactlyValue(+2.0))
7293     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
7295   // fold (fmul X, -1.0) -> (fneg X)
7296   if (N1CFP && N1CFP->isExactlyValue(-1.0))
7297     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7298       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
7300   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7301   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7302     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7303       // Both can be negated for free, check to see if at least one is cheaper
7304       // negated.
7305       if (LHSNeg == 2 || RHSNeg == 2)
7306         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7307                            GetNegatedExpression(N0, DAG, LegalOperations),
7308                            GetNegatedExpression(N1, DAG, LegalOperations));
7309     }
7310   }
7312   return SDValue();
7315 SDValue DAGCombiner::visitFMA(SDNode *N) {
7316   SDValue N0 = N->getOperand(0);
7317   SDValue N1 = N->getOperand(1);
7318   SDValue N2 = N->getOperand(2);
7319   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7320   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7321   EVT VT = N->getValueType(0);
7322   SDLoc dl(N);
7323   const TargetOptions &Options = DAG.getTarget().Options;
7325   // Constant fold FMA.
7326   if (isa<ConstantFPSDNode>(N0) &&
7327       isa<ConstantFPSDNode>(N1) &&
7328       isa<ConstantFPSDNode>(N2)) {
7329     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7330   }
7332   if (Options.UnsafeFPMath) {
7333     if (N0CFP && N0CFP->isZero())
7334       return N2;
7335     if (N1CFP && N1CFP->isZero())
7336       return N2;
7337   }
7338   if (N0CFP && N0CFP->isExactlyValue(1.0))
7339     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
7340   if (N1CFP && N1CFP->isExactlyValue(1.0))
7341     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
7343   // Canonicalize (fma c, x, y) -> (fma x, c, y)
7344   if (N0CFP && !N1CFP)
7345     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
7347   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
7348   if (Options.UnsafeFPMath && N1CFP &&
7349       N2.getOpcode() == ISD::FMUL &&
7350       N0 == N2.getOperand(0) &&
7351       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7352     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7353                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7354   }
7357   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
7358   if (Options.UnsafeFPMath &&
7359       N0.getOpcode() == ISD::FMUL && N1CFP &&
7360       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7361     return DAG.getNode(ISD::FMA, dl, VT,
7362                        N0.getOperand(0),
7363                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7364                        N2);
7365   }
7367   // (fma x, 1, y) -> (fadd x, y)
7368   // (fma x, -1, y) -> (fadd (fneg x), y)
7369   if (N1CFP) {
7370     if (N1CFP->isExactlyValue(1.0))
7371       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7373     if (N1CFP->isExactlyValue(-1.0) &&
7374         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7375       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
7376       AddToWorklist(RHSNeg.getNode());
7377       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7378     }
7379   }
7381   // (fma x, c, x) -> (fmul x, (c+1))
7382   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
7383     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7384                        DAG.getNode(ISD::FADD, dl, VT,
7385                                    N1, DAG.getConstantFP(1.0, VT)));
7387   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
7388   if (Options.UnsafeFPMath && N1CFP &&
7389       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7390     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7391                        DAG.getNode(ISD::FADD, dl, VT,
7392                                    N1, DAG.getConstantFP(-1.0, VT)));
7395   return SDValue();
7398 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7399   SDValue N0 = N->getOperand(0);
7400   SDValue N1 = N->getOperand(1);
7401   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7402   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7403   EVT VT = N->getValueType(0);
7404   SDLoc DL(N);
7405   const TargetOptions &Options = DAG.getTarget().Options;
7407   // fold vector ops
7408   if (VT.isVector()) {
7409     SDValue FoldedVOp = SimplifyVBinOp(N);
7410     if (FoldedVOp.getNode()) return FoldedVOp;
7411   }
7413   // fold (fdiv c1, c2) -> c1/c2
7414   if (N0CFP && N1CFP)
7415     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7417   if (Options.UnsafeFPMath) {
7418     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7419     if (N1CFP) {
7420       // Compute the reciprocal 1.0 / c2.
7421       APFloat N1APF = N1CFP->getValueAPF();
7422       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7423       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7424       // Only do the transform if the reciprocal is a legal fp immediate that
7425       // isn't too nasty (eg NaN, denormal, ...).
7426       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7427           (!LegalOperations ||
7428            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7429            // backend)... we should handle this gracefully after Legalize.
7430            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7431            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7432            TLI.isFPImmLegal(Recip, VT)))
7433         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7434                            DAG.getConstantFP(Recip, VT));
7435     }
7437     // If this FDIV is part of a reciprocal square root, it may be folded
7438     // into a target-specific square root estimate instruction.
7439     if (N1.getOpcode() == ISD::FSQRT) {
7440       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7441         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7442       }
7443     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7444                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7445       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7446         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7447         AddToWorklist(RV.getNode());
7448         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7449       }
7450     } else if (N1.getOpcode() == ISD::FP_ROUND &&
7451                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7452       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7453         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7454         AddToWorklist(RV.getNode());
7455         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7456       }
7457     } else if (N1.getOpcode() == ISD::FMUL) {
7458       // Look through an FMUL. Even though this won't remove the FDIV directly,
7459       // it's still worthwhile to get rid of the FSQRT if possible.
7460       SDValue SqrtOp;
7461       SDValue OtherOp;
7462       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7463         SqrtOp = N1.getOperand(0);
7464         OtherOp = N1.getOperand(1);
7465       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7466         SqrtOp = N1.getOperand(1);
7467         OtherOp = N1.getOperand(0);
7468       }
7469       if (SqrtOp.getNode()) {
7470         // We found a FSQRT, so try to make this fold:
7471         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7472         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7473           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7474           AddToWorklist(RV.getNode());
7475           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7476         }
7477       }
7478     }
7480     // Fold into a reciprocal estimate and multiply instead of a real divide.
7481     if (SDValue RV = BuildReciprocalEstimate(N1)) {
7482       AddToWorklist(RV.getNode());
7483       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7484     }
7485   }
7487   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7488   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7489     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7490       // Both can be negated for free, check to see if at least one is cheaper
7491       // negated.
7492       if (LHSNeg == 2 || RHSNeg == 2)
7493         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7494                            GetNegatedExpression(N0, DAG, LegalOperations),
7495                            GetNegatedExpression(N1, DAG, LegalOperations));
7496     }
7497   }
7499   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7500   // reciprocal.
7501   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
7502   // Notice that this is not always beneficial. One reason is different target
7503   // may have different costs for FDIV and FMUL, so sometimes the cost of two
7504   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
7505   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
7506   if (Options.UnsafeFPMath) {
7507     // Skip if current node is a reciprocal.
7508     if (N0CFP && N0CFP->isExactlyValue(1.0))
7509       return SDValue();
7511     SmallVector<SDNode *, 4> Users;
7512     // Find all FDIV users of the same divisor.
7513     for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
7514                               UE = N1.getNode()->use_end();
7515          UI != UE; ++UI) {
7516       SDNode *User = UI.getUse().getUser();
7517       if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
7518         Users.push_back(User);
7519     }
7521     if (TLI.combineRepeatedFPDivisors(Users.size())) {
7522       SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
7523       SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
7525       // Dividend / Divisor -> Dividend * Reciprocal
7526       for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
7527         if ((*I)->getOperand(0) != FPOne) {
7528           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
7529                                         (*I)->getOperand(0), Reciprocal);
7530           DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
7531         }
7532       }
7533       return SDValue();
7534     }
7535   }
7537   return SDValue();
7540 SDValue DAGCombiner::visitFREM(SDNode *N) {
7541   SDValue N0 = N->getOperand(0);
7542   SDValue N1 = N->getOperand(1);
7543   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7544   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7545   EVT VT = N->getValueType(0);
7547   // fold (frem c1, c2) -> fmod(c1,c2)
7548   if (N0CFP && N1CFP)
7549     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7551   return SDValue();
7554 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7555   if (DAG.getTarget().Options.UnsafeFPMath &&
7556       !TLI.isFsqrtCheap()) {
7557     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
7558     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7559       EVT VT = RV.getValueType();
7560       RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7561       AddToWorklist(RV.getNode());
7563       // Unfortunately, RV is now NaN if the input was exactly 0.
7564       // Select out this case and force the answer to 0.
7565       SDValue Zero = DAG.getConstantFP(0.0, VT);
7566       SDValue ZeroCmp =
7567         DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7568                      N->getOperand(0), Zero, ISD::SETEQ);
7569       AddToWorklist(ZeroCmp.getNode());
7570       AddToWorklist(RV.getNode());
7572       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7573                        SDLoc(N), VT, ZeroCmp, Zero, RV);
7574       return RV;
7575     }
7576   }
7577   return SDValue();
7580 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7581   SDValue N0 = N->getOperand(0);
7582   SDValue N1 = N->getOperand(1);
7583   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7584   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7585   EVT VT = N->getValueType(0);
7587   if (N0CFP && N1CFP)  // Constant fold
7588     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7590   if (N1CFP) {
7591     const APFloat& V = N1CFP->getValueAPF();
7592     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7593     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7594     if (!V.isNegative()) {
7595       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7596         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7597     } else {
7598       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7599         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7600                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7601     }
7602   }
7604   // copysign(fabs(x), y) -> copysign(x, y)
7605   // copysign(fneg(x), y) -> copysign(x, y)
7606   // copysign(copysign(x,z), y) -> copysign(x, y)
7607   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7608       N0.getOpcode() == ISD::FCOPYSIGN)
7609     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7610                        N0.getOperand(0), N1);
7612   // copysign(x, abs(y)) -> abs(x)
7613   if (N1.getOpcode() == ISD::FABS)
7614     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7616   // copysign(x, copysign(y,z)) -> copysign(x, z)
7617   if (N1.getOpcode() == ISD::FCOPYSIGN)
7618     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7619                        N0, N1.getOperand(1));
7621   // copysign(x, fp_extend(y)) -> copysign(x, y)
7622   // copysign(x, fp_round(y)) -> copysign(x, y)
7623   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7624     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7625                        N0, N1.getOperand(0));
7627   return SDValue();
7630 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7631   SDValue N0 = N->getOperand(0);
7632   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7633   EVT VT = N->getValueType(0);
7634   EVT OpVT = N0.getValueType();
7636   // fold (sint_to_fp c1) -> c1fp
7637   if (N0C &&
7638       // ...but only if the target supports immediate floating-point values
7639       (!LegalOperations ||
7640        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7641     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7643   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7644   // but UINT_TO_FP is legal on this target, try to convert.
7645   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7646       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7647     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7648     if (DAG.SignBitIsZero(N0))
7649       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7650   }
7652   // The next optimizations are desirable only if SELECT_CC can be lowered.
7653   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7654     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7655     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7656         !VT.isVector() &&
7657         (!LegalOperations ||
7658          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7659       SDValue Ops[] =
7660         { N0.getOperand(0), N0.getOperand(1),
7661           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7662           N0.getOperand(2) };
7663       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7664     }
7666     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7667     //      (select_cc x, y, 1.0, 0.0,, cc)
7668     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7669         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7670         (!LegalOperations ||
7671          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7672       SDValue Ops[] =
7673         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7674           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7675           N0.getOperand(0).getOperand(2) };
7676       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7677     }
7678   }
7680   return SDValue();
7683 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7684   SDValue N0 = N->getOperand(0);
7685   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7686   EVT VT = N->getValueType(0);
7687   EVT OpVT = N0.getValueType();
7689   // fold (uint_to_fp c1) -> c1fp
7690   if (N0C &&
7691       // ...but only if the target supports immediate floating-point values
7692       (!LegalOperations ||
7693        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7694     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7696   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7697   // but SINT_TO_FP is legal on this target, try to convert.
7698   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7699       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7700     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7701     if (DAG.SignBitIsZero(N0))
7702       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7703   }
7705   // The next optimizations are desirable only if SELECT_CC can be lowered.
7706   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7707     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7709     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7710         (!LegalOperations ||
7711          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7712       SDValue Ops[] =
7713         { N0.getOperand(0), N0.getOperand(1),
7714           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7715           N0.getOperand(2) };
7716       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7717     }
7718   }
7720   return SDValue();
7723 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7724   SDValue N0 = N->getOperand(0);
7725   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7726   EVT VT = N->getValueType(0);
7728   // fold (fp_to_sint c1fp) -> c1
7729   if (N0CFP)
7730     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7732   return SDValue();
7735 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7736   SDValue N0 = N->getOperand(0);
7737   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7738   EVT VT = N->getValueType(0);
7740   // fold (fp_to_uint c1fp) -> c1
7741   if (N0CFP)
7742     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7744   return SDValue();
7747 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7748   SDValue N0 = N->getOperand(0);
7749   SDValue N1 = N->getOperand(1);
7750   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7751   EVT VT = N->getValueType(0);
7753   // fold (fp_round c1fp) -> c1fp
7754   if (N0CFP)
7755     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7757   // fold (fp_round (fp_extend x)) -> x
7758   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7759     return N0.getOperand(0);
7761   // fold (fp_round (fp_round x)) -> (fp_round x)
7762   if (N0.getOpcode() == ISD::FP_ROUND) {
7763     // This is a value preserving truncation if both round's are.
7764     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7765                    N0.getNode()->getConstantOperandVal(1) == 1;
7766     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7767                        DAG.getIntPtrConstant(IsTrunc));
7768   }
7770   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7771   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7772     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7773                               N0.getOperand(0), N1);
7774     AddToWorklist(Tmp.getNode());
7775     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7776                        Tmp, N0.getOperand(1));
7777   }
7779   return SDValue();
7782 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7783   SDValue N0 = N->getOperand(0);
7784   EVT VT = N->getValueType(0);
7785   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7786   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7788   // fold (fp_round_inreg c1fp) -> c1fp
7789   if (N0CFP && isTypeLegal(EVT)) {
7790     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7791     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7792   }
7794   return SDValue();
7797 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7798   SDValue N0 = N->getOperand(0);
7799   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7800   EVT VT = N->getValueType(0);
7802   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7803   if (N->hasOneUse() &&
7804       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7805     return SDValue();
7807   // fold (fp_extend c1fp) -> c1fp
7808   if (N0CFP)
7809     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7811   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7812   // value of X.
7813   if (N0.getOpcode() == ISD::FP_ROUND
7814       && N0.getNode()->getConstantOperandVal(1) == 1) {
7815     SDValue In = N0.getOperand(0);
7816     if (In.getValueType() == VT) return In;
7817     if (VT.bitsLT(In.getValueType()))
7818       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7819                          In, N0.getOperand(1));
7820     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7821   }
7823   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7824   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7825        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
7826     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7827     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7828                                      LN0->getChain(),
7829                                      LN0->getBasePtr(), N0.getValueType(),
7830                                      LN0->getMemOperand());
7831     CombineTo(N, ExtLoad);
7832     CombineTo(N0.getNode(),
7833               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7834                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7835               ExtLoad.getValue(1));
7836     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7837   }
7839   return SDValue();
7842 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7843   SDValue N0 = N->getOperand(0);
7844   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7845   EVT VT = N->getValueType(0);
7847   // fold (fceil c1) -> fceil(c1)
7848   if (N0CFP)
7849     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7851   return SDValue();
7854 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7855   SDValue N0 = N->getOperand(0);
7856   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7857   EVT VT = N->getValueType(0);
7859   // fold (ftrunc c1) -> ftrunc(c1)
7860   if (N0CFP)
7861     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7863   return SDValue();
7866 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7867   SDValue N0 = N->getOperand(0);
7868   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7869   EVT VT = N->getValueType(0);
7871   // fold (ffloor c1) -> ffloor(c1)
7872   if (N0CFP)
7873     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7875   return SDValue();
7878 // FIXME: FNEG and FABS have a lot in common; refactor.
7879 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7880   SDValue N0 = N->getOperand(0);
7881   EVT VT = N->getValueType(0);
7883   if (VT.isVector()) {
7884     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7885     if (FoldedVOp.getNode()) return FoldedVOp;
7886   }
7888   // Constant fold FNEG.
7889   if (isa<ConstantFPSDNode>(N0))
7890     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7892   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7893                          &DAG.getTarget().Options))
7894     return GetNegatedExpression(N0, DAG, LegalOperations);
7896   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7897   // constant pool values.
7898   if (!TLI.isFNegFree(VT) &&
7899       N0.getOpcode() == ISD::BITCAST &&
7900       N0.getNode()->hasOneUse()) {
7901     SDValue Int = N0.getOperand(0);
7902     EVT IntVT = Int.getValueType();
7903     if (IntVT.isInteger() && !IntVT.isVector()) {
7904       APInt SignMask;
7905       if (N0.getValueType().isVector()) {
7906         // For a vector, get a mask such as 0x80... per scalar element
7907         // and splat it.
7908         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7909         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7910       } else {
7911         // For a scalar, just generate 0x80...
7912         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7913       }
7914       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7915                         DAG.getConstant(SignMask, IntVT));
7916       AddToWorklist(Int.getNode());
7917       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7918     }
7919   }
7921   // (fneg (fmul c, x)) -> (fmul -c, x)
7922   if (N0.getOpcode() == ISD::FMUL) {
7923     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7924     if (CFP1) {
7925       APFloat CVal = CFP1->getValueAPF();
7926       CVal.changeSign();
7927       if (Level >= AfterLegalizeDAG &&
7928           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7929            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7930         return DAG.getNode(
7931             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7932             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7933     }
7934   }
7936   return SDValue();
7939 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
7940   SDValue N0 = N->getOperand(0);
7941   SDValue N1 = N->getOperand(1);
7942   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7943   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7945   if (N0CFP && N1CFP) {
7946     const APFloat &C0 = N0CFP->getValueAPF();
7947     const APFloat &C1 = N1CFP->getValueAPF();
7948     return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
7949   }
7951   if (N0CFP) {
7952     EVT VT = N->getValueType(0);
7953     // Canonicalize to constant on RHS.
7954     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
7955   }
7957   return SDValue();
7960 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
7961   SDValue N0 = N->getOperand(0);
7962   SDValue N1 = N->getOperand(1);
7963   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7964   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7966   if (N0CFP && N1CFP) {
7967     const APFloat &C0 = N0CFP->getValueAPF();
7968     const APFloat &C1 = N1CFP->getValueAPF();
7969     return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
7970   }
7972   if (N0CFP) {
7973     EVT VT = N->getValueType(0);
7974     // Canonicalize to constant on RHS.
7975     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
7976   }
7978   return SDValue();
7981 SDValue DAGCombiner::visitFABS(SDNode *N) {
7982   SDValue N0 = N->getOperand(0);
7983   EVT VT = N->getValueType(0);
7985   if (VT.isVector()) {
7986     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7987     if (FoldedVOp.getNode()) return FoldedVOp;
7988   }
7990   // fold (fabs c1) -> fabs(c1)
7991   if (isa<ConstantFPSDNode>(N0))
7992     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7994   // fold (fabs (fabs x)) -> (fabs x)
7995   if (N0.getOpcode() == ISD::FABS)
7996     return N->getOperand(0);
7998   // fold (fabs (fneg x)) -> (fabs x)
7999   // fold (fabs (fcopysign x, y)) -> (fabs x)
8000   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8001     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8003   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8004   // constant pool values.
8005   if (!TLI.isFAbsFree(VT) &&
8006       N0.getOpcode() == ISD::BITCAST &&
8007       N0.getNode()->hasOneUse()) {
8008     SDValue Int = N0.getOperand(0);
8009     EVT IntVT = Int.getValueType();
8010     if (IntVT.isInteger() && !IntVT.isVector()) {
8011       APInt SignMask;
8012       if (N0.getValueType().isVector()) {
8013         // For a vector, get a mask such as 0x7f... per scalar element
8014         // and splat it.
8015         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8016         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8017       } else {
8018         // For a scalar, just generate 0x7f...
8019         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8020       }
8021       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
8022                         DAG.getConstant(SignMask, IntVT));
8023       AddToWorklist(Int.getNode());
8024       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8025     }
8026   }
8028   return SDValue();
8031 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8032   SDValue Chain = N->getOperand(0);
8033   SDValue N1 = N->getOperand(1);
8034   SDValue N2 = N->getOperand(2);
8036   // If N is a constant we could fold this into a fallthrough or unconditional
8037   // branch. However that doesn't happen very often in normal code, because
8038   // Instcombine/SimplifyCFG should have handled the available opportunities.
8039   // If we did this folding here, it would be necessary to update the
8040   // MachineBasicBlock CFG, which is awkward.
8042   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8043   // on the target.
8044   if (N1.getOpcode() == ISD::SETCC &&
8045       TLI.isOperationLegalOrCustom(ISD::BR_CC,
8046                                    N1.getOperand(0).getValueType())) {
8047     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8048                        Chain, N1.getOperand(2),
8049                        N1.getOperand(0), N1.getOperand(1), N2);
8050   }
8052   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8053       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8054        (N1.getOperand(0).hasOneUse() &&
8055         N1.getOperand(0).getOpcode() == ISD::SRL))) {
8056     SDNode *Trunc = nullptr;
8057     if (N1.getOpcode() == ISD::TRUNCATE) {
8058       // Look pass the truncate.
8059       Trunc = N1.getNode();
8060       N1 = N1.getOperand(0);
8061     }
8063     // Match this pattern so that we can generate simpler code:
8064     //
8065     //   %a = ...
8066     //   %b = and i32 %a, 2
8067     //   %c = srl i32 %b, 1
8068     //   brcond i32 %c ...
8069     //
8070     // into
8071     //
8072     //   %a = ...
8073     //   %b = and i32 %a, 2
8074     //   %c = setcc eq %b, 0
8075     //   brcond %c ...
8076     //
8077     // This applies only when the AND constant value has one bit set and the
8078     // SRL constant is equal to the log2 of the AND constant. The back-end is
8079     // smart enough to convert the result into a TEST/JMP sequence.
8080     SDValue Op0 = N1.getOperand(0);
8081     SDValue Op1 = N1.getOperand(1);
8083     if (Op0.getOpcode() == ISD::AND &&
8084         Op1.getOpcode() == ISD::Constant) {
8085       SDValue AndOp1 = Op0.getOperand(1);
8087       if (AndOp1.getOpcode() == ISD::Constant) {
8088         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8090         if (AndConst.isPowerOf2() &&
8091             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8092           SDValue SetCC =
8093             DAG.getSetCC(SDLoc(N),
8094                          getSetCCResultType(Op0.getValueType()),
8095                          Op0, DAG.getConstant(0, Op0.getValueType()),
8096                          ISD::SETNE);
8098           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
8099                                           MVT::Other, Chain, SetCC, N2);
8100           // Don't add the new BRCond into the worklist or else SimplifySelectCC
8101           // will convert it back to (X & C1) >> C2.
8102           CombineTo(N, NewBRCond, false);
8103           // Truncate is dead.
8104           if (Trunc)
8105             deleteAndRecombine(Trunc);
8106           // Replace the uses of SRL with SETCC
8107           WorklistRemover DeadNodes(*this);
8108           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8109           deleteAndRecombine(N1.getNode());
8110           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8111         }
8112       }
8113     }
8115     if (Trunc)
8116       // Restore N1 if the above transformation doesn't match.
8117       N1 = N->getOperand(1);
8118   }
8120   // Transform br(xor(x, y)) -> br(x != y)
8121   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8122   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8123     SDNode *TheXor = N1.getNode();
8124     SDValue Op0 = TheXor->getOperand(0);
8125     SDValue Op1 = TheXor->getOperand(1);
8126     if (Op0.getOpcode() == Op1.getOpcode()) {
8127       // Avoid missing important xor optimizations.
8128       SDValue Tmp = visitXOR(TheXor);
8129       if (Tmp.getNode()) {
8130         if (Tmp.getNode() != TheXor) {
8131           DEBUG(dbgs() << "\nReplacing.8 ";
8132                 TheXor->dump(&DAG);
8133                 dbgs() << "\nWith: ";
8134                 Tmp.getNode()->dump(&DAG);
8135                 dbgs() << '\n');
8136           WorklistRemover DeadNodes(*this);
8137           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8138           deleteAndRecombine(TheXor);
8139           return DAG.getNode(ISD::BRCOND, SDLoc(N),
8140                              MVT::Other, Chain, Tmp, N2);
8141         }
8143         // visitXOR has changed XOR's operands or replaced the XOR completely,
8144         // bail out.
8145         return SDValue(N, 0);
8146       }
8147     }
8149     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8150       bool Equal = false;
8151       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8152         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8153             Op0.getOpcode() == ISD::XOR) {
8154           TheXor = Op0.getNode();
8155           Equal = true;
8156         }
8158       EVT SetCCVT = N1.getValueType();
8159       if (LegalTypes)
8160         SetCCVT = getSetCCResultType(SetCCVT);
8161       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8162                                    SetCCVT,
8163                                    Op0, Op1,
8164                                    Equal ? ISD::SETEQ : ISD::SETNE);
8165       // Replace the uses of XOR with SETCC
8166       WorklistRemover DeadNodes(*this);
8167       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8168       deleteAndRecombine(N1.getNode());
8169       return DAG.getNode(ISD::BRCOND, SDLoc(N),
8170                          MVT::Other, Chain, SetCC, N2);
8171     }
8172   }
8174   return SDValue();
8177 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8178 //
8179 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
8180   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
8181   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
8183   // If N is a constant we could fold this into a fallthrough or unconditional
8184   // branch. However that doesn't happen very often in normal code, because
8185   // Instcombine/SimplifyCFG should have handled the available opportunities.
8186   // If we did this folding here, it would be necessary to update the
8187   // MachineBasicBlock CFG, which is awkward.
8189   // Use SimplifySetCC to simplify SETCC's.
8190   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
8191                                CondLHS, CondRHS, CC->get(), SDLoc(N),
8192                                false);
8193   if (Simp.getNode()) AddToWorklist(Simp.getNode());
8195   // fold to a simpler setcc
8196   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
8197     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8198                        N->getOperand(0), Simp.getOperand(2),
8199                        Simp.getOperand(0), Simp.getOperand(1),
8200                        N->getOperand(4));
8202   return SDValue();
8205 /// Return true if 'Use' is a load or a store that uses N as its base pointer
8206 /// and that N may be folded in the load / store addressing mode.
8207 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8208                                     SelectionDAG &DAG,
8209                                     const TargetLowering &TLI) {
8210   EVT VT;
8211   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
8212     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8213       return false;
8214     VT = Use->getValueType(0);
8215   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
8216     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8217       return false;
8218     VT = ST->getValue().getValueType();
8219   } else
8220     return false;
8222   TargetLowering::AddrMode AM;
8223   if (N->getOpcode() == ISD::ADD) {
8224     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8225     if (Offset)
8226       // [reg +/- imm]
8227       AM.BaseOffs = Offset->getSExtValue();
8228     else
8229       // [reg +/- reg]
8230       AM.Scale = 1;
8231   } else if (N->getOpcode() == ISD::SUB) {
8232     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8233     if (Offset)
8234       // [reg +/- imm]
8235       AM.BaseOffs = -Offset->getSExtValue();
8236     else
8237       // [reg +/- reg]
8238       AM.Scale = 1;
8239   } else
8240     return false;
8242   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8245 /// Try turning a load/store into a pre-indexed load/store when the base
8246 /// pointer is an add or subtract and it has other uses besides the load/store.
8247 /// After the transformation, the new indexed load/store has effectively folded
8248 /// the add/subtract in and all of its other uses are redirected to the
8249 /// new load/store.
8250 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8251   if (Level < AfterLegalizeDAG)
8252     return false;
8254   bool isLoad = true;
8255   SDValue Ptr;
8256   EVT VT;
8257   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8258     if (LD->isIndexed())
8259       return false;
8260     VT = LD->getMemoryVT();
8261     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8262         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8263       return false;
8264     Ptr = LD->getBasePtr();
8265   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8266     if (ST->isIndexed())
8267       return false;
8268     VT = ST->getMemoryVT();
8269     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8270         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8271       return false;
8272     Ptr = ST->getBasePtr();
8273     isLoad = false;
8274   } else {
8275     return false;
8276   }
8278   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8279   // out.  There is no reason to make this a preinc/predec.
8280   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
8281       Ptr.getNode()->hasOneUse())
8282     return false;
8284   // Ask the target to do addressing mode selection.
8285   SDValue BasePtr;
8286   SDValue Offset;
8287   ISD::MemIndexedMode AM = ISD::UNINDEXED;
8288   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8289     return false;
8291   // Backends without true r+i pre-indexed forms may need to pass a
8292   // constant base with a variable offset so that constant coercion
8293   // will work with the patterns in canonical form.
8294   bool Swapped = false;
8295   if (isa<ConstantSDNode>(BasePtr)) {
8296     std::swap(BasePtr, Offset);
8297     Swapped = true;
8298   }
8300   // Don't create a indexed load / store with zero offset.
8301   if (isa<ConstantSDNode>(Offset) &&
8302       cast<ConstantSDNode>(Offset)->isNullValue())
8303     return false;
8305   // Try turning it into a pre-indexed load / store except when:
8306   // 1) The new base ptr is a frame index.
8307   // 2) If N is a store and the new base ptr is either the same as or is a
8308   //    predecessor of the value being stored.
8309   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
8310   //    that would create a cycle.
8311   // 4) All uses are load / store ops that use it as old base ptr.
8313   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
8314   // (plus the implicit offset) to a register to preinc anyway.
8315   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8316     return false;
8318   // Check #2.
8319   if (!isLoad) {
8320     SDValue Val = cast<StoreSDNode>(N)->getValue();
8321     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
8322       return false;
8323   }
8325   // If the offset is a constant, there may be other adds of constants that
8326   // can be folded with this one. We should do this to avoid having to keep
8327   // a copy of the original base pointer.
8328   SmallVector<SDNode *, 16> OtherUses;
8329   if (isa<ConstantSDNode>(Offset))
8330     for (SDNode *Use : BasePtr.getNode()->uses()) {
8331       if (Use == Ptr.getNode())
8332         continue;
8334       if (Use->isPredecessorOf(N))
8335         continue;
8337       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8338         OtherUses.clear();
8339         break;
8340       }
8342       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8343       if (Op1.getNode() == BasePtr.getNode())
8344         std::swap(Op0, Op1);
8345       assert(Op0.getNode() == BasePtr.getNode() &&
8346              "Use of ADD/SUB but not an operand");
8348       if (!isa<ConstantSDNode>(Op1)) {
8349         OtherUses.clear();
8350         break;
8351       }
8353       // FIXME: In some cases, we can be smarter about this.
8354       if (Op1.getValueType() != Offset.getValueType()) {
8355         OtherUses.clear();
8356         break;
8357       }
8359       OtherUses.push_back(Use);
8360     }
8362   if (Swapped)
8363     std::swap(BasePtr, Offset);
8365   // Now check for #3 and #4.
8366   bool RealUse = false;
8368   // Caches for hasPredecessorHelper
8369   SmallPtrSet<const SDNode *, 32> Visited;
8370   SmallVector<const SDNode *, 16> Worklist;
8372   for (SDNode *Use : Ptr.getNode()->uses()) {
8373     if (Use == N)
8374       continue;
8375     if (N->hasPredecessorHelper(Use, Visited, Worklist))
8376       return false;
8378     // If Ptr may be folded in addressing mode of other use, then it's
8379     // not profitable to do this transformation.
8380     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
8381       RealUse = true;
8382   }
8384   if (!RealUse)
8385     return false;
8387   SDValue Result;
8388   if (isLoad)
8389     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8390                                 BasePtr, Offset, AM);
8391   else
8392     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8393                                  BasePtr, Offset, AM);
8394   ++PreIndexedNodes;
8395   ++NodesCombined;
8396   DEBUG(dbgs() << "\nReplacing.4 ";
8397         N->dump(&DAG);
8398         dbgs() << "\nWith: ";
8399         Result.getNode()->dump(&DAG);
8400         dbgs() << '\n');
8401   WorklistRemover DeadNodes(*this);
8402   if (isLoad) {
8403     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8404     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8405   } else {
8406     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8407   }
8409   // Finally, since the node is now dead, remove it from the graph.
8410   deleteAndRecombine(N);
8412   if (Swapped)
8413     std::swap(BasePtr, Offset);
8415   // Replace other uses of BasePtr that can be updated to use Ptr
8416   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8417     unsigned OffsetIdx = 1;
8418     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8419       OffsetIdx = 0;
8420     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8421            BasePtr.getNode() && "Expected BasePtr operand");
8423     // We need to replace ptr0 in the following expression:
8424     //   x0 * offset0 + y0 * ptr0 = t0
8425     // knowing that
8426     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
8427     //
8428     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8429     // indexed load/store and the expresion that needs to be re-written.
8430     //
8431     // Therefore, we have:
8432     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
8434     ConstantSDNode *CN =
8435       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
8436     int X0, X1, Y0, Y1;
8437     APInt Offset0 = CN->getAPIntValue();
8438     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8440     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8441     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8442     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8443     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8445     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8447     APInt CNV = Offset0;
8448     if (X0 < 0) CNV = -CNV;
8449     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8450     else CNV = CNV - Offset1;
8452     // We can now generate the new expression.
8453     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8454     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8456     SDValue NewUse = DAG.getNode(Opcode,
8457                                  SDLoc(OtherUses[i]),
8458                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8459     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8460     deleteAndRecombine(OtherUses[i]);
8461   }
8463   // Replace the uses of Ptr with uses of the updated base value.
8464   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8465   deleteAndRecombine(Ptr.getNode());
8467   return true;
8470 /// Try to combine a load/store with a add/sub of the base pointer node into a
8471 /// post-indexed load/store. The transformation folded the add/subtract into the
8472 /// new indexed load/store effectively and all of its uses are redirected to the
8473 /// new load/store.
8474 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
8475   if (Level < AfterLegalizeDAG)
8476     return false;
8478   bool isLoad = true;
8479   SDValue Ptr;
8480   EVT VT;
8481   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8482     if (LD->isIndexed())
8483       return false;
8484     VT = LD->getMemoryVT();
8485     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8486         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8487       return false;
8488     Ptr = LD->getBasePtr();
8489   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8490     if (ST->isIndexed())
8491       return false;
8492     VT = ST->getMemoryVT();
8493     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8494         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8495       return false;
8496     Ptr = ST->getBasePtr();
8497     isLoad = false;
8498   } else {
8499     return false;
8500   }
8502   if (Ptr.getNode()->hasOneUse())
8503     return false;
8505   for (SDNode *Op : Ptr.getNode()->uses()) {
8506     if (Op == N ||
8507         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8508       continue;
8510     SDValue BasePtr;
8511     SDValue Offset;
8512     ISD::MemIndexedMode AM = ISD::UNINDEXED;
8513     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8514       // Don't create a indexed load / store with zero offset.
8515       if (isa<ConstantSDNode>(Offset) &&
8516           cast<ConstantSDNode>(Offset)->isNullValue())
8517         continue;
8519       // Try turning it into a post-indexed load / store except when
8520       // 1) All uses are load / store ops that use it as base ptr (and
8521       //    it may be folded as addressing mmode).
8522       // 2) Op must be independent of N, i.e. Op is neither a predecessor
8523       //    nor a successor of N. Otherwise, if Op is folded that would
8524       //    create a cycle.
8526       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8527         continue;
8529       // Check for #1.
8530       bool TryNext = false;
8531       for (SDNode *Use : BasePtr.getNode()->uses()) {
8532         if (Use == Ptr.getNode())
8533           continue;
8535         // If all the uses are load / store addresses, then don't do the
8536         // transformation.
8537         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8538           bool RealUse = false;
8539           for (SDNode *UseUse : Use->uses()) {
8540             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8541               RealUse = true;
8542           }
8544           if (!RealUse) {
8545             TryNext = true;
8546             break;
8547           }
8548         }
8549       }
8551       if (TryNext)
8552         continue;
8554       // Check for #2
8555       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8556         SDValue Result = isLoad
8557           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8558                                BasePtr, Offset, AM)
8559           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8560                                 BasePtr, Offset, AM);
8561         ++PostIndexedNodes;
8562         ++NodesCombined;
8563         DEBUG(dbgs() << "\nReplacing.5 ";
8564               N->dump(&DAG);
8565               dbgs() << "\nWith: ";
8566               Result.getNode()->dump(&DAG);
8567               dbgs() << '\n');
8568         WorklistRemover DeadNodes(*this);
8569         if (isLoad) {
8570           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8571           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8572         } else {
8573           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8574         }
8576         // Finally, since the node is now dead, remove it from the graph.
8577         deleteAndRecombine(N);
8579         // Replace the uses of Use with uses of the updated base value.
8580         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8581                                       Result.getValue(isLoad ? 1 : 0));
8582         deleteAndRecombine(Op);
8583         return true;
8584       }
8585     }
8586   }
8588   return false;
8591 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8592 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8593   ISD::MemIndexedMode AM = LD->getAddressingMode();
8594   assert(AM != ISD::UNINDEXED);
8595   SDValue BP = LD->getOperand(1);
8596   SDValue Inc = LD->getOperand(2);
8598   // Some backends use TargetConstants for load offsets, but don't expect
8599   // TargetConstants in general ADD nodes. We can convert these constants into
8600   // regular Constants (if the constant is not opaque).
8601   assert((Inc.getOpcode() != ISD::TargetConstant ||
8602           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8603          "Cannot split out indexing using opaque target constants");
8604   if (Inc.getOpcode() == ISD::TargetConstant) {
8605     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8606     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8607                           ConstInc->getValueType(0));
8608   }
8610   unsigned Opc =
8611       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8612   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8615 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8616   LoadSDNode *LD  = cast<LoadSDNode>(N);
8617   SDValue Chain = LD->getChain();
8618   SDValue Ptr   = LD->getBasePtr();
8620   // If load is not volatile and there are no uses of the loaded value (and
8621   // the updated indexed value in case of indexed loads), change uses of the
8622   // chain value into uses of the chain input (i.e. delete the dead load).
8623   if (!LD->isVolatile()) {
8624     if (N->getValueType(1) == MVT::Other) {
8625       // Unindexed loads.
8626       if (!N->hasAnyUseOfValue(0)) {
8627         // It's not safe to use the two value CombineTo variant here. e.g.
8628         // v1, chain2 = load chain1, loc
8629         // v2, chain3 = load chain2, loc
8630         // v3         = add v2, c
8631         // Now we replace use of chain2 with chain1.  This makes the second load
8632         // isomorphic to the one we are deleting, and thus makes this load live.
8633         DEBUG(dbgs() << "\nReplacing.6 ";
8634               N->dump(&DAG);
8635               dbgs() << "\nWith chain: ";
8636               Chain.getNode()->dump(&DAG);
8637               dbgs() << "\n");
8638         WorklistRemover DeadNodes(*this);
8639         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8641         if (N->use_empty())
8642           deleteAndRecombine(N);
8644         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8645       }
8646     } else {
8647       // Indexed loads.
8648       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8650       // If this load has an opaque TargetConstant offset, then we cannot split
8651       // the indexing into an add/sub directly (that TargetConstant may not be
8652       // valid for a different type of node, and we cannot convert an opaque
8653       // target constant into a regular constant).
8654       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8655                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8657       if (!N->hasAnyUseOfValue(0) &&
8658           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8659         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8660         SDValue Index;
8661         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8662           Index = SplitIndexingFromLoad(LD);
8663           // Try to fold the base pointer arithmetic into subsequent loads and
8664           // stores.
8665           AddUsersToWorklist(N);
8666         } else
8667           Index = DAG.getUNDEF(N->getValueType(1));
8668         DEBUG(dbgs() << "\nReplacing.7 ";
8669               N->dump(&DAG);
8670               dbgs() << "\nWith: ";
8671               Undef.getNode()->dump(&DAG);
8672               dbgs() << " and 2 other values\n");
8673         WorklistRemover DeadNodes(*this);
8674         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8675         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8676         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8677         deleteAndRecombine(N);
8678         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8679       }
8680     }
8681   }
8683   // If this load is directly stored, replace the load value with the stored
8684   // value.
8685   // TODO: Handle store large -> read small portion.
8686   // TODO: Handle TRUNCSTORE/LOADEXT
8687   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8688     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8689       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8690       if (PrevST->getBasePtr() == Ptr &&
8691           PrevST->getValue().getValueType() == N->getValueType(0))
8692       return CombineTo(N, Chain.getOperand(1), Chain);
8693     }
8694   }
8696   // Try to infer better alignment information than the load already has.
8697   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8698     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8699       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8700         SDValue NewLoad =
8701                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8702                               LD->getValueType(0),
8703                               Chain, Ptr, LD->getPointerInfo(),
8704                               LD->getMemoryVT(),
8705                               LD->isVolatile(), LD->isNonTemporal(),
8706                               LD->isInvariant(), Align, LD->getAAInfo());
8707         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8708       }
8709     }
8710   }
8712   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
8713                                                   : DAG.getSubtarget().useAA();
8714 #ifndef NDEBUG
8715   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8716       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8717     UseAA = false;
8718 #endif
8719   if (UseAA && LD->isUnindexed()) {
8720     // Walk up chain skipping non-aliasing memory nodes.
8721     SDValue BetterChain = FindBetterChain(N, Chain);
8723     // If there is a better chain.
8724     if (Chain != BetterChain) {
8725       SDValue ReplLoad;
8727       // Replace the chain to void dependency.
8728       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8729         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8730                                BetterChain, Ptr, LD->getMemOperand());
8731       } else {
8732         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8733                                   LD->getValueType(0),
8734                                   BetterChain, Ptr, LD->getMemoryVT(),
8735                                   LD->getMemOperand());
8736       }
8738       // Create token factor to keep old chain connected.
8739       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8740                                   MVT::Other, Chain, ReplLoad.getValue(1));
8742       // Make sure the new and old chains are cleaned up.
8743       AddToWorklist(Token.getNode());
8745       // Replace uses with load result and token factor. Don't add users
8746       // to work list.
8747       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8748     }
8749   }
8751   // Try transforming N to an indexed load.
8752   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8753     return SDValue(N, 0);
8755   // Try to slice up N to more direct loads if the slices are mapped to
8756   // different register banks or pairing can take place.
8757   if (SliceUpLoad(N))
8758     return SDValue(N, 0);
8760   return SDValue();
8763 namespace {
8764 /// \brief Helper structure used to slice a load in smaller loads.
8765 /// Basically a slice is obtained from the following sequence:
8766 /// Origin = load Ty1, Base
8767 /// Shift = srl Ty1 Origin, CstTy Amount
8768 /// Inst = trunc Shift to Ty2
8769 ///
8770 /// Then, it will be rewriten into:
8771 /// Slice = load SliceTy, Base + SliceOffset
8772 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8773 ///
8774 /// SliceTy is deduced from the number of bits that are actually used to
8775 /// build Inst.
8776 struct LoadedSlice {
8777   /// \brief Helper structure used to compute the cost of a slice.
8778   struct Cost {
8779     /// Are we optimizing for code size.
8780     bool ForCodeSize;
8781     /// Various cost.
8782     unsigned Loads;
8783     unsigned Truncates;
8784     unsigned CrossRegisterBanksCopies;
8785     unsigned ZExts;
8786     unsigned Shift;
8788     Cost(bool ForCodeSize = false)
8789         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8790           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8792     /// \brief Get the cost of one isolated slice.
8793     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8794         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8795           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8796       EVT TruncType = LS.Inst->getValueType(0);
8797       EVT LoadedType = LS.getLoadedType();
8798       if (TruncType != LoadedType &&
8799           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8800         ZExts = 1;
8801     }
8803     /// \brief Account for slicing gain in the current cost.
8804     /// Slicing provide a few gains like removing a shift or a
8805     /// truncate. This method allows to grow the cost of the original
8806     /// load with the gain from this slice.
8807     void addSliceGain(const LoadedSlice &LS) {
8808       // Each slice saves a truncate.
8809       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8810       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8811                               LS.Inst->getOperand(0).getValueType()))
8812         ++Truncates;
8813       // If there is a shift amount, this slice gets rid of it.
8814       if (LS.Shift)
8815         ++Shift;
8816       // If this slice can merge a cross register bank copy, account for it.
8817       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8818         ++CrossRegisterBanksCopies;
8819     }
8821     Cost &operator+=(const Cost &RHS) {
8822       Loads += RHS.Loads;
8823       Truncates += RHS.Truncates;
8824       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8825       ZExts += RHS.ZExts;
8826       Shift += RHS.Shift;
8827       return *this;
8828     }
8830     bool operator==(const Cost &RHS) const {
8831       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8832              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8833              ZExts == RHS.ZExts && Shift == RHS.Shift;
8834     }
8836     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8838     bool operator<(const Cost &RHS) const {
8839       // Assume cross register banks copies are as expensive as loads.
8840       // FIXME: Do we want some more target hooks?
8841       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8842       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8843       // Unless we are optimizing for code size, consider the
8844       // expensive operation first.
8845       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8846         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8847       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8848              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8849     }
8851     bool operator>(const Cost &RHS) const { return RHS < *this; }
8853     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8855     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8856   };
8857   // The last instruction that represent the slice. This should be a
8858   // truncate instruction.
8859   SDNode *Inst;
8860   // The original load instruction.
8861   LoadSDNode *Origin;
8862   // The right shift amount in bits from the original load.
8863   unsigned Shift;
8864   // The DAG from which Origin came from.
8865   // This is used to get some contextual information about legal types, etc.
8866   SelectionDAG *DAG;
8868   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8869               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8870       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8872   LoadedSlice(const LoadedSlice &LS)
8873       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8875   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8876   /// \return Result is \p BitWidth and has used bits set to 1 and
8877   ///         not used bits set to 0.
8878   APInt getUsedBits() const {
8879     // Reproduce the trunc(lshr) sequence:
8880     // - Start from the truncated value.
8881     // - Zero extend to the desired bit width.
8882     // - Shift left.
8883     assert(Origin && "No original load to compare against.");
8884     unsigned BitWidth = Origin->getValueSizeInBits(0);
8885     assert(Inst && "This slice is not bound to an instruction");
8886     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8887            "Extracted slice is bigger than the whole type!");
8888     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8889     UsedBits.setAllBits();
8890     UsedBits = UsedBits.zext(BitWidth);
8891     UsedBits <<= Shift;
8892     return UsedBits;
8893   }
8895   /// \brief Get the size of the slice to be loaded in bytes.
8896   unsigned getLoadedSize() const {
8897     unsigned SliceSize = getUsedBits().countPopulation();
8898     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8899     return SliceSize / 8;
8900   }
8902   /// \brief Get the type that will be loaded for this slice.
8903   /// Note: This may not be the final type for the slice.
8904   EVT getLoadedType() const {
8905     assert(DAG && "Missing context");
8906     LLVMContext &Ctxt = *DAG->getContext();
8907     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8908   }
8910   /// \brief Get the alignment of the load used for this slice.
8911   unsigned getAlignment() const {
8912     unsigned Alignment = Origin->getAlignment();
8913     unsigned Offset = getOffsetFromBase();
8914     if (Offset != 0)
8915       Alignment = MinAlign(Alignment, Alignment + Offset);
8916     return Alignment;
8917   }
8919   /// \brief Check if this slice can be rewritten with legal operations.
8920   bool isLegal() const {
8921     // An invalid slice is not legal.
8922     if (!Origin || !Inst || !DAG)
8923       return false;
8925     // Offsets are for indexed load only, we do not handle that.
8926     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8927       return false;
8929     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8931     // Check that the type is legal.
8932     EVT SliceType = getLoadedType();
8933     if (!TLI.isTypeLegal(SliceType))
8934       return false;
8936     // Check that the load is legal for this type.
8937     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8938       return false;
8940     // Check that the offset can be computed.
8941     // 1. Check its type.
8942     EVT PtrType = Origin->getBasePtr().getValueType();
8943     if (PtrType == MVT::Untyped || PtrType.isExtended())
8944       return false;
8946     // 2. Check that it fits in the immediate.
8947     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8948       return false;
8950     // 3. Check that the computation is legal.
8951     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8952       return false;
8954     // Check that the zext is legal if it needs one.
8955     EVT TruncateType = Inst->getValueType(0);
8956     if (TruncateType != SliceType &&
8957         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8958       return false;
8960     return true;
8961   }
8963   /// \brief Get the offset in bytes of this slice in the original chunk of
8964   /// bits.
8965   /// \pre DAG != nullptr.
8966   uint64_t getOffsetFromBase() const {
8967     assert(DAG && "Missing context.");
8968     bool IsBigEndian =
8969         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8970     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8971     uint64_t Offset = Shift / 8;
8972     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8973     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8974            "The size of the original loaded type is not a multiple of a"
8975            " byte.");
8976     // If Offset is bigger than TySizeInBytes, it means we are loading all
8977     // zeros. This should have been optimized before in the process.
8978     assert(TySizeInBytes > Offset &&
8979            "Invalid shift amount for given loaded size");
8980     if (IsBigEndian)
8981       Offset = TySizeInBytes - Offset - getLoadedSize();
8982     return Offset;
8983   }
8985   /// \brief Generate the sequence of instructions to load the slice
8986   /// represented by this object and redirect the uses of this slice to
8987   /// this new sequence of instructions.
8988   /// \pre this->Inst && this->Origin are valid Instructions and this
8989   /// object passed the legal check: LoadedSlice::isLegal returned true.
8990   /// \return The last instruction of the sequence used to load the slice.
8991   SDValue loadSlice() const {
8992     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8993     const SDValue &OldBaseAddr = Origin->getBasePtr();
8994     SDValue BaseAddr = OldBaseAddr;
8995     // Get the offset in that chunk of bytes w.r.t. the endianess.
8996     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8997     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8998     if (Offset) {
8999       // BaseAddr = BaseAddr + Offset.
9000       EVT ArithType = BaseAddr.getValueType();
9001       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
9002                               DAG->getConstant(Offset, ArithType));
9003     }
9005     // Create the type of the loaded slice according to its size.
9006     EVT SliceType = getLoadedType();
9008     // Create the load for the slice.
9009     SDValue LastInst = DAG->getLoad(
9010         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9011         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9012         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9013     // If the final type is not the same as the loaded type, this means that
9014     // we have to pad with zero. Create a zero extend for that.
9015     EVT FinalType = Inst->getValueType(0);
9016     if (SliceType != FinalType)
9017       LastInst =
9018           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9019     return LastInst;
9020   }
9022   /// \brief Check if this slice can be merged with an expensive cross register
9023   /// bank copy. E.g.,
9024   /// i = load i32
9025   /// f = bitcast i32 i to float
9026   bool canMergeExpensiveCrossRegisterBankCopy() const {
9027     if (!Inst || !Inst->hasOneUse())
9028       return false;
9029     SDNode *Use = *Inst->use_begin();
9030     if (Use->getOpcode() != ISD::BITCAST)
9031       return false;
9032     assert(DAG && "Missing context");
9033     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9034     EVT ResVT = Use->getValueType(0);
9035     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9036     const TargetRegisterClass *ArgRC =
9037         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9038     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9039       return false;
9041     // At this point, we know that we perform a cross-register-bank copy.
9042     // Check if it is expensive.
9043     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9044     // Assume bitcasts are cheap, unless both register classes do not
9045     // explicitly share a common sub class.
9046     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9047       return false;
9049     // Check if it will be merged with the load.
9050     // 1. Check the alignment constraint.
9051     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9052         ResVT.getTypeForEVT(*DAG->getContext()));
9054     if (RequiredAlignment > getAlignment())
9055       return false;
9057     // 2. Check that the load is a legal operation for that type.
9058     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9059       return false;
9061     // 3. Check that we do not have a zext in the way.
9062     if (Inst->getValueType(0) != getLoadedType())
9063       return false;
9065     return true;
9066   }
9067 };
9070 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9071 /// \p UsedBits looks like 0..0 1..1 0..0.
9072 static bool areUsedBitsDense(const APInt &UsedBits) {
9073   // If all the bits are one, this is dense!
9074   if (UsedBits.isAllOnesValue())
9075     return true;
9077   // Get rid of the unused bits on the right.
9078   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9079   // Get rid of the unused bits on the left.
9080   if (NarrowedUsedBits.countLeadingZeros())
9081     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9082   // Check that the chunk of bits is completely used.
9083   return NarrowedUsedBits.isAllOnesValue();
9086 /// \brief Check whether or not \p First and \p Second are next to each other
9087 /// in memory. This means that there is no hole between the bits loaded
9088 /// by \p First and the bits loaded by \p Second.
9089 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9090                                      const LoadedSlice &Second) {
9091   assert(First.Origin == Second.Origin && First.Origin &&
9092          "Unable to match different memory origins.");
9093   APInt UsedBits = First.getUsedBits();
9094   assert((UsedBits & Second.getUsedBits()) == 0 &&
9095          "Slices are not supposed to overlap.");
9096   UsedBits |= Second.getUsedBits();
9097   return areUsedBitsDense(UsedBits);
9100 /// \brief Adjust the \p GlobalLSCost according to the target
9101 /// paring capabilities and the layout of the slices.
9102 /// \pre \p GlobalLSCost should account for at least as many loads as
9103 /// there is in the slices in \p LoadedSlices.
9104 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9105                                  LoadedSlice::Cost &GlobalLSCost) {
9106   unsigned NumberOfSlices = LoadedSlices.size();
9107   // If there is less than 2 elements, no pairing is possible.
9108   if (NumberOfSlices < 2)
9109     return;
9111   // Sort the slices so that elements that are likely to be next to each
9112   // other in memory are next to each other in the list.
9113   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9114             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9115     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9116     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9117   });
9118   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9119   // First (resp. Second) is the first (resp. Second) potentially candidate
9120   // to be placed in a paired load.
9121   const LoadedSlice *First = nullptr;
9122   const LoadedSlice *Second = nullptr;
9123   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9124                 // Set the beginning of the pair.
9125                                                            First = Second) {
9127     Second = &LoadedSlices[CurrSlice];
9129     // If First is NULL, it means we start a new pair.
9130     // Get to the next slice.
9131     if (!First)
9132       continue;
9134     EVT LoadedType = First->getLoadedType();
9136     // If the types of the slices are different, we cannot pair them.
9137     if (LoadedType != Second->getLoadedType())
9138       continue;
9140     // Check if the target supplies paired loads for this type.
9141     unsigned RequiredAlignment = 0;
9142     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9143       // move to the next pair, this type is hopeless.
9144       Second = nullptr;
9145       continue;
9146     }
9147     // Check if we meet the alignment requirement.
9148     if (RequiredAlignment > First->getAlignment())
9149       continue;
9151     // Check that both loads are next to each other in memory.
9152     if (!areSlicesNextToEachOther(*First, *Second))
9153       continue;
9155     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9156     --GlobalLSCost.Loads;
9157     // Move to the next pair.
9158     Second = nullptr;
9159   }
9162 /// \brief Check the profitability of all involved LoadedSlice.
9163 /// Currently, it is considered profitable if there is exactly two
9164 /// involved slices (1) which are (2) next to each other in memory, and
9165 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9166 ///
9167 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9168 /// the elements themselves.
9169 ///
9170 /// FIXME: When the cost model will be mature enough, we can relax
9171 /// constraints (1) and (2).
9172 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9173                                 const APInt &UsedBits, bool ForCodeSize) {
9174   unsigned NumberOfSlices = LoadedSlices.size();
9175   if (StressLoadSlicing)
9176     return NumberOfSlices > 1;
9178   // Check (1).
9179   if (NumberOfSlices != 2)
9180     return false;
9182   // Check (2).
9183   if (!areUsedBitsDense(UsedBits))
9184     return false;
9186   // Check (3).
9187   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9188   // The original code has one big load.
9189   OrigCost.Loads = 1;
9190   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9191     const LoadedSlice &LS = LoadedSlices[CurrSlice];
9192     // Accumulate the cost of all the slices.
9193     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9194     GlobalSlicingCost += SliceCost;
9196     // Account as cost in the original configuration the gain obtained
9197     // with the current slices.
9198     OrigCost.addSliceGain(LS);
9199   }
9201   // If the target supports paired load, adjust the cost accordingly.
9202   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9203   return OrigCost > GlobalSlicingCost;
9206 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9207 /// operations, split it in the various pieces being extracted.
9208 ///
9209 /// This sort of thing is introduced by SROA.
9210 /// This slicing takes care not to insert overlapping loads.
9211 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
9212 bool DAGCombiner::SliceUpLoad(SDNode *N) {
9213   if (Level < AfterLegalizeDAG)
9214     return false;
9216   LoadSDNode *LD = cast<LoadSDNode>(N);
9217   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9218       !LD->getValueType(0).isInteger())
9219     return false;
9221   // Keep track of already used bits to detect overlapping values.
9222   // In that case, we will just abort the transformation.
9223   APInt UsedBits(LD->getValueSizeInBits(0), 0);
9225   SmallVector<LoadedSlice, 4> LoadedSlices;
9227   // Check if this load is used as several smaller chunks of bits.
9228   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9229   // of computation for each trunc.
9230   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9231        UI != UIEnd; ++UI) {
9232     // Skip the uses of the chain.
9233     if (UI.getUse().getResNo() != 0)
9234       continue;
9236     SDNode *User = *UI;
9237     unsigned Shift = 0;
9239     // Check if this is a trunc(lshr).
9240     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9241         isa<ConstantSDNode>(User->getOperand(1))) {
9242       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9243       User = *User->use_begin();
9244     }
9246     // At this point, User is a Truncate, iff we encountered, trunc or
9247     // trunc(lshr).
9248     if (User->getOpcode() != ISD::TRUNCATE)
9249       return false;
9251     // The width of the type must be a power of 2 and greater than 8-bits.
9252     // Otherwise the load cannot be represented in LLVM IR.
9253     // Moreover, if we shifted with a non-8-bits multiple, the slice
9254     // will be across several bytes. We do not support that.
9255     unsigned Width = User->getValueSizeInBits(0);
9256     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9257       return 0;
9259     // Build the slice for this chain of computations.
9260     LoadedSlice LS(User, LD, Shift, &DAG);
9261     APInt CurrentUsedBits = LS.getUsedBits();
9263     // Check if this slice overlaps with another.
9264     if ((CurrentUsedBits & UsedBits) != 0)
9265       return false;
9266     // Update the bits used globally.
9267     UsedBits |= CurrentUsedBits;
9269     // Check if the new slice would be legal.
9270     if (!LS.isLegal())
9271       return false;
9273     // Record the slice.
9274     LoadedSlices.push_back(LS);
9275   }
9277   // Abort slicing if it does not seem to be profitable.
9278   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9279     return false;
9281   ++SlicedLoads;
9283   // Rewrite each chain to use an independent load.
9284   // By construction, each chain can be represented by a unique load.
9286   // Prepare the argument for the new token factor for all the slices.
9287   SmallVector<SDValue, 8> ArgChains;
9288   for (SmallVectorImpl<LoadedSlice>::const_iterator
9289            LSIt = LoadedSlices.begin(),
9290            LSItEnd = LoadedSlices.end();
9291        LSIt != LSItEnd; ++LSIt) {
9292     SDValue SliceInst = LSIt->loadSlice();
9293     CombineTo(LSIt->Inst, SliceInst, true);
9294     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9295       SliceInst = SliceInst.getOperand(0);
9296     assert(SliceInst->getOpcode() == ISD::LOAD &&
9297            "It takes more than a zext to get to the loaded slice!!");
9298     ArgChains.push_back(SliceInst.getValue(1));
9299   }
9301   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
9302                               ArgChains);
9303   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9304   return true;
9307 /// Check to see if V is (and load (ptr), imm), where the load is having
9308 /// specific bytes cleared out.  If so, return the byte size being masked out
9309 /// and the shift amount.
9310 static std::pair<unsigned, unsigned>
9311 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9312   std::pair<unsigned, unsigned> Result(0, 0);
9314   // Check for the structure we're looking for.
9315   if (V->getOpcode() != ISD::AND ||
9316       !isa<ConstantSDNode>(V->getOperand(1)) ||
9317       !ISD::isNormalLoad(V->getOperand(0).getNode()))
9318     return Result;
9320   // Check the chain and pointer.
9321   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
9322   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
9324   // The store should be chained directly to the load or be an operand of a
9325   // tokenfactor.
9326   if (LD == Chain.getNode())
9327     ; // ok.
9328   else if (Chain->getOpcode() != ISD::TokenFactor)
9329     return Result; // Fail.
9330   else {
9331     bool isOk = false;
9332     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9333       if (Chain->getOperand(i).getNode() == LD) {
9334         isOk = true;
9335         break;
9336       }
9337     if (!isOk) return Result;
9338   }
9340   // This only handles simple types.
9341   if (V.getValueType() != MVT::i16 &&
9342       V.getValueType() != MVT::i32 &&
9343       V.getValueType() != MVT::i64)
9344     return Result;
9346   // Check the constant mask.  Invert it so that the bits being masked out are
9347   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
9348   // follow the sign bit for uniformity.
9349   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
9350   unsigned NotMaskLZ = countLeadingZeros(NotMask);
9351   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
9352   unsigned NotMaskTZ = countTrailingZeros(NotMask);
9353   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
9354   if (NotMaskLZ == 64) return Result;  // All zero mask.
9356   // See if we have a continuous run of bits.  If so, we have 0*1+0*
9357   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
9358     return Result;
9360   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9361   if (V.getValueType() != MVT::i64 && NotMaskLZ)
9362     NotMaskLZ -= 64-V.getValueSizeInBits();
9364   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9365   switch (MaskedBytes) {
9366   case 1:
9367   case 2:
9368   case 4: break;
9369   default: return Result; // All one mask, or 5-byte mask.
9370   }
9372   // Verify that the first bit starts at a multiple of mask so that the access
9373   // is aligned the same as the access width.
9374   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
9376   Result.first = MaskedBytes;
9377   Result.second = NotMaskTZ/8;
9378   return Result;
9382 /// Check to see if IVal is something that provides a value as specified by
9383 /// MaskInfo. If so, replace the specified store with a narrower store of
9384 /// truncated IVal.
9385 static SDNode *
9386 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9387                                 SDValue IVal, StoreSDNode *St,
9388                                 DAGCombiner *DC) {
9389   unsigned NumBytes = MaskInfo.first;
9390   unsigned ByteShift = MaskInfo.second;
9391   SelectionDAG &DAG = DC->getDAG();
9393   // Check to see if IVal is all zeros in the part being masked in by the 'or'
9394   // that uses this.  If not, this is not a replacement.
9395   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9396                                   ByteShift*8, (ByteShift+NumBytes)*8);
9397   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
9399   // Check that it is legal on the target to do this.  It is legal if the new
9400   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9401   // legalization.
9402   MVT VT = MVT::getIntegerVT(NumBytes*8);
9403   if (!DC->isTypeLegal(VT))
9404     return nullptr;
9406   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
9407   // shifted by ByteShift and truncated down to NumBytes.
9408   if (ByteShift)
9409     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
9410                        DAG.getConstant(ByteShift*8,
9411                                     DC->getShiftAmountTy(IVal.getValueType())));
9413   // Figure out the offset for the store and the alignment of the access.
9414   unsigned StOffset;
9415   unsigned NewAlign = St->getAlignment();
9417   if (DAG.getTargetLoweringInfo().isLittleEndian())
9418     StOffset = ByteShift;
9419   else
9420     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
9422   SDValue Ptr = St->getBasePtr();
9423   if (StOffset) {
9424     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
9425                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9426     NewAlign = MinAlign(NewAlign, StOffset);
9427   }
9429   // Truncate down to the new size.
9430   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
9432   ++OpsNarrowed;
9433   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
9434                       St->getPointerInfo().getWithOffset(StOffset),
9435                       false, false, NewAlign).getNode();
9439 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9440 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9441 /// narrowing the load and store if it would end up being a win for performance
9442 /// or code size.
9443 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9444   StoreSDNode *ST  = cast<StoreSDNode>(N);
9445   if (ST->isVolatile())
9446     return SDValue();
9448   SDValue Chain = ST->getChain();
9449   SDValue Value = ST->getValue();
9450   SDValue Ptr   = ST->getBasePtr();
9451   EVT VT = Value.getValueType();
9453   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9454     return SDValue();
9456   unsigned Opc = Value.getOpcode();
9458   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9459   // is a byte mask indicating a consecutive number of bytes, check to see if
9460   // Y is known to provide just those bytes.  If so, we try to replace the
9461   // load + replace + store sequence with a single (narrower) store, which makes
9462   // the load dead.
9463   if (Opc == ISD::OR) {
9464     std::pair<unsigned, unsigned> MaskedLoad;
9465     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9466     if (MaskedLoad.first)
9467       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9468                                                   Value.getOperand(1), ST,this))
9469         return SDValue(NewST, 0);
9471     // Or is commutative, so try swapping X and Y.
9472     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9473     if (MaskedLoad.first)
9474       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9475                                                   Value.getOperand(0), ST,this))
9476         return SDValue(NewST, 0);
9477   }
9479   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9480       Value.getOperand(1).getOpcode() != ISD::Constant)
9481     return SDValue();
9483   SDValue N0 = Value.getOperand(0);
9484   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9485       Chain == SDValue(N0.getNode(), 1)) {
9486     LoadSDNode *LD = cast<LoadSDNode>(N0);
9487     if (LD->getBasePtr() != Ptr ||
9488         LD->getPointerInfo().getAddrSpace() !=
9489         ST->getPointerInfo().getAddrSpace())
9490       return SDValue();
9492     // Find the type to narrow it the load / op / store to.
9493     SDValue N1 = Value.getOperand(1);
9494     unsigned BitWidth = N1.getValueSizeInBits();
9495     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9496     if (Opc == ISD::AND)
9497       Imm ^= APInt::getAllOnesValue(BitWidth);
9498     if (Imm == 0 || Imm.isAllOnesValue())
9499       return SDValue();
9500     unsigned ShAmt = Imm.countTrailingZeros();
9501     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9502     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9503     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9504     // The narrowing should be profitable, the load/store operation should be
9505     // legal (or custom) and the store size should be equal to the NewVT width.
9506     while (NewBW < BitWidth &&
9507            (NewVT.getStoreSizeInBits() != NewBW ||
9508             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
9509             !TLI.isNarrowingProfitable(VT, NewVT))) {
9510       NewBW = NextPowerOf2(NewBW);
9511       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9512     }
9513     if (NewBW >= BitWidth)
9514       return SDValue();
9516     // If the lsb changed does not start at the type bitwidth boundary,
9517     // start at the previous one.
9518     if (ShAmt % NewBW)
9519       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9520     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9521                                    std::min(BitWidth, ShAmt + NewBW));
9522     if ((Imm & Mask) == Imm) {
9523       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9524       if (Opc == ISD::AND)
9525         NewImm ^= APInt::getAllOnesValue(NewBW);
9526       uint64_t PtrOff = ShAmt / 8;
9527       // For big endian targets, we need to adjust the offset to the pointer to
9528       // load the correct bytes.
9529       if (TLI.isBigEndian())
9530         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9532       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9533       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9534       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9535         return SDValue();
9537       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9538                                    Ptr.getValueType(), Ptr,
9539                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
9540       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9541                                   LD->getChain(), NewPtr,
9542                                   LD->getPointerInfo().getWithOffset(PtrOff),
9543                                   LD->isVolatile(), LD->isNonTemporal(),
9544                                   LD->isInvariant(), NewAlign,
9545                                   LD->getAAInfo());
9546       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9547                                    DAG.getConstant(NewImm, NewVT));
9548       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9549                                    NewVal, NewPtr,
9550                                    ST->getPointerInfo().getWithOffset(PtrOff),
9551                                    false, false, NewAlign);
9553       AddToWorklist(NewPtr.getNode());
9554       AddToWorklist(NewLD.getNode());
9555       AddToWorklist(NewVal.getNode());
9556       WorklistRemover DeadNodes(*this);
9557       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9558       ++OpsNarrowed;
9559       return NewST;
9560     }
9561   }
9563   return SDValue();
9566 /// For a given floating point load / store pair, if the load value isn't used
9567 /// by any other operations, then consider transforming the pair to integer
9568 /// load / store operations if the target deems the transformation profitable.
9569 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9570   StoreSDNode *ST  = cast<StoreSDNode>(N);
9571   SDValue Chain = ST->getChain();
9572   SDValue Value = ST->getValue();
9573   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9574       Value.hasOneUse() &&
9575       Chain == SDValue(Value.getNode(), 1)) {
9576     LoadSDNode *LD = cast<LoadSDNode>(Value);
9577     EVT VT = LD->getMemoryVT();
9578     if (!VT.isFloatingPoint() ||
9579         VT != ST->getMemoryVT() ||
9580         LD->isNonTemporal() ||
9581         ST->isNonTemporal() ||
9582         LD->getPointerInfo().getAddrSpace() != 0 ||
9583         ST->getPointerInfo().getAddrSpace() != 0)
9584       return SDValue();
9586     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9587     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9588         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9589         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9590         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9591       return SDValue();
9593     unsigned LDAlign = LD->getAlignment();
9594     unsigned STAlign = ST->getAlignment();
9595     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9596     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9597     if (LDAlign < ABIAlign || STAlign < ABIAlign)
9598       return SDValue();
9600     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9601                                 LD->getChain(), LD->getBasePtr(),
9602                                 LD->getPointerInfo(),
9603                                 false, false, false, LDAlign);
9605     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9606                                  NewLD, ST->getBasePtr(),
9607                                  ST->getPointerInfo(),
9608                                  false, false, STAlign);
9610     AddToWorklist(NewLD.getNode());
9611     AddToWorklist(NewST.getNode());
9612     WorklistRemover DeadNodes(*this);
9613     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9614     ++LdStFP2Int;
9615     return NewST;
9616   }
9618   return SDValue();
9621 /// Helper struct to parse and store a memory address as base + index + offset.
9622 /// We ignore sign extensions when it is safe to do so.
9623 /// The following two expressions are not equivalent. To differentiate we need
9624 /// to store whether there was a sign extension involved in the index
9625 /// computation.
9626 ///  (load (i64 add (i64 copyfromreg %c)
9627 ///                 (i64 signextend (add (i8 load %index)
9628 ///                                      (i8 1))))
9629 /// vs
9630 ///
9631 /// (load (i64 add (i64 copyfromreg %c)
9632 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
9633 ///                                         (i32 1)))))
9634 struct BaseIndexOffset {
9635   SDValue Base;
9636   SDValue Index;
9637   int64_t Offset;
9638   bool IsIndexSignExt;
9640   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9642   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9643                   bool IsIndexSignExt) :
9644     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9646   bool equalBaseIndex(const BaseIndexOffset &Other) {
9647     return Other.Base == Base && Other.Index == Index &&
9648       Other.IsIndexSignExt == IsIndexSignExt;
9649   }
9651   /// Parses tree in Ptr for base, index, offset addresses.
9652   static BaseIndexOffset match(SDValue Ptr) {
9653     bool IsIndexSignExt = false;
9655     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9656     // instruction, then it could be just the BASE or everything else we don't
9657     // know how to handle. Just use Ptr as BASE and give up.
9658     if (Ptr->getOpcode() != ISD::ADD)
9659       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9661     // We know that we have at least an ADD instruction. Try to pattern match
9662     // the simple case of BASE + OFFSET.
9663     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9664       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9665       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9666                               IsIndexSignExt);
9667     }
9669     // Inside a loop the current BASE pointer is calculated using an ADD and a
9670     // MUL instruction. In this case Ptr is the actual BASE pointer.
9671     // (i64 add (i64 %array_ptr)
9672     //          (i64 mul (i64 %induction_var)
9673     //                   (i64 %element_size)))
9674     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9675       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9677     // Look at Base + Index + Offset cases.
9678     SDValue Base = Ptr->getOperand(0);
9679     SDValue IndexOffset = Ptr->getOperand(1);
9681     // Skip signextends.
9682     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9683       IndexOffset = IndexOffset->getOperand(0);
9684       IsIndexSignExt = true;
9685     }
9687     // Either the case of Base + Index (no offset) or something else.
9688     if (IndexOffset->getOpcode() != ISD::ADD)
9689       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9691     // Now we have the case of Base + Index + offset.
9692     SDValue Index = IndexOffset->getOperand(0);
9693     SDValue Offset = IndexOffset->getOperand(1);
9695     if (!isa<ConstantSDNode>(Offset))
9696       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9698     // Ignore signextends.
9699     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9700       Index = Index->getOperand(0);
9701       IsIndexSignExt = true;
9702     } else IsIndexSignExt = false;
9704     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9705     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9706   }
9707 };
9709 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9710 /// is located in a sequence of memory operations connected by a chain.
9711 struct MemOpLink {
9712   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9713     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9714   // Ptr to the mem node.
9715   LSBaseSDNode *MemNode;
9716   // Offset from the base ptr.
9717   int64_t OffsetFromBase;
9718   // What is the sequence number of this mem node.
9719   // Lowest mem operand in the DAG starts at zero.
9720   unsigned SequenceNum;
9721 };
9723 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9724   EVT MemVT = St->getMemoryVT();
9725   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9726   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9727     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9729   // Don't merge vectors into wider inputs.
9730   if (MemVT.isVector() || !MemVT.isSimple())
9731     return false;
9733   // Perform an early exit check. Do not bother looking at stored values that
9734   // are not constants or loads.
9735   SDValue StoredVal = St->getValue();
9736   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9737   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9738       !IsLoadSrc)
9739     return false;
9741   // Only look at ends of store sequences.
9742   SDValue Chain = SDValue(St, 0);
9743   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9744     return false;
9746   // This holds the base pointer, index, and the offset in bytes from the base
9747   // pointer.
9748   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9750   // We must have a base and an offset.
9751   if (!BasePtr.Base.getNode())
9752     return false;
9754   // Do not handle stores to undef base pointers.
9755   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9756     return false;
9758   // Save the LoadSDNodes that we find in the chain.
9759   // We need to make sure that these nodes do not interfere with
9760   // any of the store nodes.
9761   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9763   // Save the StoreSDNodes that we find in the chain.
9764   SmallVector<MemOpLink, 8> StoreNodes;
9766   // Walk up the chain and look for nodes with offsets from the same
9767   // base pointer. Stop when reaching an instruction with a different kind
9768   // or instruction which has a different base pointer.
9769   unsigned Seq = 0;
9770   StoreSDNode *Index = St;
9771   while (Index) {
9772     // If the chain has more than one use, then we can't reorder the mem ops.
9773     if (Index != St && !SDValue(Index, 0)->hasOneUse())
9774       break;
9776     // Find the base pointer and offset for this memory node.
9777     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9779     // Check that the base pointer is the same as the original one.
9780     if (!Ptr.equalBaseIndex(BasePtr))
9781       break;
9783     // Check that the alignment is the same.
9784     if (Index->getAlignment() != St->getAlignment())
9785       break;
9787     // The memory operands must not be volatile.
9788     if (Index->isVolatile() || Index->isIndexed())
9789       break;
9791     // No truncation.
9792     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9793       if (St->isTruncatingStore())
9794         break;
9796     // The stored memory type must be the same.
9797     if (Index->getMemoryVT() != MemVT)
9798       break;
9800     // We do not allow unaligned stores because we want to prevent overriding
9801     // stores.
9802     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9803       break;
9805     // We found a potential memory operand to merge.
9806     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9808     // Find the next memory operand in the chain. If the next operand in the
9809     // chain is a store then move up and continue the scan with the next
9810     // memory operand. If the next operand is a load save it and use alias
9811     // information to check if it interferes with anything.
9812     SDNode *NextInChain = Index->getChain().getNode();
9813     while (1) {
9814       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9815         // We found a store node. Use it for the next iteration.
9816         Index = STn;
9817         break;
9818       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9819         if (Ldn->isVolatile()) {
9820           Index = nullptr;
9821           break;
9822         }
9824         // Save the load node for later. Continue the scan.
9825         AliasLoadNodes.push_back(Ldn);
9826         NextInChain = Ldn->getChain().getNode();
9827         continue;
9828       } else {
9829         Index = nullptr;
9830         break;
9831       }
9832     }
9833   }
9835   // Check if there is anything to merge.
9836   if (StoreNodes.size() < 2)
9837     return false;
9839   // Sort the memory operands according to their distance from the base pointer.
9840   std::sort(StoreNodes.begin(), StoreNodes.end(),
9841             [](MemOpLink LHS, MemOpLink RHS) {
9842     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9843            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9844             LHS.SequenceNum > RHS.SequenceNum);
9845   });
9847   // Scan the memory operations on the chain and find the first non-consecutive
9848   // store memory address.
9849   unsigned LastConsecutiveStore = 0;
9850   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9851   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9853     // Check that the addresses are consecutive starting from the second
9854     // element in the list of stores.
9855     if (i > 0) {
9856       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9857       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9858         break;
9859     }
9861     bool Alias = false;
9862     // Check if this store interferes with any of the loads that we found.
9863     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9864       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9865         Alias = true;
9866         break;
9867       }
9868     // We found a load that alias with this store. Stop the sequence.
9869     if (Alias)
9870       break;
9872     // Mark this node as useful.
9873     LastConsecutiveStore = i;
9874   }
9876   // The node with the lowest store address.
9877   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9879   // Store the constants into memory as one consecutive store.
9880   if (!IsLoadSrc) {
9881     unsigned LastLegalType = 0;
9882     unsigned LastLegalVectorType = 0;
9883     bool NonZero = false;
9884     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9885       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9886       SDValue StoredVal = St->getValue();
9888       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9889         NonZero |= !C->isNullValue();
9890       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9891         NonZero |= !C->getConstantFPValue()->isNullValue();
9892       } else {
9893         // Non-constant.
9894         break;
9895       }
9897       // Find a legal type for the constant store.
9898       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9899       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9900       if (TLI.isTypeLegal(StoreTy))
9901         LastLegalType = i+1;
9902       // Or check whether a truncstore is legal.
9903       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9904                TargetLowering::TypePromoteInteger) {
9905         EVT LegalizedStoredValueTy =
9906           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9907         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9908           LastLegalType = i+1;
9909       }
9911       // Find a legal type for the vector store.
9912       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9913       if (TLI.isTypeLegal(Ty))
9914         LastLegalVectorType = i + 1;
9915     }
9917     // We only use vectors if the constant is known to be zero and the
9918     // function is not marked with the noimplicitfloat attribute.
9919     if (NonZero || NoVectors)
9920       LastLegalVectorType = 0;
9922     // Check if we found a legal integer type to store.
9923     if (LastLegalType == 0 && LastLegalVectorType == 0)
9924       return false;
9926     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9927     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9929     // Make sure we have something to merge.
9930     if (NumElem < 2)
9931       return false;
9933     unsigned EarliestNodeUsed = 0;
9934     for (unsigned i=0; i < NumElem; ++i) {
9935       // Find a chain for the new wide-store operand. Notice that some
9936       // of the store nodes that we found may not be selected for inclusion
9937       // in the wide store. The chain we use needs to be the chain of the
9938       // earliest store node which is *used* and replaced by the wide store.
9939       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9940         EarliestNodeUsed = i;
9941     }
9943     // The earliest Node in the DAG.
9944     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9945     SDLoc DL(StoreNodes[0].MemNode);
9947     SDValue StoredVal;
9948     if (UseVector) {
9949       // Find a legal type for the vector store.
9950       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9951       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9952       StoredVal = DAG.getConstant(0, Ty);
9953     } else {
9954       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9955       APInt StoreInt(StoreBW, 0);
9957       // Construct a single integer constant which is made of the smaller
9958       // constant inputs.
9959       bool IsLE = TLI.isLittleEndian();
9960       for (unsigned i = 0; i < NumElem ; ++i) {
9961         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9962         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9963         SDValue Val = St->getValue();
9964         StoreInt<<=ElementSizeBytes*8;
9965         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9966           StoreInt|=C->getAPIntValue().zext(StoreBW);
9967         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9968           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9969         } else {
9970           llvm_unreachable("Invalid constant element type");
9971         }
9972       }
9974       // Create the new Load and Store operations.
9975       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9976       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9977     }
9979     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9980                                     FirstInChain->getBasePtr(),
9981                                     FirstInChain->getPointerInfo(),
9982                                     false, false,
9983                                     FirstInChain->getAlignment());
9985     // Replace the first store with the new store
9986     CombineTo(EarliestOp, NewStore);
9987     // Erase all other stores.
9988     for (unsigned i = 0; i < NumElem ; ++i) {
9989       if (StoreNodes[i].MemNode == EarliestOp)
9990         continue;
9991       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9992       // ReplaceAllUsesWith will replace all uses that existed when it was
9993       // called, but graph optimizations may cause new ones to appear. For
9994       // example, the case in pr14333 looks like
9995       //
9996       //  St's chain -> St -> another store -> X
9997       //
9998       // And the only difference from St to the other store is the chain.
9999       // When we change it's chain to be St's chain they become identical,
10000       // get CSEed and the net result is that X is now a use of St.
10001       // Since we know that St is redundant, just iterate.
10002       while (!St->use_empty())
10003         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10004       deleteAndRecombine(St);
10005     }
10007     return true;
10008   }
10010   // Below we handle the case of multiple consecutive stores that
10011   // come from multiple consecutive loads. We merge them into a single
10012   // wide load and a single wide store.
10014   // Look for load nodes which are used by the stored values.
10015   SmallVector<MemOpLink, 8> LoadNodes;
10017   // Find acceptable loads. Loads need to have the same chain (token factor),
10018   // must not be zext, volatile, indexed, and they must be consecutive.
10019   BaseIndexOffset LdBasePtr;
10020   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10021     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10022     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10023     if (!Ld) break;
10025     // Loads must only have one use.
10026     if (!Ld->hasNUsesOfValue(1, 0))
10027       break;
10029     // Check that the alignment is the same as the stores.
10030     if (Ld->getAlignment() != St->getAlignment())
10031       break;
10033     // The memory operands must not be volatile.
10034     if (Ld->isVolatile() || Ld->isIndexed())
10035       break;
10037     // We do not accept ext loads.
10038     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10039       break;
10041     // The stored memory type must be the same.
10042     if (Ld->getMemoryVT() != MemVT)
10043       break;
10045     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10046     // If this is not the first ptr that we check.
10047     if (LdBasePtr.Base.getNode()) {
10048       // The base ptr must be the same.
10049       if (!LdPtr.equalBaseIndex(LdBasePtr))
10050         break;
10051     } else {
10052       // Check that all other base pointers are the same as this one.
10053       LdBasePtr = LdPtr;
10054     }
10056     // We found a potential memory operand to merge.
10057     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10058   }
10060   if (LoadNodes.size() < 2)
10061     return false;
10063   // If we have load/store pair instructions and we only have two values,
10064   // don't bother.
10065   unsigned RequiredAlignment;
10066   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10067       St->getAlignment() >= RequiredAlignment)
10068     return false;
10070   // Scan the memory operations on the chain and find the first non-consecutive
10071   // load memory address. These variables hold the index in the store node
10072   // array.
10073   unsigned LastConsecutiveLoad = 0;
10074   // This variable refers to the size and not index in the array.
10075   unsigned LastLegalVectorType = 0;
10076   unsigned LastLegalIntegerType = 0;
10077   StartAddress = LoadNodes[0].OffsetFromBase;
10078   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10079   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10080     // All loads much share the same chain.
10081     if (LoadNodes[i].MemNode->getChain() != FirstChain)
10082       break;
10084     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10085     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10086       break;
10087     LastConsecutiveLoad = i;
10089     // Find a legal type for the vector store.
10090     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10091     if (TLI.isTypeLegal(StoreTy))
10092       LastLegalVectorType = i + 1;
10094     // Find a legal type for the integer store.
10095     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10096     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10097     if (TLI.isTypeLegal(StoreTy))
10098       LastLegalIntegerType = i + 1;
10099     // Or check whether a truncstore and extload is legal.
10100     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10101              TargetLowering::TypePromoteInteger) {
10102       EVT LegalizedStoredValueTy =
10103         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10104       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10105           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10106           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10107           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
10108         LastLegalIntegerType = i+1;
10109     }
10110   }
10112   // Only use vector types if the vector type is larger than the integer type.
10113   // If they are the same, use integers.
10114   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
10115   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10117   // We add +1 here because the LastXXX variables refer to location while
10118   // the NumElem refers to array/index size.
10119   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10120   NumElem = std::min(LastLegalType, NumElem);
10122   if (NumElem < 2)
10123     return false;
10125   // The earliest Node in the DAG.
10126   unsigned EarliestNodeUsed = 0;
10127   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10128   for (unsigned i=1; i<NumElem; ++i) {
10129     // Find a chain for the new wide-store operand. Notice that some
10130     // of the store nodes that we found may not be selected for inclusion
10131     // in the wide store. The chain we use needs to be the chain of the
10132     // earliest store node which is *used* and replaced by the wide store.
10133     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
10134       EarliestNodeUsed = i;
10135   }
10137   // Find if it is better to use vectors or integers to load and store
10138   // to memory.
10139   EVT JointMemOpVT;
10140   if (UseVectorTy) {
10141     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10142   } else {
10143     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10144     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10145   }
10147   SDLoc LoadDL(LoadNodes[0].MemNode);
10148   SDLoc StoreDL(StoreNodes[0].MemNode);
10150   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10151   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10152                                 FirstLoad->getChain(),
10153                                 FirstLoad->getBasePtr(),
10154                                 FirstLoad->getPointerInfo(),
10155                                 false, false, false,
10156                                 FirstLoad->getAlignment());
10158   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
10159                                   FirstInChain->getBasePtr(),
10160                                   FirstInChain->getPointerInfo(), false, false,
10161                                   FirstInChain->getAlignment());
10163   // Replace one of the loads with the new load.
10164   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10165   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10166                                 SDValue(NewLoad.getNode(), 1));
10168   // Remove the rest of the load chains.
10169   for (unsigned i = 1; i < NumElem ; ++i) {
10170     // Replace all chain users of the old load nodes with the chain of the new
10171     // load node.
10172     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
10173     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10174   }
10176   // Replace the first store with the new store.
10177   CombineTo(EarliestOp, NewStore);
10178   // Erase all other stores.
10179   for (unsigned i = 0; i < NumElem ; ++i) {
10180     // Remove all Store nodes.
10181     if (StoreNodes[i].MemNode == EarliestOp)
10182       continue;
10183     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10184     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
10185     deleteAndRecombine(St);
10186   }
10188   return true;
10191 SDValue DAGCombiner::visitSTORE(SDNode *N) {
10192   StoreSDNode *ST  = cast<StoreSDNode>(N);
10193   SDValue Chain = ST->getChain();
10194   SDValue Value = ST->getValue();
10195   SDValue Ptr   = ST->getBasePtr();
10197   // If this is a store of a bit convert, store the input value if the
10198   // resultant store does not need a higher alignment than the original.
10199   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
10200       ST->isUnindexed()) {
10201     unsigned OrigAlign = ST->getAlignment();
10202     EVT SVT = Value.getOperand(0).getValueType();
10203     unsigned Align = TLI.getDataLayout()->
10204       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
10205     if (Align <= OrigAlign &&
10206         ((!LegalOperations && !ST->isVolatile()) ||
10207          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
10208       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
10209                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
10210                           ST->isNonTemporal(), OrigAlign,
10211                           ST->getAAInfo());
10212   }
10214   // Turn 'store undef, Ptr' -> nothing.
10215   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10216     return Chain;
10218   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
10219   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
10220     // NOTE: If the original store is volatile, this transform must not increase
10221     // the number of stores.  For example, on x86-32 an f64 can be stored in one
10222     // processor operation but an i64 (which is not legal) requires two.  So the
10223     // transform should not be done in this case.
10224     if (Value.getOpcode() != ISD::TargetConstantFP) {
10225       SDValue Tmp;
10226       switch (CFP->getSimpleValueType(0).SimpleTy) {
10227       default: llvm_unreachable("Unknown FP type");
10228       case MVT::f16:    // We don't do this for these yet.
10229       case MVT::f80:
10230       case MVT::f128:
10231       case MVT::ppcf128:
10232         break;
10233       case MVT::f32:
10234         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
10235             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10236           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
10237                               bitcastToAPInt().getZExtValue(), MVT::i32);
10238           return DAG.getStore(Chain, SDLoc(N), Tmp,
10239                               Ptr, ST->getMemOperand());
10240         }
10241         break;
10242       case MVT::f64:
10243         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
10244              !ST->isVolatile()) ||
10245             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
10246           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
10247                                 getZExtValue(), MVT::i64);
10248           return DAG.getStore(Chain, SDLoc(N), Tmp,
10249                               Ptr, ST->getMemOperand());
10250         }
10252         if (!ST->isVolatile() &&
10253             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10254           // Many FP stores are not made apparent until after legalize, e.g. for
10255           // argument passing.  Since this is so common, custom legalize the
10256           // 64-bit integer store into two 32-bit stores.
10257           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
10258           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10259           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
10260           if (TLI.isBigEndian()) std::swap(Lo, Hi);
10262           unsigned Alignment = ST->getAlignment();
10263           bool isVolatile = ST->isVolatile();
10264           bool isNonTemporal = ST->isNonTemporal();
10265           AAMDNodes AAInfo = ST->getAAInfo();
10267           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
10268                                      Ptr, ST->getPointerInfo(),
10269                                      isVolatile, isNonTemporal,
10270                                      ST->getAlignment(), AAInfo);
10271           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
10272                             DAG.getConstant(4, Ptr.getValueType()));
10273           Alignment = MinAlign(Alignment, 4U);
10274           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
10275                                      Ptr, ST->getPointerInfo().getWithOffset(4),
10276                                      isVolatile, isNonTemporal,
10277                                      Alignment, AAInfo);
10278           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10279                              St0, St1);
10280         }
10282         break;
10283       }
10284     }
10285   }
10287   // Try to infer better alignment information than the store already has.
10288   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
10289     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10290       if (Align > ST->getAlignment())
10291         return DAG.getTruncStore(Chain, SDLoc(N), Value,
10292                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
10293                                  ST->isVolatile(), ST->isNonTemporal(), Align,
10294                                  ST->getAAInfo());
10295     }
10296   }
10298   // Try transforming a pair floating point load / store ops to integer
10299   // load / store ops.
10300   SDValue NewST = TransformFPLoadStorePair(N);
10301   if (NewST.getNode())
10302     return NewST;
10304   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10305                                                   : DAG.getSubtarget().useAA();
10306 #ifndef NDEBUG
10307   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10308       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10309     UseAA = false;
10310 #endif
10311   if (UseAA && ST->isUnindexed()) {
10312     // Walk up chain skipping non-aliasing memory nodes.
10313     SDValue BetterChain = FindBetterChain(N, Chain);
10315     // If there is a better chain.
10316     if (Chain != BetterChain) {
10317       SDValue ReplStore;
10319       // Replace the chain to avoid dependency.
10320       if (ST->isTruncatingStore()) {
10321         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
10322                                       ST->getMemoryVT(), ST->getMemOperand());
10323       } else {
10324         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
10325                                  ST->getMemOperand());
10326       }
10328       // Create token to keep both nodes around.
10329       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10330                                   MVT::Other, Chain, ReplStore);
10332       // Make sure the new and old chains are cleaned up.
10333       AddToWorklist(Token.getNode());
10335       // Don't add users to work list.
10336       return CombineTo(N, Token, false);
10337     }
10338   }
10340   // Try transforming N to an indexed store.
10341   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10342     return SDValue(N, 0);
10344   // FIXME: is there such a thing as a truncating indexed store?
10345   if (ST->isTruncatingStore() && ST->isUnindexed() &&
10346       Value.getValueType().isInteger()) {
10347     // See if we can simplify the input to this truncstore with knowledge that
10348     // only the low bits are being used.  For example:
10349     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
10350     SDValue Shorter =
10351       GetDemandedBits(Value,
10352                       APInt::getLowBitsSet(
10353                         Value.getValueType().getScalarType().getSizeInBits(),
10354                         ST->getMemoryVT().getScalarType().getSizeInBits()));
10355     AddToWorklist(Value.getNode());
10356     if (Shorter.getNode())
10357       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
10358                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
10360     // Otherwise, see if we can simplify the operation with
10361     // SimplifyDemandedBits, which only works if the value has a single use.
10362     if (SimplifyDemandedBits(Value,
10363                         APInt::getLowBitsSet(
10364                           Value.getValueType().getScalarType().getSizeInBits(),
10365                           ST->getMemoryVT().getScalarType().getSizeInBits())))
10366       return SDValue(N, 0);
10367   }
10369   // If this is a load followed by a store to the same location, then the store
10370   // is dead/noop.
10371   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
10372     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
10373         ST->isUnindexed() && !ST->isVolatile() &&
10374         // There can't be any side effects between the load and store, such as
10375         // a call or store.
10376         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
10377       // The store is dead, remove it.
10378       return Chain;
10379     }
10380   }
10382   // If this is a store followed by a store with the same value to the same
10383   // location, then the store is dead/noop.
10384   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
10385     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
10386         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
10387         ST1->isUnindexed() && !ST1->isVolatile()) {
10388       // The store is dead, remove it.
10389       return Chain;
10390     }
10391   }
10393   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
10394   // truncating store.  We can do this even if this is already a truncstore.
10395   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
10396       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
10397       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
10398                             ST->getMemoryVT())) {
10399     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
10400                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
10401   }
10403   // Only perform this optimization before the types are legal, because we
10404   // don't want to perform this optimization on every DAGCombine invocation.
10405   if (!LegalTypes) {
10406     bool EverChanged = false;
10408     do {
10409       // There can be multiple store sequences on the same chain.
10410       // Keep trying to merge store sequences until we are unable to do so
10411       // or until we merge the last store on the chain.
10412       bool Changed = MergeConsecutiveStores(ST);
10413       EverChanged |= Changed;
10414       if (!Changed) break;
10415     } while (ST->getOpcode() != ISD::DELETED_NODE);
10417     if (EverChanged)
10418       return SDValue(N, 0);
10419   }
10421   return ReduceLoadOpStoreWidth(N);
10424 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
10425   SDValue InVec = N->getOperand(0);
10426   SDValue InVal = N->getOperand(1);
10427   SDValue EltNo = N->getOperand(2);
10428   SDLoc dl(N);
10430   // If the inserted element is an UNDEF, just use the input vector.
10431   if (InVal.getOpcode() == ISD::UNDEF)
10432     return InVec;
10434   EVT VT = InVec.getValueType();
10436   // If we can't generate a legal BUILD_VECTOR, exit
10437   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10438     return SDValue();
10440   // Check that we know which element is being inserted
10441   if (!isa<ConstantSDNode>(EltNo))
10442     return SDValue();
10443   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10445   // Canonicalize insert_vector_elt dag nodes.
10446   // Example:
10447   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10448   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10449   //
10450   // Do this only if the child insert_vector node has one use; also
10451   // do this only if indices are both constants and Idx1 < Idx0.
10452   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10453       && isa<ConstantSDNode>(InVec.getOperand(2))) {
10454     unsigned OtherElt =
10455       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10456     if (Elt < OtherElt) {
10457       // Swap nodes.
10458       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10459                                   InVec.getOperand(0), InVal, EltNo);
10460       AddToWorklist(NewOp.getNode());
10461       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10462                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10463     }
10464   }
10466   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10467   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
10468   // vector elements.
10469   SmallVector<SDValue, 8> Ops;
10470   // Do not combine these two vectors if the output vector will not replace
10471   // the input vector.
10472   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
10473     Ops.append(InVec.getNode()->op_begin(),
10474                InVec.getNode()->op_end());
10475   } else if (InVec.getOpcode() == ISD::UNDEF) {
10476     unsigned NElts = VT.getVectorNumElements();
10477     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10478   } else {
10479     return SDValue();
10480   }
10482   // Insert the element
10483   if (Elt < Ops.size()) {
10484     // All the operands of BUILD_VECTOR must have the same type;
10485     // we enforce that here.
10486     EVT OpVT = Ops[0].getValueType();
10487     if (InVal.getValueType() != OpVT)
10488       InVal = OpVT.bitsGT(InVal.getValueType()) ?
10489                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10490                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10491     Ops[Elt] = InVal;
10492   }
10494   // Return the new vector
10495   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
10498 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10499     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10500   EVT ResultVT = EVE->getValueType(0);
10501   EVT VecEltVT = InVecVT.getVectorElementType();
10502   unsigned Align = OriginalLoad->getAlignment();
10503   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10504       VecEltVT.getTypeForEVT(*DAG.getContext()));
10506   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10507     return SDValue();
10509   Align = NewAlign;
10511   SDValue NewPtr = OriginalLoad->getBasePtr();
10512   SDValue Offset;
10513   EVT PtrType = NewPtr.getValueType();
10514   MachinePointerInfo MPI;
10515   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10516     int Elt = ConstEltNo->getZExtValue();
10517     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10518     if (TLI.isBigEndian())
10519       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10520     Offset = DAG.getConstant(PtrOff, PtrType);
10521     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10522   } else {
10523     Offset = DAG.getNode(
10524         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10525         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10526     if (TLI.isBigEndian())
10527       Offset = DAG.getNode(
10528           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10529           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10530     MPI = OriginalLoad->getPointerInfo();
10531   }
10532   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10534   // The replacement we need to do here is a little tricky: we need to
10535   // replace an extractelement of a load with a load.
10536   // Use ReplaceAllUsesOfValuesWith to do the replacement.
10537   // Note that this replacement assumes that the extractvalue is the only
10538   // use of the load; that's okay because we don't want to perform this
10539   // transformation in other cases anyway.
10540   SDValue Load;
10541   SDValue Chain;
10542   if (ResultVT.bitsGT(VecEltVT)) {
10543     // If the result type of vextract is wider than the load, then issue an
10544     // extending load instead.
10545     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
10546                                                   VecEltVT)
10547                                    ? ISD::ZEXTLOAD
10548                                    : ISD::EXTLOAD;
10549     Load = DAG.getExtLoad(
10550         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10551         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10552         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10553     Chain = Load.getValue(1);
10554   } else {
10555     Load = DAG.getLoad(
10556         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10557         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10558         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10559     Chain = Load.getValue(1);
10560     if (ResultVT.bitsLT(VecEltVT))
10561       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10562     else
10563       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10564   }
10565   WorklistRemover DeadNodes(*this);
10566   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10567   SDValue To[] = { Load, Chain };
10568   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10569   // Since we're explicitly calling ReplaceAllUses, add the new node to the
10570   // worklist explicitly as well.
10571   AddToWorklist(Load.getNode());
10572   AddUsersToWorklist(Load.getNode()); // Add users too
10573   // Make sure to revisit this node to clean it up; it will usually be dead.
10574   AddToWorklist(EVE);
10575   ++OpsNarrowed;
10576   return SDValue(EVE, 0);
10579 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10580   // (vextract (scalar_to_vector val, 0) -> val
10581   SDValue InVec = N->getOperand(0);
10582   EVT VT = InVec.getValueType();
10583   EVT NVT = N->getValueType(0);
10585   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10586     // Check if the result type doesn't match the inserted element type. A
10587     // SCALAR_TO_VECTOR may truncate the inserted element and the
10588     // EXTRACT_VECTOR_ELT may widen the extracted vector.
10589     SDValue InOp = InVec.getOperand(0);
10590     if (InOp.getValueType() != NVT) {
10591       assert(InOp.getValueType().isInteger() && NVT.isInteger());
10592       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10593     }
10594     return InOp;
10595   }
10597   SDValue EltNo = N->getOperand(1);
10598   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10600   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10601   // We only perform this optimization before the op legalization phase because
10602   // we may introduce new vector instructions which are not backed by TD
10603   // patterns. For example on AVX, extracting elements from a wide vector
10604   // without using extract_subvector. However, if we can find an underlying
10605   // scalar value, then we can always use that.
10606   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10607       && ConstEltNo) {
10608     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10609     int NumElem = VT.getVectorNumElements();
10610     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10611     // Find the new index to extract from.
10612     int OrigElt = SVOp->getMaskElt(Elt);
10614     // Extracting an undef index is undef.
10615     if (OrigElt == -1)
10616       return DAG.getUNDEF(NVT);
10618     // Select the right vector half to extract from.
10619     SDValue SVInVec;
10620     if (OrigElt < NumElem) {
10621       SVInVec = InVec->getOperand(0);
10622     } else {
10623       SVInVec = InVec->getOperand(1);
10624       OrigElt -= NumElem;
10625     }
10627     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10628       SDValue InOp = SVInVec.getOperand(OrigElt);
10629       if (InOp.getValueType() != NVT) {
10630         assert(InOp.getValueType().isInteger() && NVT.isInteger());
10631         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10632       }
10634       return InOp;
10635     }
10637     // FIXME: We should handle recursing on other vector shuffles and
10638     // scalar_to_vector here as well.
10640     if (!LegalOperations) {
10641       EVT IndexTy = TLI.getVectorIdxTy();
10642       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10643                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
10644     }
10645   }
10647   bool BCNumEltsChanged = false;
10648   EVT ExtVT = VT.getVectorElementType();
10649   EVT LVT = ExtVT;
10651   // If the result of load has to be truncated, then it's not necessarily
10652   // profitable.
10653   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10654     return SDValue();
10656   if (InVec.getOpcode() == ISD::BITCAST) {
10657     // Don't duplicate a load with other uses.
10658     if (!InVec.hasOneUse())
10659       return SDValue();
10661     EVT BCVT = InVec.getOperand(0).getValueType();
10662     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10663       return SDValue();
10664     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10665       BCNumEltsChanged = true;
10666     InVec = InVec.getOperand(0);
10667     ExtVT = BCVT.getVectorElementType();
10668   }
10670   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10671   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10672       ISD::isNormalLoad(InVec.getNode()) &&
10673       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10674     SDValue Index = N->getOperand(1);
10675     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10676       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10677                                                            OrigLoad);
10678   }
10680   // Perform only after legalization to ensure build_vector / vector_shuffle
10681   // optimizations have already been done.
10682   if (!LegalOperations) return SDValue();
10684   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10685   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10686   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10688   if (ConstEltNo) {
10689     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10691     LoadSDNode *LN0 = nullptr;
10692     const ShuffleVectorSDNode *SVN = nullptr;
10693     if (ISD::isNormalLoad(InVec.getNode())) {
10694       LN0 = cast<LoadSDNode>(InVec);
10695     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10696                InVec.getOperand(0).getValueType() == ExtVT &&
10697                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10698       // Don't duplicate a load with other uses.
10699       if (!InVec.hasOneUse())
10700         return SDValue();
10702       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10703     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10704       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10705       // =>
10706       // (load $addr+1*size)
10708       // Don't duplicate a load with other uses.
10709       if (!InVec.hasOneUse())
10710         return SDValue();
10712       // If the bit convert changed the number of elements, it is unsafe
10713       // to examine the mask.
10714       if (BCNumEltsChanged)
10715         return SDValue();
10717       // Select the input vector, guarding against out of range extract vector.
10718       unsigned NumElems = VT.getVectorNumElements();
10719       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10720       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10722       if (InVec.getOpcode() == ISD::BITCAST) {
10723         // Don't duplicate a load with other uses.
10724         if (!InVec.hasOneUse())
10725           return SDValue();
10727         InVec = InVec.getOperand(0);
10728       }
10729       if (ISD::isNormalLoad(InVec.getNode())) {
10730         LN0 = cast<LoadSDNode>(InVec);
10731         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10732         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10733       }
10734     }
10736     // Make sure we found a non-volatile load and the extractelement is
10737     // the only use.
10738     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10739       return SDValue();
10741     // If Idx was -1 above, Elt is going to be -1, so just return undef.
10742     if (Elt == -1)
10743       return DAG.getUNDEF(LVT);
10745     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10746   }
10748   return SDValue();
10751 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10752 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10753   // We perform this optimization post type-legalization because
10754   // the type-legalizer often scalarizes integer-promoted vectors.
10755   // Performing this optimization before may create bit-casts which
10756   // will be type-legalized to complex code sequences.
10757   // We perform this optimization only before the operation legalizer because we
10758   // may introduce illegal operations.
10759   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10760     return SDValue();
10762   unsigned NumInScalars = N->getNumOperands();
10763   SDLoc dl(N);
10764   EVT VT = N->getValueType(0);
10766   // Check to see if this is a BUILD_VECTOR of a bunch of values
10767   // which come from any_extend or zero_extend nodes. If so, we can create
10768   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10769   // optimizations. We do not handle sign-extend because we can't fill the sign
10770   // using shuffles.
10771   EVT SourceType = MVT::Other;
10772   bool AllAnyExt = true;
10774   for (unsigned i = 0; i != NumInScalars; ++i) {
10775     SDValue In = N->getOperand(i);
10776     // Ignore undef inputs.
10777     if (In.getOpcode() == ISD::UNDEF) continue;
10779     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10780     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10782     // Abort if the element is not an extension.
10783     if (!ZeroExt && !AnyExt) {
10784       SourceType = MVT::Other;
10785       break;
10786     }
10788     // The input is a ZeroExt or AnyExt. Check the original type.
10789     EVT InTy = In.getOperand(0).getValueType();
10791     // Check that all of the widened source types are the same.
10792     if (SourceType == MVT::Other)
10793       // First time.
10794       SourceType = InTy;
10795     else if (InTy != SourceType) {
10796       // Multiple income types. Abort.
10797       SourceType = MVT::Other;
10798       break;
10799     }
10801     // Check if all of the extends are ANY_EXTENDs.
10802     AllAnyExt &= AnyExt;
10803   }
10805   // In order to have valid types, all of the inputs must be extended from the
10806   // same source type and all of the inputs must be any or zero extend.
10807   // Scalar sizes must be a power of two.
10808   EVT OutScalarTy = VT.getScalarType();
10809   bool ValidTypes = SourceType != MVT::Other &&
10810                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10811                  isPowerOf2_32(SourceType.getSizeInBits());
10813   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10814   // turn into a single shuffle instruction.
10815   if (!ValidTypes)
10816     return SDValue();
10818   bool isLE = TLI.isLittleEndian();
10819   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10820   assert(ElemRatio > 1 && "Invalid element size ratio");
10821   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10822                                DAG.getConstant(0, SourceType);
10824   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10825   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10827   // Populate the new build_vector
10828   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10829     SDValue Cast = N->getOperand(i);
10830     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10831             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10832             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10833     SDValue In;
10834     if (Cast.getOpcode() == ISD::UNDEF)
10835       In = DAG.getUNDEF(SourceType);
10836     else
10837       In = Cast->getOperand(0);
10838     unsigned Index = isLE ? (i * ElemRatio) :
10839                             (i * ElemRatio + (ElemRatio - 1));
10841     assert(Index < Ops.size() && "Invalid index");
10842     Ops[Index] = In;
10843   }
10845   // The type of the new BUILD_VECTOR node.
10846   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10847   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10848          "Invalid vector size");
10849   // Check if the new vector type is legal.
10850   if (!isTypeLegal(VecVT)) return SDValue();
10852   // Make the new BUILD_VECTOR.
10853   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10855   // The new BUILD_VECTOR node has the potential to be further optimized.
10856   AddToWorklist(BV.getNode());
10857   // Bitcast to the desired type.
10858   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10861 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10862   EVT VT = N->getValueType(0);
10864   unsigned NumInScalars = N->getNumOperands();
10865   SDLoc dl(N);
10867   EVT SrcVT = MVT::Other;
10868   unsigned Opcode = ISD::DELETED_NODE;
10869   unsigned NumDefs = 0;
10871   for (unsigned i = 0; i != NumInScalars; ++i) {
10872     SDValue In = N->getOperand(i);
10873     unsigned Opc = In.getOpcode();
10875     if (Opc == ISD::UNDEF)
10876       continue;
10878     // If all scalar values are floats and converted from integers.
10879     if (Opcode == ISD::DELETED_NODE &&
10880         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10881       Opcode = Opc;
10882     }
10884     if (Opc != Opcode)
10885       return SDValue();
10887     EVT InVT = In.getOperand(0).getValueType();
10889     // If all scalar values are typed differently, bail out. It's chosen to
10890     // simplify BUILD_VECTOR of integer types.
10891     if (SrcVT == MVT::Other)
10892       SrcVT = InVT;
10893     if (SrcVT != InVT)
10894       return SDValue();
10895     NumDefs++;
10896   }
10898   // If the vector has just one element defined, it's not worth to fold it into
10899   // a vectorized one.
10900   if (NumDefs < 2)
10901     return SDValue();
10903   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10904          && "Should only handle conversion from integer to float.");
10905   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10907   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10909   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10910     return SDValue();
10912   SmallVector<SDValue, 8> Opnds;
10913   for (unsigned i = 0; i != NumInScalars; ++i) {
10914     SDValue In = N->getOperand(i);
10916     if (In.getOpcode() == ISD::UNDEF)
10917       Opnds.push_back(DAG.getUNDEF(SrcVT));
10918     else
10919       Opnds.push_back(In.getOperand(0));
10920   }
10921   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10922   AddToWorklist(BV.getNode());
10924   return DAG.getNode(Opcode, dl, VT, BV);
10927 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10928   unsigned NumInScalars = N->getNumOperands();
10929   SDLoc dl(N);
10930   EVT VT = N->getValueType(0);
10932   // A vector built entirely of undefs is undef.
10933   if (ISD::allOperandsUndef(N))
10934     return DAG.getUNDEF(VT);
10936   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10937   if (V.getNode())
10938     return V;
10940   V = reduceBuildVecConvertToConvertBuildVec(N);
10941   if (V.getNode())
10942     return V;
10944   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10945   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10946   // at most two distinct vectors, turn this into a shuffle node.
10948   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10949   if (!isTypeLegal(VT))
10950     return SDValue();
10952   // May only combine to shuffle after legalize if shuffle is legal.
10953   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
10954     return SDValue();
10956   SDValue VecIn1, VecIn2;
10957   bool UsesZeroVector = false;
10958   for (unsigned i = 0; i != NumInScalars; ++i) {
10959     SDValue Op = N->getOperand(i);
10960     // Ignore undef inputs.
10961     if (Op.getOpcode() == ISD::UNDEF) continue;
10963     // See if we can combine this build_vector into a blend with a zero vector.
10964     if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
10965         cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
10966         (Op.getOpcode() == ISD::ConstantFP &&
10967         cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
10968       UsesZeroVector = true;
10969       continue;
10970     }
10972     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10973     // constant index, bail out.
10974     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10975         !isa<ConstantSDNode>(Op.getOperand(1))) {
10976       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10977       break;
10978     }
10980     // We allow up to two distinct input vectors.
10981     SDValue ExtractedFromVec = Op.getOperand(0);
10982     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10983       continue;
10985     if (!VecIn1.getNode()) {
10986       VecIn1 = ExtractedFromVec;
10987     } else if (!VecIn2.getNode() && !UsesZeroVector) {
10988       VecIn2 = ExtractedFromVec;
10989     } else {
10990       // Too many inputs.
10991       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10992       break;
10993     }
10994   }
10996   // If everything is good, we can make a shuffle operation.
10997   if (VecIn1.getNode()) {
10998     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
10999     SmallVector<int, 8> Mask;
11000     for (unsigned i = 0; i != NumInScalars; ++i) {
11001       unsigned Opcode = N->getOperand(i).getOpcode();
11002       if (Opcode == ISD::UNDEF) {
11003         Mask.push_back(-1);
11004         continue;
11005       }
11007       // Operands can also be zero.
11008       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11009         assert(UsesZeroVector &&
11010                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11011                "Unexpected node found!");
11012         Mask.push_back(NumInScalars+i);
11013         continue;
11014       }
11016       // If extracting from the first vector, just use the index directly.
11017       SDValue Extract = N->getOperand(i);
11018       SDValue ExtVal = Extract.getOperand(1);
11019       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11020       if (Extract.getOperand(0) == VecIn1) {
11021         Mask.push_back(ExtIndex);
11022         continue;
11023       }
11025       // Otherwise, use InIdx + InputVecSize
11026       Mask.push_back(InNumElements + ExtIndex);
11027     }
11029     // Avoid introducing illegal shuffles with zero.
11030     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11031       return SDValue();
11033     // We can't generate a shuffle node with mismatched input and output types.
11034     // Attempt to transform a single input vector to the correct type.
11035     if ((VT != VecIn1.getValueType())) {
11036       // If the input vector type has a different base type to the output
11037       // vector type, bail out.
11038       EVT VTElemType = VT.getVectorElementType();
11039       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11040           (VecIn2.getNode() &&
11041            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11042         return SDValue();
11044       // If the input vector is too small, widen it.
11045       // We only support widening of vectors which are half the size of the
11046       // output registers. For example XMM->YMM widening on X86 with AVX.
11047       EVT VecInT = VecIn1.getValueType();
11048       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11049         // If we only have one small input, widen it by adding undef values.
11050         if (!VecIn2.getNode())
11051           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11052                                DAG.getUNDEF(VecIn1.getValueType()));
11053         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11054           // If we have two small inputs of the same type, try to concat them.
11055           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11056           VecIn2 = SDValue(nullptr, 0);
11057         } else
11058           return SDValue();
11059       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11060         // If the input vector is too large, try to split it.
11061         // We don't support having two input vectors that are too large.
11062         if (VecIn2.getNode())
11063           return SDValue();
11065         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11066           return SDValue();
11067         
11068         // Try to replace VecIn1 with two extract_subvectors
11069         // No need to update the masks, they should still be correct.
11070         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 
11071           DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy()));
11072         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11073           DAG.getConstant(0, TLI.getVectorIdxTy()));
11074         UsesZeroVector = false;
11075       } else
11076         return SDValue();
11077     }
11079     if (UsesZeroVector)
11080       VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
11081                                 DAG.getConstantFP(0.0, VT);
11082     else
11083       // If VecIn2 is unused then change it to undef.
11084       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11086     // Check that we were able to transform all incoming values to the same
11087     // type.
11088     if (VecIn2.getValueType() != VecIn1.getValueType() ||
11089         VecIn1.getValueType() != VT)
11090           return SDValue();
11092     // Return the new VECTOR_SHUFFLE node.
11093     SDValue Ops[2];
11094     Ops[0] = VecIn1;
11095     Ops[1] = VecIn2;
11096     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
11097   }
11099   return SDValue();
11102 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
11103   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11104   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
11105   // inputs come from at most two distinct vectors, turn this into a shuffle
11106   // node.
11108   // If we only have one input vector, we don't need to do any concatenation.
11109   if (N->getNumOperands() == 1)
11110     return N->getOperand(0);
11112   // Check if all of the operands are undefs.
11113   EVT VT = N->getValueType(0);
11114   if (ISD::allOperandsUndef(N))
11115     return DAG.getUNDEF(VT);
11117   // Optimize concat_vectors where one of the vectors is undef.
11118   if (N->getNumOperands() == 2 &&
11119       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
11120     SDValue In = N->getOperand(0);
11121     assert(In.getValueType().isVector() && "Must concat vectors");
11123     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11124     if (In->getOpcode() == ISD::BITCAST &&
11125         !In->getOperand(0)->getValueType(0).isVector()) {
11126       SDValue Scalar = In->getOperand(0);
11127       EVT SclTy = Scalar->getValueType(0);
11129       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
11130         return SDValue();
11132       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
11133                                  VT.getSizeInBits() / SclTy.getSizeInBits());
11134       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
11135         return SDValue();
11137       SDLoc dl = SDLoc(N);
11138       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
11139       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
11140     }
11141   }
11143   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
11144   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
11145   if (N->getNumOperands() == 2 &&
11146       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
11147       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
11148     EVT VT = N->getValueType(0);
11149     SDValue N0 = N->getOperand(0);
11150     SDValue N1 = N->getOperand(1);
11151     SmallVector<SDValue, 8> Opnds;
11152     unsigned BuildVecNumElts =  N0.getNumOperands();
11154     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
11155     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
11156     if (SclTy0.isFloatingPoint()) {
11157       for (unsigned i = 0; i != BuildVecNumElts; ++i)
11158         Opnds.push_back(N0.getOperand(i));
11159       for (unsigned i = 0; i != BuildVecNumElts; ++i)
11160         Opnds.push_back(N1.getOperand(i));
11161     } else {
11162       // If BUILD_VECTOR are from built from integer, they may have different
11163       // operand types. Get the smaller type and truncate all operands to it.
11164       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
11165       for (unsigned i = 0; i != BuildVecNumElts; ++i)
11166         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
11167                         N0.getOperand(i)));
11168       for (unsigned i = 0; i != BuildVecNumElts; ++i)
11169         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
11170                         N1.getOperand(i)));
11171     }
11173     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
11174   }
11176   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
11177   // nodes often generate nop CONCAT_VECTOR nodes.
11178   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
11179   // place the incoming vectors at the exact same location.
11180   SDValue SingleSource = SDValue();
11181   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
11183   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11184     SDValue Op = N->getOperand(i);
11186     if (Op.getOpcode() == ISD::UNDEF)
11187       continue;
11189     // Check if this is the identity extract:
11190     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
11191       return SDValue();
11193     // Find the single incoming vector for the extract_subvector.
11194     if (SingleSource.getNode()) {
11195       if (Op.getOperand(0) != SingleSource)
11196         return SDValue();
11197     } else {
11198       SingleSource = Op.getOperand(0);
11200       // Check the source type is the same as the type of the result.
11201       // If not, this concat may extend the vector, so we can not
11202       // optimize it away.
11203       if (SingleSource.getValueType() != N->getValueType(0))
11204         return SDValue();
11205     }
11207     unsigned IdentityIndex = i * PartNumElem;
11208     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11209     // The extract index must be constant.
11210     if (!CS)
11211       return SDValue();
11213     // Check that we are reading from the identity index.
11214     if (CS->getZExtValue() != IdentityIndex)
11215       return SDValue();
11216   }
11218   if (SingleSource.getNode())
11219     return SingleSource;
11221   return SDValue();
11224 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
11225   EVT NVT = N->getValueType(0);
11226   SDValue V = N->getOperand(0);
11228   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
11229     // Combine:
11230     //    (extract_subvec (concat V1, V2, ...), i)
11231     // Into:
11232     //    Vi if possible
11233     // Only operand 0 is checked as 'concat' assumes all inputs of the same
11234     // type.
11235     if (V->getOperand(0).getValueType() != NVT)
11236       return SDValue();
11237     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11238     unsigned NumElems = NVT.getVectorNumElements();
11239     assert((Idx % NumElems) == 0 &&
11240            "IDX in concat is not a multiple of the result vector length.");
11241     return V->getOperand(Idx / NumElems);
11242   }
11244   // Skip bitcasting
11245   if (V->getOpcode() == ISD::BITCAST)
11246     V = V.getOperand(0);
11248   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
11249     SDLoc dl(N);
11250     // Handle only simple case where vector being inserted and vector
11251     // being extracted are of same type, and are half size of larger vectors.
11252     EVT BigVT = V->getOperand(0).getValueType();
11253     EVT SmallVT = V->getOperand(1).getValueType();
11254     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
11255       return SDValue();
11257     // Only handle cases where both indexes are constants with the same type.
11258     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11259     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
11261     if (InsIdx && ExtIdx &&
11262         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
11263         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
11264       // Combine:
11265       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
11266       // Into:
11267       //    indices are equal or bit offsets are equal => V1
11268       //    otherwise => (extract_subvec V1, ExtIdx)
11269       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
11270           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
11271         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
11272       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
11273                          DAG.getNode(ISD::BITCAST, dl,
11274                                      N->getOperand(0).getValueType(),
11275                                      V->getOperand(0)), N->getOperand(1));
11276     }
11277   }
11279   return SDValue();
11282 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
11283                                                  SDValue V, SelectionDAG &DAG) {
11284   SDLoc DL(V);
11285   EVT VT = V.getValueType();
11287   switch (V.getOpcode()) {
11288   default:
11289     return V;
11291   case ISD::CONCAT_VECTORS: {
11292     EVT OpVT = V->getOperand(0).getValueType();
11293     int OpSize = OpVT.getVectorNumElements();
11294     SmallBitVector OpUsedElements(OpSize, false);
11295     bool FoundSimplification = false;
11296     SmallVector<SDValue, 4> NewOps;
11297     NewOps.reserve(V->getNumOperands());
11298     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
11299       SDValue Op = V->getOperand(i);
11300       bool OpUsed = false;
11301       for (int j = 0; j < OpSize; ++j)
11302         if (UsedElements[i * OpSize + j]) {
11303           OpUsedElements[j] = true;
11304           OpUsed = true;
11305         }
11306       NewOps.push_back(
11307           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
11308                  : DAG.getUNDEF(OpVT));
11309       FoundSimplification |= Op == NewOps.back();
11310       OpUsedElements.reset();
11311     }
11312     if (FoundSimplification)
11313       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
11314     return V;
11315   }
11317   case ISD::INSERT_SUBVECTOR: {
11318     SDValue BaseV = V->getOperand(0);
11319     SDValue SubV = V->getOperand(1);
11320     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
11321     if (!IdxN)
11322       return V;
11324     int SubSize = SubV.getValueType().getVectorNumElements();
11325     int Idx = IdxN->getZExtValue();
11326     bool SubVectorUsed = false;
11327     SmallBitVector SubUsedElements(SubSize, false);
11328     for (int i = 0; i < SubSize; ++i)
11329       if (UsedElements[i + Idx]) {
11330         SubVectorUsed = true;
11331         SubUsedElements[i] = true;
11332         UsedElements[i + Idx] = false;
11333       }
11335     // Now recurse on both the base and sub vectors.
11336     SDValue SimplifiedSubV =
11337         SubVectorUsed
11338             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
11339             : DAG.getUNDEF(SubV.getValueType());
11340     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
11341     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
11342       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
11343                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
11344     return V;
11345   }
11346   }
11349 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
11350                                        SDValue N1, SelectionDAG &DAG) {
11351   EVT VT = SVN->getValueType(0);
11352   int NumElts = VT.getVectorNumElements();
11353   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
11354   for (int M : SVN->getMask())
11355     if (M >= 0 && M < NumElts)
11356       N0UsedElements[M] = true;
11357     else if (M >= NumElts)
11358       N1UsedElements[M - NumElts] = true;
11360   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
11361   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
11362   if (S0 == N0 && S1 == N1)
11363     return SDValue();
11365   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
11368 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
11369 // or turn a shuffle of a single concat into simpler shuffle then concat.
11370 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
11371   EVT VT = N->getValueType(0);
11372   unsigned NumElts = VT.getVectorNumElements();
11374   SDValue N0 = N->getOperand(0);
11375   SDValue N1 = N->getOperand(1);
11376   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11378   SmallVector<SDValue, 4> Ops;
11379   EVT ConcatVT = N0.getOperand(0).getValueType();
11380   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
11381   unsigned NumConcats = NumElts / NumElemsPerConcat;
11383   // Special case: shuffle(concat(A,B)) can be more efficiently represented
11384   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
11385   // half vector elements.
11386   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
11387       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
11388                   SVN->getMask().end(), [](int i) { return i == -1; })) {
11389     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
11390                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
11391     N1 = DAG.getUNDEF(ConcatVT);
11392     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
11393   }
11395   // Look at every vector that's inserted. We're looking for exact
11396   // subvector-sized copies from a concatenated vector
11397   for (unsigned I = 0; I != NumConcats; ++I) {
11398     // Make sure we're dealing with a copy.
11399     unsigned Begin = I * NumElemsPerConcat;
11400     bool AllUndef = true, NoUndef = true;
11401     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
11402       if (SVN->getMaskElt(J) >= 0)
11403         AllUndef = false;
11404       else
11405         NoUndef = false;
11406     }
11408     if (NoUndef) {
11409       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
11410         return SDValue();
11412       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
11413         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
11414           return SDValue();
11416       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
11417       if (FirstElt < N0.getNumOperands())
11418         Ops.push_back(N0.getOperand(FirstElt));
11419       else
11420         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
11422     } else if (AllUndef) {
11423       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
11424     } else { // Mixed with general masks and undefs, can't do optimization.
11425       return SDValue();
11426     }
11427   }
11429   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
11432 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
11433   EVT VT = N->getValueType(0);
11434   unsigned NumElts = VT.getVectorNumElements();
11436   SDValue N0 = N->getOperand(0);
11437   SDValue N1 = N->getOperand(1);
11439   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
11441   // Canonicalize shuffle undef, undef -> undef
11442   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
11443     return DAG.getUNDEF(VT);
11445   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11447   // Canonicalize shuffle v, v -> v, undef
11448   if (N0 == N1) {
11449     SmallVector<int, 8> NewMask;
11450     for (unsigned i = 0; i != NumElts; ++i) {
11451       int Idx = SVN->getMaskElt(i);
11452       if (Idx >= (int)NumElts) Idx -= NumElts;
11453       NewMask.push_back(Idx);
11454     }
11455     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
11456                                 &NewMask[0]);
11457   }
11459   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
11460   if (N0.getOpcode() == ISD::UNDEF) {
11461     SmallVector<int, 8> NewMask;
11462     for (unsigned i = 0; i != NumElts; ++i) {
11463       int Idx = SVN->getMaskElt(i);
11464       if (Idx >= 0) {
11465         if (Idx >= (int)NumElts)
11466           Idx -= NumElts;
11467         else
11468           Idx = -1; // remove reference to lhs
11469       }
11470       NewMask.push_back(Idx);
11471     }
11472     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
11473                                 &NewMask[0]);
11474   }
11476   // Remove references to rhs if it is undef
11477   if (N1.getOpcode() == ISD::UNDEF) {
11478     bool Changed = false;
11479     SmallVector<int, 8> NewMask;
11480     for (unsigned i = 0; i != NumElts; ++i) {
11481       int Idx = SVN->getMaskElt(i);
11482       if (Idx >= (int)NumElts) {
11483         Idx = -1;
11484         Changed = true;
11485       }
11486       NewMask.push_back(Idx);
11487     }
11488     if (Changed)
11489       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
11490   }
11492   // If it is a splat, check if the argument vector is another splat or a
11493   // build_vector with all scalar elements the same.
11494   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
11495     SDNode *V = N0.getNode();
11497     // If this is a bit convert that changes the element type of the vector but
11498     // not the number of vector elements, look through it.  Be careful not to
11499     // look though conversions that change things like v4f32 to v2f64.
11500     if (V->getOpcode() == ISD::BITCAST) {
11501       SDValue ConvInput = V->getOperand(0);
11502       if (ConvInput.getValueType().isVector() &&
11503           ConvInput.getValueType().getVectorNumElements() == NumElts)
11504         V = ConvInput.getNode();
11505     }
11507     if (V->getOpcode() == ISD::BUILD_VECTOR) {
11508       assert(V->getNumOperands() == NumElts &&
11509              "BUILD_VECTOR has wrong number of operands");
11510       SDValue Base;
11511       bool AllSame = true;
11512       for (unsigned i = 0; i != NumElts; ++i) {
11513         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11514           Base = V->getOperand(i);
11515           break;
11516         }
11517       }
11518       // Splat of <u, u, u, u>, return <u, u, u, u>
11519       if (!Base.getNode())
11520         return N0;
11521       for (unsigned i = 0; i != NumElts; ++i) {
11522         if (V->getOperand(i) != Base) {
11523           AllSame = false;
11524           break;
11525         }
11526       }
11527       // Splat of <x, x, x, x>, return <x, x, x, x>
11528       if (AllSame)
11529         return N0;
11530     }
11531   }
11533   // There are various patterns used to build up a vector from smaller vectors,
11534   // subvectors, or elements. Scan chains of these and replace unused insertions
11535   // or components with undef.
11536   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11537     return S;
11539   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11540       Level < AfterLegalizeVectorOps &&
11541       (N1.getOpcode() == ISD::UNDEF ||
11542       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11543        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11544     SDValue V = partitionShuffleOfConcats(N, DAG);
11546     if (V.getNode())
11547       return V;
11548   }
11550   // Canonicalize shuffles according to rules:
11551   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
11552   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
11553   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
11554   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
11555       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11556       TLI.isTypeLegal(VT)) {
11557     // The incoming shuffle must be of the same type as the result of the
11558     // current shuffle.
11559     assert(N1->getOperand(0).getValueType() == VT &&
11560            "Shuffle types don't match");
11562     SDValue SV0 = N1->getOperand(0);
11563     SDValue SV1 = N1->getOperand(1);
11564     bool HasSameOp0 = N0 == SV0;
11565     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11566     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
11567       // Commute the operands of this shuffle so that next rule
11568       // will trigger.
11569       return DAG.getCommutedVectorShuffle(*SVN);
11570   }
11572   // Try to fold according to rules:
11573   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11574   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11575   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11576   // Don't try to fold shuffles with illegal type.
11577   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11578       TLI.isTypeLegal(VT)) {
11579     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11581     // The incoming shuffle must be of the same type as the result of the
11582     // current shuffle.
11583     assert(OtherSV->getOperand(0).getValueType() == VT &&
11584            "Shuffle types don't match");
11586     SDValue SV0, SV1;
11587     SmallVector<int, 4> Mask;
11588     // Compute the combined shuffle mask for a shuffle with SV0 as the first
11589     // operand, and SV1 as the second operand.
11590     for (unsigned i = 0; i != NumElts; ++i) {
11591       int Idx = SVN->getMaskElt(i);
11592       if (Idx < 0) {
11593         // Propagate Undef.
11594         Mask.push_back(Idx);
11595         continue;
11596       }
11598       SDValue CurrentVec;
11599       if (Idx < (int)NumElts) {
11600         // This shuffle index refers to the inner shuffle N0. Lookup the inner
11601         // shuffle mask to identify which vector is actually referenced.
11602         Idx = OtherSV->getMaskElt(Idx);
11603         if (Idx < 0) {
11604           // Propagate Undef.
11605           Mask.push_back(Idx);
11606           continue;
11607         }
11609         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
11610                                            : OtherSV->getOperand(1);
11611       } else {
11612         // This shuffle index references an element within N1.
11613         CurrentVec = N1;
11614       }
11616       // Simple case where 'CurrentVec' is UNDEF.
11617       if (CurrentVec.getOpcode() == ISD::UNDEF) {
11618         Mask.push_back(-1);
11619         continue;
11620       }
11622       // Canonicalize the shuffle index. We don't know yet if CurrentVec
11623       // will be the first or second operand of the combined shuffle.
11624       Idx = Idx % NumElts;
11625       if (!SV0.getNode() || SV0 == CurrentVec) {
11626         // Ok. CurrentVec is the left hand side.
11627         // Update the mask accordingly.
11628         SV0 = CurrentVec;
11629         Mask.push_back(Idx);
11630         continue;
11631       }
11633       // Bail out if we cannot convert the shuffle pair into a single shuffle.
11634       if (SV1.getNode() && SV1 != CurrentVec)
11635         return SDValue();
11637       // Ok. CurrentVec is the right hand side.
11638       // Update the mask accordingly.
11639       SV1 = CurrentVec;
11640       Mask.push_back(Idx + NumElts);
11641     }
11643     // Check if all indices in Mask are Undef. In case, propagate Undef.
11644     bool isUndefMask = true;
11645     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11646       isUndefMask &= Mask[i] < 0;
11648     if (isUndefMask)
11649       return DAG.getUNDEF(VT);
11651     if (!SV0.getNode())
11652       SV0 = DAG.getUNDEF(VT);
11653     if (!SV1.getNode())
11654       SV1 = DAG.getUNDEF(VT);
11656     // Avoid introducing shuffles with illegal mask.
11657     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
11658       // Compute the commuted shuffle mask and test again.
11659       for (unsigned i = 0; i != NumElts; ++i) {
11660         int idx = Mask[i];
11661         if (idx < 0)
11662           continue;
11663         else if (idx < (int)NumElts)
11664           Mask[i] = idx + NumElts;
11665         else
11666           Mask[i] = idx - NumElts;
11667       }
11669       if (!TLI.isShuffleMaskLegal(Mask, VT))
11670         return SDValue();
11672       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
11673       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
11674       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
11675       std::swap(SV0, SV1);
11676     }
11678     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11679     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11680     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11681     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
11682   }
11684   return SDValue();
11687 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11688   SDValue N0 = N->getOperand(0);
11689   SDValue N2 = N->getOperand(2);
11691   // If the input vector is a concatenation, and the insert replaces
11692   // one of the halves, we can optimize into a single concat_vectors.
11693   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11694       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11695     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11696     EVT VT = N->getValueType(0);
11698     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11699     // (concat_vectors Z, Y)
11700     if (InsIdx == 0)
11701       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11702                          N->getOperand(1), N0.getOperand(1));
11704     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11705     // (concat_vectors X, Z)
11706     if (InsIdx == VT.getVectorNumElements()/2)
11707       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11708                          N0.getOperand(0), N->getOperand(1));
11709   }
11711   return SDValue();
11714 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11715 /// with the destination vector and a zero vector.
11716 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11717 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
11718 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11719   EVT VT = N->getValueType(0);
11720   SDLoc dl(N);
11721   SDValue LHS = N->getOperand(0);
11722   SDValue RHS = N->getOperand(1);
11723   if (N->getOpcode() == ISD::AND) {
11724     if (RHS.getOpcode() == ISD::BITCAST)
11725       RHS = RHS.getOperand(0);
11726     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11727       SmallVector<int, 8> Indices;
11728       unsigned NumElts = RHS.getNumOperands();
11729       for (unsigned i = 0; i != NumElts; ++i) {
11730         SDValue Elt = RHS.getOperand(i);
11731         if (!isa<ConstantSDNode>(Elt))
11732           return SDValue();
11734         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11735           Indices.push_back(i);
11736         else if (cast<ConstantSDNode>(Elt)->isNullValue())
11737           Indices.push_back(NumElts+i);
11738         else
11739           return SDValue();
11740       }
11742       // Let's see if the target supports this vector_shuffle.
11743       EVT RVT = RHS.getValueType();
11744       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11745         return SDValue();
11747       // Return the new VECTOR_SHUFFLE node.
11748       EVT EltVT = RVT.getVectorElementType();
11749       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11750                                      DAG.getConstant(0, EltVT));
11751       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11752       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11753       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11754       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11755     }
11756   }
11758   return SDValue();
11761 /// Visit a binary vector operation, like ADD.
11762 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11763   assert(N->getValueType(0).isVector() &&
11764          "SimplifyVBinOp only works on vectors!");
11766   SDValue LHS = N->getOperand(0);
11767   SDValue RHS = N->getOperand(1);
11768   SDValue Shuffle = XformToShuffleWithZero(N);
11769   if (Shuffle.getNode()) return Shuffle;
11771   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11772   // this operation.
11773   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11774       RHS.getOpcode() == ISD::BUILD_VECTOR) {
11775     // Check if both vectors are constants. If not bail out.
11776     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11777           cast<BuildVectorSDNode>(RHS)->isConstant()))
11778       return SDValue();
11780     SmallVector<SDValue, 8> Ops;
11781     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11782       SDValue LHSOp = LHS.getOperand(i);
11783       SDValue RHSOp = RHS.getOperand(i);
11785       // Can't fold divide by zero.
11786       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11787           N->getOpcode() == ISD::FDIV) {
11788         if ((RHSOp.getOpcode() == ISD::Constant &&
11789              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11790             (RHSOp.getOpcode() == ISD::ConstantFP &&
11791              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11792           break;
11793       }
11795       EVT VT = LHSOp.getValueType();
11796       EVT RVT = RHSOp.getValueType();
11797       if (RVT != VT) {
11798         // Integer BUILD_VECTOR operands may have types larger than the element
11799         // size (e.g., when the element type is not legal).  Prior to type
11800         // legalization, the types may not match between the two BUILD_VECTORS.
11801         // Truncate one of the operands to make them match.
11802         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11803           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11804         } else {
11805           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11806           VT = RVT;
11807         }
11808       }
11809       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11810                                    LHSOp, RHSOp);
11811       if (FoldOp.getOpcode() != ISD::UNDEF &&
11812           FoldOp.getOpcode() != ISD::Constant &&
11813           FoldOp.getOpcode() != ISD::ConstantFP)
11814         break;
11815       Ops.push_back(FoldOp);
11816       AddToWorklist(FoldOp.getNode());
11817     }
11819     if (Ops.size() == LHS.getNumOperands())
11820       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11821   }
11823   // Type legalization might introduce new shuffles in the DAG.
11824   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11825   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
11826   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11827       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11828       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11829       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11830     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11831     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11833     if (SVN0->getMask().equals(SVN1->getMask())) {
11834       EVT VT = N->getValueType(0);
11835       SDValue UndefVector = LHS.getOperand(1);
11836       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11837                                      LHS.getOperand(0), RHS.getOperand(0));
11838       AddUsersToWorklist(N);
11839       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11840                                   &SVN0->getMask()[0]);
11841     }
11842   }
11844   return SDValue();
11847 /// Visit a binary vector operation, like FABS/FNEG.
11848 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11849   assert(N->getValueType(0).isVector() &&
11850          "SimplifyVUnaryOp only works on vectors!");
11852   SDValue N0 = N->getOperand(0);
11854   if (N0.getOpcode() != ISD::BUILD_VECTOR)
11855     return SDValue();
11857   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11858   SmallVector<SDValue, 8> Ops;
11859   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11860     SDValue Op = N0.getOperand(i);
11861     if (Op.getOpcode() != ISD::UNDEF &&
11862         Op.getOpcode() != ISD::ConstantFP)
11863       break;
11864     EVT EltVT = Op.getValueType();
11865     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11866     if (FoldOp.getOpcode() != ISD::UNDEF &&
11867         FoldOp.getOpcode() != ISD::ConstantFP)
11868       break;
11869     Ops.push_back(FoldOp);
11870     AddToWorklist(FoldOp.getNode());
11871   }
11873   if (Ops.size() != N0.getNumOperands())
11874     return SDValue();
11876   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11879 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11880                                     SDValue N1, SDValue N2){
11881   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11883   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11884                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11886   // If we got a simplified select_cc node back from SimplifySelectCC, then
11887   // break it down into a new SETCC node, and a new SELECT node, and then return
11888   // the SELECT node, since we were called with a SELECT node.
11889   if (SCC.getNode()) {
11890     // Check to see if we got a select_cc back (to turn into setcc/select).
11891     // Otherwise, just return whatever node we got back, like fabs.
11892     if (SCC.getOpcode() == ISD::SELECT_CC) {
11893       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11894                                   N0.getValueType(),
11895                                   SCC.getOperand(0), SCC.getOperand(1),
11896                                   SCC.getOperand(4));
11897       AddToWorklist(SETCC.getNode());
11898       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11899                            SCC.getOperand(2), SCC.getOperand(3));
11900     }
11902     return SCC;
11903   }
11904   return SDValue();
11907 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11908 /// being selected between, see if we can simplify the select.  Callers of this
11909 /// should assume that TheSelect is deleted if this returns true.  As such, they
11910 /// should return the appropriate thing (e.g. the node) back to the top-level of
11911 /// the DAG combiner loop to avoid it being looked at.
11912 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11913                                     SDValue RHS) {
11915   // Cannot simplify select with vector condition
11916   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11918   // If this is a select from two identical things, try to pull the operation
11919   // through the select.
11920   if (LHS.getOpcode() != RHS.getOpcode() ||
11921       !LHS.hasOneUse() || !RHS.hasOneUse())
11922     return false;
11924   // If this is a load and the token chain is identical, replace the select
11925   // of two loads with a load through a select of the address to load from.
11926   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11927   // constants have been dropped into the constant pool.
11928   if (LHS.getOpcode() == ISD::LOAD) {
11929     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11930     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11932     // Token chains must be identical.
11933     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11934         // Do not let this transformation reduce the number of volatile loads.
11935         LLD->isVolatile() || RLD->isVolatile() ||
11936         // If this is an EXTLOAD, the VT's must match.
11937         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11938         // If this is an EXTLOAD, the kind of extension must match.
11939         (LLD->getExtensionType() != RLD->getExtensionType() &&
11940          // The only exception is if one of the extensions is anyext.
11941          LLD->getExtensionType() != ISD::EXTLOAD &&
11942          RLD->getExtensionType() != ISD::EXTLOAD) ||
11943         // FIXME: this discards src value information.  This is
11944         // over-conservative. It would be beneficial to be able to remember
11945         // both potential memory locations.  Since we are discarding
11946         // src value info, don't do the transformation if the memory
11947         // locations are not in the default address space.
11948         LLD->getPointerInfo().getAddrSpace() != 0 ||
11949         RLD->getPointerInfo().getAddrSpace() != 0 ||
11950         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11951                                       LLD->getBasePtr().getValueType()))
11952       return false;
11954     // Check that the select condition doesn't reach either load.  If so,
11955     // folding this will induce a cycle into the DAG.  If not, this is safe to
11956     // xform, so create a select of the addresses.
11957     SDValue Addr;
11958     if (TheSelect->getOpcode() == ISD::SELECT) {
11959       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11960       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11961           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11962         return false;
11963       // The loads must not depend on one another.
11964       if (LLD->isPredecessorOf(RLD) ||
11965           RLD->isPredecessorOf(LLD))
11966         return false;
11967       Addr = DAG.getSelect(SDLoc(TheSelect),
11968                            LLD->getBasePtr().getValueType(),
11969                            TheSelect->getOperand(0), LLD->getBasePtr(),
11970                            RLD->getBasePtr());
11971     } else {  // Otherwise SELECT_CC
11972       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11973       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11975       if ((LLD->hasAnyUseOfValue(1) &&
11976            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11977           (RLD->hasAnyUseOfValue(1) &&
11978            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11979         return false;
11981       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11982                          LLD->getBasePtr().getValueType(),
11983                          TheSelect->getOperand(0),
11984                          TheSelect->getOperand(1),
11985                          LLD->getBasePtr(), RLD->getBasePtr(),
11986                          TheSelect->getOperand(4));
11987     }
11989     SDValue Load;
11990     // It is safe to replace the two loads if they have different alignments,
11991     // but the new load must be the minimum (most restrictive) alignment of the
11992     // inputs.
11993     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
11994     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11995     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11996       Load = DAG.getLoad(TheSelect->getValueType(0),
11997                          SDLoc(TheSelect),
11998                          // FIXME: Discards pointer and AA info.
11999                          LLD->getChain(), Addr, MachinePointerInfo(),
12000                          LLD->isVolatile(), LLD->isNonTemporal(),
12001                          isInvariant, Alignment);
12002     } else {
12003       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
12004                             RLD->getExtensionType() : LLD->getExtensionType(),
12005                             SDLoc(TheSelect),
12006                             TheSelect->getValueType(0),
12007                             // FIXME: Discards pointer and AA info.
12008                             LLD->getChain(), Addr, MachinePointerInfo(),
12009                             LLD->getMemoryVT(), LLD->isVolatile(),
12010                             LLD->isNonTemporal(), isInvariant, Alignment);
12011     }
12013     // Users of the select now use the result of the load.
12014     CombineTo(TheSelect, Load);
12016     // Users of the old loads now use the new load's chain.  We know the
12017     // old-load value is dead now.
12018     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
12019     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
12020     return true;
12021   }
12023   return false;
12026 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
12027 /// where 'cond' is the comparison specified by CC.
12028 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
12029                                       SDValue N2, SDValue N3,
12030                                       ISD::CondCode CC, bool NotExtCompare) {
12031   // (x ? y : y) -> y.
12032   if (N2 == N3) return N2;
12034   EVT VT = N2.getValueType();
12035   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
12036   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
12037   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
12039   // Determine if the condition we're dealing with is constant
12040   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
12041                               N0, N1, CC, DL, false);
12042   if (SCC.getNode()) AddToWorklist(SCC.getNode());
12043   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
12045   // fold select_cc true, x, y -> x
12046   if (SCCC && !SCCC->isNullValue())
12047     return N2;
12048   // fold select_cc false, x, y -> y
12049   if (SCCC && SCCC->isNullValue())
12050     return N3;
12052   // Check to see if we can simplify the select into an fabs node
12053   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
12054     // Allow either -0.0 or 0.0
12055     if (CFP->getValueAPF().isZero()) {
12056       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
12057       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
12058           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
12059           N2 == N3.getOperand(0))
12060         return DAG.getNode(ISD::FABS, DL, VT, N0);
12062       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
12063       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
12064           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
12065           N2.getOperand(0) == N3)
12066         return DAG.getNode(ISD::FABS, DL, VT, N3);
12067     }
12068   }
12070   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
12071   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
12072   // in it.  This is a win when the constant is not otherwise available because
12073   // it replaces two constant pool loads with one.  We only do this if the FP
12074   // type is known to be legal, because if it isn't, then we are before legalize
12075   // types an we want the other legalization to happen first (e.g. to avoid
12076   // messing with soft float) and if the ConstantFP is not legal, because if
12077   // it is legal, we may not need to store the FP constant in a constant pool.
12078   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
12079     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
12080       if (TLI.isTypeLegal(N2.getValueType()) &&
12081           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
12082                TargetLowering::Legal &&
12083            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
12084            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
12085           // If both constants have multiple uses, then we won't need to do an
12086           // extra load, they are likely around in registers for other users.
12087           (TV->hasOneUse() || FV->hasOneUse())) {
12088         Constant *Elts[] = {
12089           const_cast<ConstantFP*>(FV->getConstantFPValue()),
12090           const_cast<ConstantFP*>(TV->getConstantFPValue())
12091         };
12092         Type *FPTy = Elts[0]->getType();
12093         const DataLayout &TD = *TLI.getDataLayout();
12095         // Create a ConstantArray of the two constants.
12096         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
12097         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
12098                                             TD.getPrefTypeAlignment(FPTy));
12099         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12101         // Get the offsets to the 0 and 1 element of the array so that we can
12102         // select between them.
12103         SDValue Zero = DAG.getIntPtrConstant(0);
12104         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
12105         SDValue One = DAG.getIntPtrConstant(EltSize);
12107         SDValue Cond = DAG.getSetCC(DL,
12108                                     getSetCCResultType(N0.getValueType()),
12109                                     N0, N1, CC);
12110         AddToWorklist(Cond.getNode());
12111         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
12112                                           Cond, One, Zero);
12113         AddToWorklist(CstOffset.getNode());
12114         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
12115                             CstOffset);
12116         AddToWorklist(CPIdx.getNode());
12117         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
12118                            MachinePointerInfo::getConstantPool(), false,
12119                            false, false, Alignment);
12121       }
12122     }
12124   // Check to see if we can perform the "gzip trick", transforming
12125   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
12126   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
12127       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
12128        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
12129     EVT XType = N0.getValueType();
12130     EVT AType = N2.getValueType();
12131     if (XType.bitsGE(AType)) {
12132       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
12133       // single-bit constant.
12134       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
12135         unsigned ShCtV = N2C->getAPIntValue().logBase2();
12136         ShCtV = XType.getSizeInBits()-ShCtV-1;
12137         SDValue ShCt = DAG.getConstant(ShCtV,
12138                                        getShiftAmountTy(N0.getValueType()));
12139         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
12140                                     XType, N0, ShCt);
12141         AddToWorklist(Shift.getNode());
12143         if (XType.bitsGT(AType)) {
12144           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12145           AddToWorklist(Shift.getNode());
12146         }
12148         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12149       }
12151       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
12152                                   XType, N0,
12153                                   DAG.getConstant(XType.getSizeInBits()-1,
12154                                          getShiftAmountTy(N0.getValueType())));
12155       AddToWorklist(Shift.getNode());
12157       if (XType.bitsGT(AType)) {
12158         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12159         AddToWorklist(Shift.getNode());
12160       }
12162       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12163     }
12164   }
12166   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
12167   // where y is has a single bit set.
12168   // A plaintext description would be, we can turn the SELECT_CC into an AND
12169   // when the condition can be materialized as an all-ones register.  Any
12170   // single bit-test can be materialized as an all-ones register with
12171   // shift-left and shift-right-arith.
12172   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
12173       N0->getValueType(0) == VT &&
12174       N1C && N1C->isNullValue() &&
12175       N2C && N2C->isNullValue()) {
12176     SDValue AndLHS = N0->getOperand(0);
12177     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12178     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
12179       // Shift the tested bit over the sign bit.
12180       APInt AndMask = ConstAndRHS->getAPIntValue();
12181       SDValue ShlAmt =
12182         DAG.getConstant(AndMask.countLeadingZeros(),
12183                         getShiftAmountTy(AndLHS.getValueType()));
12184       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
12186       // Now arithmetic right shift it all the way over, so the result is either
12187       // all-ones, or zero.
12188       SDValue ShrAmt =
12189         DAG.getConstant(AndMask.getBitWidth()-1,
12190                         getShiftAmountTy(Shl.getValueType()));
12191       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
12193       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
12194     }
12195   }
12197   // fold select C, 16, 0 -> shl C, 4
12198   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
12199       TLI.getBooleanContents(N0.getValueType()) ==
12200           TargetLowering::ZeroOrOneBooleanContent) {
12202     // If the caller doesn't want us to simplify this into a zext of a compare,
12203     // don't do it.
12204     if (NotExtCompare && N2C->getAPIntValue() == 1)
12205       return SDValue();
12207     // Get a SetCC of the condition
12208     // NOTE: Don't create a SETCC if it's not legal on this target.
12209     if (!LegalOperations ||
12210         TLI.isOperationLegal(ISD::SETCC,
12211           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
12212       SDValue Temp, SCC;
12213       // cast from setcc result type to select result type
12214       if (LegalTypes) {
12215         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
12216                             N0, N1, CC);
12217         if (N2.getValueType().bitsLT(SCC.getValueType()))
12218           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
12219                                         N2.getValueType());
12220         else
12221           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12222                              N2.getValueType(), SCC);
12223       } else {
12224         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
12225         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12226                            N2.getValueType(), SCC);
12227       }
12229       AddToWorklist(SCC.getNode());
12230       AddToWorklist(Temp.getNode());
12232       if (N2C->getAPIntValue() == 1)
12233         return Temp;
12235       // shl setcc result by log2 n2c
12236       return DAG.getNode(
12237           ISD::SHL, DL, N2.getValueType(), Temp,
12238           DAG.getConstant(N2C->getAPIntValue().logBase2(),
12239                           getShiftAmountTy(Temp.getValueType())));
12240     }
12241   }
12243   // Check to see if this is the equivalent of setcc
12244   // FIXME: Turn all of these into setcc if setcc if setcc is legal
12245   // otherwise, go ahead with the folds.
12246   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
12247     EVT XType = N0.getValueType();
12248     if (!LegalOperations ||
12249         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
12250       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
12251       if (Res.getValueType() != VT)
12252         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
12253       return Res;
12254     }
12256     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
12257     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
12258         (!LegalOperations ||
12259          TLI.isOperationLegal(ISD::CTLZ, XType))) {
12260       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
12261       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
12262                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
12263                                        getShiftAmountTy(Ctlz.getValueType())));
12264     }
12265     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
12266     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
12267       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
12268                                   XType, DAG.getConstant(0, XType), N0);
12269       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
12270       return DAG.getNode(ISD::SRL, DL, XType,
12271                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
12272                          DAG.getConstant(XType.getSizeInBits()-1,
12273                                          getShiftAmountTy(XType)));
12274     }
12275     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
12276     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
12277       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
12278                                  DAG.getConstant(XType.getSizeInBits()-1,
12279                                          getShiftAmountTy(N0.getValueType())));
12280       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
12281     }
12282   }
12284   // Check to see if this is an integer abs.
12285   // select_cc setg[te] X,  0,  X, -X ->
12286   // select_cc setgt    X, -1,  X, -X ->
12287   // select_cc setl[te] X,  0, -X,  X ->
12288   // select_cc setlt    X,  1, -X,  X ->
12289   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
12290   if (N1C) {
12291     ConstantSDNode *SubC = nullptr;
12292     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
12293          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
12294         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
12295       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
12296     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
12297               (N1C->isOne() && CC == ISD::SETLT)) &&
12298              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
12299       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
12301     EVT XType = N0.getValueType();
12302     if (SubC && SubC->isNullValue() && XType.isInteger()) {
12303       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
12304                                   N0,
12305                                   DAG.getConstant(XType.getSizeInBits()-1,
12306                                          getShiftAmountTy(N0.getValueType())));
12307       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
12308                                 XType, N0, Shift);
12309       AddToWorklist(Shift.getNode());
12310       AddToWorklist(Add.getNode());
12311       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
12312     }
12313   }
12315   return SDValue();
12318 /// This is a stub for TargetLowering::SimplifySetCC.
12319 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
12320                                    SDValue N1, ISD::CondCode Cond,
12321                                    SDLoc DL, bool foldBooleans) {
12322   TargetLowering::DAGCombinerInfo
12323     DagCombineInfo(DAG, Level, false, this);
12324   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
12327 /// Given an ISD::SDIV node expressing a divide by constant, return
12328 /// a DAG expression to select that will generate the same value by multiplying
12329 /// by a magic number.
12330 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12331 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
12332   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12333   if (!C)
12334     return SDValue();
12336   // Avoid division by zero.
12337   if (!C->getAPIntValue())
12338     return SDValue();
12340   std::vector<SDNode*> Built;
12341   SDValue S =
12342       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12344   for (SDNode *N : Built)
12345     AddToWorklist(N);
12346   return S;
12349 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
12350 /// DAG expression that will generate the same value by right shifting.
12351 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
12352   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12353   if (!C)
12354     return SDValue();
12356   // Avoid division by zero.
12357   if (!C->getAPIntValue())
12358     return SDValue();
12360   std::vector<SDNode *> Built;
12361   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
12363   for (SDNode *N : Built)
12364     AddToWorklist(N);
12365   return S;
12368 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
12369 /// expression that will generate the same value by multiplying by a magic
12370 /// number.
12371 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12372 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
12373   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12374   if (!C)
12375     return SDValue();
12377   // Avoid division by zero.
12378   if (!C->getAPIntValue())
12379     return SDValue();
12381   std::vector<SDNode*> Built;
12382   SDValue S =
12383       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12385   for (SDNode *N : Built)
12386     AddToWorklist(N);
12387   return S;
12390 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
12391   if (Level >= AfterLegalizeDAG)
12392     return SDValue();
12394   // Expose the DAG combiner to the target combiner implementations.
12395   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12397   unsigned Iterations = 0;
12398   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
12399     if (Iterations) {
12400       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12401       // For the reciprocal, we need to find the zero of the function:
12402       //   F(X) = A X - 1 [which has a zero at X = 1/A]
12403       //     =>
12404       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
12405       //     does not require additional intermediate precision]
12406       EVT VT = Op.getValueType();
12407       SDLoc DL(Op);
12408       SDValue FPOne = DAG.getConstantFP(1.0, VT);
12410       AddToWorklist(Est.getNode());
12412       // Newton iterations: Est = Est + Est (1 - Arg * Est)
12413       for (unsigned i = 0; i < Iterations; ++i) {
12414         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
12415         AddToWorklist(NewEst.getNode());
12417         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
12418         AddToWorklist(NewEst.getNode());
12420         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12421         AddToWorklist(NewEst.getNode());
12423         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
12424         AddToWorklist(Est.getNode());
12425       }
12426     }
12427     return Est;
12428   }
12430   return SDValue();
12433 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12434 /// For the reciprocal sqrt, we need to find the zero of the function:
12435 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12436 ///     =>
12437 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12438 /// As a result, we precompute A/2 prior to the iteration loop.
12439 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
12440                                           unsigned Iterations) {
12441   EVT VT = Arg.getValueType();
12442   SDLoc DL(Arg);
12443   SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
12445   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12446   // this entire sequence requires only one FP constant.
12447   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12448   AddToWorklist(HalfArg.getNode());
12450   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12451   AddToWorklist(HalfArg.getNode());
12453   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12454   for (unsigned i = 0; i < Iterations; ++i) {
12455     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12456     AddToWorklist(NewEst.getNode());
12458     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12459     AddToWorklist(NewEst.getNode());
12461     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
12462     AddToWorklist(NewEst.getNode());
12464     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12465     AddToWorklist(Est.getNode());
12466   }
12467   return Est;
12470 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12471 /// For the reciprocal sqrt, we need to find the zero of the function:
12472 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12473 ///     =>
12474 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
12475 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
12476                                           unsigned Iterations) {
12477   EVT VT = Arg.getValueType();
12478   SDLoc DL(Arg);
12479   SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
12480   SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
12482   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
12483   for (unsigned i = 0; i < Iterations; ++i) {
12484     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
12485     AddToWorklist(HalfEst.getNode());
12487     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12488     AddToWorklist(Est.getNode());
12490     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
12491     AddToWorklist(Est.getNode());
12493     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
12494     AddToWorklist(Est.getNode());
12496     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
12497     AddToWorklist(Est.getNode());
12498   }
12499   return Est;
12502 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
12503   if (Level >= AfterLegalizeDAG)
12504     return SDValue();
12506   // Expose the DAG combiner to the target combiner implementations.
12507   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12508   unsigned Iterations = 0;
12509   bool UseOneConstNR = false;
12510   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
12511     AddToWorklist(Est.getNode());
12512     if (Iterations) {
12513       Est = UseOneConstNR ?
12514         BuildRsqrtNROneConst(Op, Est, Iterations) :
12515         BuildRsqrtNRTwoConst(Op, Est, Iterations);
12516     }
12517     return Est;
12518   }
12520   return SDValue();
12523 /// Return true if base is a frame index, which is known not to alias with
12524 /// anything but itself.  Provides base object and offset as results.
12525 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
12526                            const GlobalValue *&GV, const void *&CV) {
12527   // Assume it is a primitive operation.
12528   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
12530   // If it's an adding a simple constant then integrate the offset.
12531   if (Base.getOpcode() == ISD::ADD) {
12532     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
12533       Base = Base.getOperand(0);
12534       Offset += C->getZExtValue();
12535     }
12536   }
12538   // Return the underlying GlobalValue, and update the Offset.  Return false
12539   // for GlobalAddressSDNode since the same GlobalAddress may be represented
12540   // by multiple nodes with different offsets.
12541   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
12542     GV = G->getGlobal();
12543     Offset += G->getOffset();
12544     return false;
12545   }
12547   // Return the underlying Constant value, and update the Offset.  Return false
12548   // for ConstantSDNodes since the same constant pool entry may be represented
12549   // by multiple nodes with different offsets.
12550   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
12551     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
12552                                          : (const void *)C->getConstVal();
12553     Offset += C->getOffset();
12554     return false;
12555   }
12556   // If it's any of the following then it can't alias with anything but itself.
12557   return isa<FrameIndexSDNode>(Base);
12560 /// Return true if there is any possibility that the two addresses overlap.
12561 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
12562   // If they are the same then they must be aliases.
12563   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
12565   // If they are both volatile then they cannot be reordered.
12566   if (Op0->isVolatile() && Op1->isVolatile()) return true;
12568   // Gather base node and offset information.
12569   SDValue Base1, Base2;
12570   int64_t Offset1, Offset2;
12571   const GlobalValue *GV1, *GV2;
12572   const void *CV1, *CV2;
12573   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
12574                                       Base1, Offset1, GV1, CV1);
12575   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
12576                                       Base2, Offset2, GV2, CV2);
12578   // If they have a same base address then check to see if they overlap.
12579   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
12580     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12581              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12583   // It is possible for different frame indices to alias each other, mostly
12584   // when tail call optimization reuses return address slots for arguments.
12585   // To catch this case, look up the actual index of frame indices to compute
12586   // the real alias relationship.
12587   if (isFrameIndex1 && isFrameIndex2) {
12588     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12589     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
12590     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
12591     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12592              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12593   }
12595   // Otherwise, if we know what the bases are, and they aren't identical, then
12596   // we know they cannot alias.
12597   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
12598     return false;
12600   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
12601   // compared to the size and offset of the access, we may be able to prove they
12602   // do not alias.  This check is conservative for now to catch cases created by
12603   // splitting vector types.
12604   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
12605       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
12606       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
12607        Op1->getMemoryVT().getSizeInBits() >> 3) &&
12608       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
12609     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
12610     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
12612     // There is no overlap between these relatively aligned accesses of similar
12613     // size, return no alias.
12614     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
12615         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
12616       return false;
12617   }
12619   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
12620                    ? CombinerGlobalAA
12621                    : DAG.getSubtarget().useAA();
12622 #ifndef NDEBUG
12623   if (CombinerAAOnlyFunc.getNumOccurrences() &&
12624       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12625     UseAA = false;
12626 #endif
12627   if (UseAA &&
12628       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
12629     // Use alias analysis information.
12630     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
12631                                  Op1->getSrcValueOffset());
12632     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
12633         Op0->getSrcValueOffset() - MinOffset;
12634     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
12635         Op1->getSrcValueOffset() - MinOffset;
12636     AliasAnalysis::AliasResult AAResult =
12637         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
12638                                          Overlap1,
12639                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
12640                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
12641                                          Overlap2,
12642                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
12643     if (AAResult == AliasAnalysis::NoAlias)
12644       return false;
12645   }
12647   // Otherwise we have to assume they alias.
12648   return true;
12651 /// Walk up chain skipping non-aliasing memory nodes,
12652 /// looking for aliasing nodes and adding them to the Aliases vector.
12653 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
12654                                    SmallVectorImpl<SDValue> &Aliases) {
12655   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
12656   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
12658   // Get alias information for node.
12659   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
12661   // Starting off.
12662   Chains.push_back(OriginalChain);
12663   unsigned Depth = 0;
12665   // Look at each chain and determine if it is an alias.  If so, add it to the
12666   // aliases list.  If not, then continue up the chain looking for the next
12667   // candidate.
12668   while (!Chains.empty()) {
12669     SDValue Chain = Chains.back();
12670     Chains.pop_back();
12672     // For TokenFactor nodes, look at each operand and only continue up the
12673     // chain until we find two aliases.  If we've seen two aliases, assume we'll
12674     // find more and revert to original chain since the xform is unlikely to be
12675     // profitable.
12676     //
12677     // FIXME: The depth check could be made to return the last non-aliasing
12678     // chain we found before we hit a tokenfactor rather than the original
12679     // chain.
12680     if (Depth > 6 || Aliases.size() == 2) {
12681       Aliases.clear();
12682       Aliases.push_back(OriginalChain);
12683       return;
12684     }
12686     // Don't bother if we've been before.
12687     if (!Visited.insert(Chain.getNode()).second)
12688       continue;
12690     switch (Chain.getOpcode()) {
12691     case ISD::EntryToken:
12692       // Entry token is ideal chain operand, but handled in FindBetterChain.
12693       break;
12695     case ISD::LOAD:
12696     case ISD::STORE: {
12697       // Get alias information for Chain.
12698       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
12699           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
12701       // If chain is alias then stop here.
12702       if (!(IsLoad && IsOpLoad) &&
12703           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
12704         Aliases.push_back(Chain);
12705       } else {
12706         // Look further up the chain.
12707         Chains.push_back(Chain.getOperand(0));
12708         ++Depth;
12709       }
12710       break;
12711     }
12713     case ISD::TokenFactor:
12714       // We have to check each of the operands of the token factor for "small"
12715       // token factors, so we queue them up.  Adding the operands to the queue
12716       // (stack) in reverse order maintains the original order and increases the
12717       // likelihood that getNode will find a matching token factor (CSE.)
12718       if (Chain.getNumOperands() > 16) {
12719         Aliases.push_back(Chain);
12720         break;
12721       }
12722       for (unsigned n = Chain.getNumOperands(); n;)
12723         Chains.push_back(Chain.getOperand(--n));
12724       ++Depth;
12725       break;
12727     default:
12728       // For all other instructions we will just have to take what we can get.
12729       Aliases.push_back(Chain);
12730       break;
12731     }
12732   }
12734   // We need to be careful here to also search for aliases through the
12735   // value operand of a store, etc. Consider the following situation:
12736   //   Token1 = ...
12737   //   L1 = load Token1, %52
12738   //   S1 = store Token1, L1, %51
12739   //   L2 = load Token1, %52+8
12740   //   S2 = store Token1, L2, %51+8
12741   //   Token2 = Token(S1, S2)
12742   //   L3 = load Token2, %53
12743   //   S3 = store Token2, L3, %52
12744   //   L4 = load Token2, %53+8
12745   //   S4 = store Token2, L4, %52+8
12746   // If we search for aliases of S3 (which loads address %52), and we look
12747   // only through the chain, then we'll miss the trivial dependence on L1
12748   // (which also loads from %52). We then might change all loads and
12749   // stores to use Token1 as their chain operand, which could result in
12750   // copying %53 into %52 before copying %52 into %51 (which should
12751   // happen first).
12752   //
12753   // The problem is, however, that searching for such data dependencies
12754   // can become expensive, and the cost is not directly related to the
12755   // chain depth. Instead, we'll rule out such configurations here by
12756   // insisting that we've visited all chain users (except for users
12757   // of the original chain, which is not necessary). When doing this,
12758   // we need to look through nodes we don't care about (otherwise, things
12759   // like register copies will interfere with trivial cases).
12761   SmallVector<const SDNode *, 16> Worklist;
12762   for (const SDNode *N : Visited)
12763     if (N != OriginalChain.getNode())
12764       Worklist.push_back(N);
12766   while (!Worklist.empty()) {
12767     const SDNode *M = Worklist.pop_back_val();
12769     // We have already visited M, and want to make sure we've visited any uses
12770     // of M that we care about. For uses that we've not visisted, and don't
12771     // care about, queue them to the worklist.
12773     for (SDNode::use_iterator UI = M->use_begin(),
12774          UIE = M->use_end(); UI != UIE; ++UI)
12775       if (UI.getUse().getValueType() == MVT::Other &&
12776           Visited.insert(*UI).second) {
12777         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
12778           // We've not visited this use, and we care about it (it could have an
12779           // ordering dependency with the original node).
12780           Aliases.clear();
12781           Aliases.push_back(OriginalChain);
12782           return;
12783         }
12785         // We've not visited this use, but we don't care about it. Mark it as
12786         // visited and enqueue it to the worklist.
12787         Worklist.push_back(*UI);
12788       }
12789   }
12792 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
12793 /// (aliasing node.)
12794 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
12795   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
12797   // Accumulate all the aliases to this node.
12798   GatherAllAliases(N, OldChain, Aliases);
12800   // If no operands then chain to entry token.
12801   if (Aliases.size() == 0)
12802     return DAG.getEntryNode();
12804   // If a single operand then chain to it.  We don't need to revisit it.
12805   if (Aliases.size() == 1)
12806     return Aliases[0];
12808   // Construct a custom tailored token factor.
12809   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
12812 /// This is the entry point for the file.
12813 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
12814                            CodeGenOpt::Level OptLevel) {
12815   /// This is the main entry point to this class.
12816   DAGCombiner(*this, AA, OptLevel).Run(Level);