]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - opencl/llvm.git/blob - lib/CodeGen/SelectionDAG/DAGCombiner.cpp
Revert "Revert '[DAGCombiner] Split up an indexed load if only the base pointer value...
[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/SmallPtrSet.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.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 visitFCOPYSIGN(SDNode *N);
280     SDValue visitSINT_TO_FP(SDNode *N);
281     SDValue visitUINT_TO_FP(SDNode *N);
282     SDValue visitFP_TO_SINT(SDNode *N);
283     SDValue visitFP_TO_UINT(SDNode *N);
284     SDValue visitFP_ROUND(SDNode *N);
285     SDValue visitFP_ROUND_INREG(SDNode *N);
286     SDValue visitFP_EXTEND(SDNode *N);
287     SDValue visitFNEG(SDNode *N);
288     SDValue visitFABS(SDNode *N);
289     SDValue visitFCEIL(SDNode *N);
290     SDValue visitFTRUNC(SDNode *N);
291     SDValue visitFFLOOR(SDNode *N);
292     SDValue visitBRCOND(SDNode *N);
293     SDValue visitBR_CC(SDNode *N);
294     SDValue visitLOAD(SDNode *N);
295     SDValue visitSTORE(SDNode *N);
296     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
297     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
298     SDValue visitBUILD_VECTOR(SDNode *N);
299     SDValue visitCONCAT_VECTORS(SDNode *N);
300     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
301     SDValue visitVECTOR_SHUFFLE(SDNode *N);
302     SDValue visitINSERT_SUBVECTOR(SDNode *N);
304     SDValue XformToShuffleWithZero(SDNode *N);
305     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
307     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
309     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
310     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
311     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
312     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
313                              SDValue N3, ISD::CondCode CC,
314                              bool NotExtCompare = false);
315     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
316                           SDLoc DL, bool foldBooleans = true);
318     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
319                            SDValue &CC) const;
320     bool isOneUseSetCC(SDValue N) const;
322     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
323                                          unsigned HiOp);
324     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
325     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
326     SDValue BuildSDIV(SDNode *N);
327     SDValue BuildSDIVPow2(SDNode *N);
328     SDValue BuildUDIV(SDNode *N);
329     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
330                                bool DemandHighBits = true);
331     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
332     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
333                               SDValue InnerPos, SDValue InnerNeg,
334                               unsigned PosOpcode, unsigned NegOpcode,
335                               SDLoc DL);
336     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
337     SDValue ReduceLoadWidth(SDNode *N);
338     SDValue ReduceLoadOpStoreWidth(SDNode *N);
339     SDValue TransformFPLoadStorePair(SDNode *N);
340     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
341     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
343     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
345     /// Walk up chain skipping non-aliasing memory nodes,
346     /// looking for aliasing nodes and adding them to the Aliases vector.
347     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
348                           SmallVectorImpl<SDValue> &Aliases);
350     /// Return true if there is any possibility that the two addresses overlap.
351     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
353     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
354     /// chain (aliasing node.)
355     SDValue FindBetterChain(SDNode *N, SDValue Chain);
357     /// Merge consecutive store operations into a wide store.
358     /// This optimization uses wide integers or vectors when possible.
359     /// \return True if some memory operations were changed.
360     bool MergeConsecutiveStores(StoreSDNode *N);
362     /// \brief Try to transform a truncation where C is a constant:
363     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
364     ///
365     /// \p N needs to be a truncation and its first operand an AND. Other
366     /// requirements are checked by the function (e.g. that trunc is
367     /// single-use) and if missed an empty SDValue is returned.
368     SDValue distributeTruncateThroughAnd(SDNode *N);
370   public:
371     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
372         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
373           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
374       AttributeSet FnAttrs =
375           DAG.getMachineFunction().getFunction()->getAttributes();
376       ForCodeSize =
377           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
378                                Attribute::OptimizeForSize) ||
379           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
380     }
382     /// Runs the dag combiner on all nodes in the work list
383     void Run(CombineLevel AtLevel);
385     SelectionDAG &getDAG() const { return DAG; }
387     /// Returns a type large enough to hold any valid shift amount - before type
388     /// legalization these can be huge.
389     EVT getShiftAmountTy(EVT LHSTy) {
390       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
391       if (LHSTy.isVector())
392         return LHSTy;
393       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
394                         : TLI.getPointerTy();
395     }
397     /// This method returns true if we are running before type legalization or
398     /// if the specified VT is legal.
399     bool isTypeLegal(const EVT &VT) {
400       if (!LegalTypes) return true;
401       return TLI.isTypeLegal(VT);
402     }
404     /// Convenience wrapper around TargetLowering::getSetCCResultType
405     EVT getSetCCResultType(EVT VT) const {
406       return TLI.getSetCCResultType(*DAG.getContext(), VT);
407     }
408   };
412 namespace {
413 /// This class is a DAGUpdateListener that removes any deleted
414 /// nodes from the worklist.
415 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
416   DAGCombiner &DC;
417 public:
418   explicit WorklistRemover(DAGCombiner &dc)
419     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
421   void NodeDeleted(SDNode *N, SDNode *E) override {
422     DC.removeFromWorklist(N);
423   }
424 };
427 //===----------------------------------------------------------------------===//
428 //  TargetLowering::DAGCombinerInfo implementation
429 //===----------------------------------------------------------------------===//
431 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
432   ((DAGCombiner*)DC)->AddToWorklist(N);
435 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
436   ((DAGCombiner*)DC)->removeFromWorklist(N);
439 SDValue TargetLowering::DAGCombinerInfo::
440 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
441   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
444 SDValue TargetLowering::DAGCombinerInfo::
445 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
446   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
450 SDValue TargetLowering::DAGCombinerInfo::
451 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
452   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
455 void TargetLowering::DAGCombinerInfo::
456 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
457   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
460 //===----------------------------------------------------------------------===//
461 // Helper Functions
462 //===----------------------------------------------------------------------===//
464 void DAGCombiner::deleteAndRecombine(SDNode *N) {
465   removeFromWorklist(N);
467   // If the operands of this node are only used by the node, they will now be
468   // dead. Make sure to re-visit them and recursively delete dead nodes.
469   for (const SDValue &Op : N->ops())
470     // For an operand generating multiple values, one of the values may
471     // become dead allowing further simplification (e.g. split index
472     // arithmetic from an indexed load).
473     if (Op->hasOneUse() || Op->getNumValues() > 1)
474       AddToWorklist(Op.getNode());
476   DAG.DeleteNode(N);
479 /// Return 1 if we can compute the negated form of the specified expression for
480 /// the same cost as the expression itself, or 2 if we can compute the negated
481 /// form more cheaply than the expression itself.
482 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
483                                const TargetLowering &TLI,
484                                const TargetOptions *Options,
485                                unsigned Depth = 0) {
486   // fneg is removable even if it has multiple uses.
487   if (Op.getOpcode() == ISD::FNEG) return 2;
489   // Don't allow anything with multiple uses.
490   if (!Op.hasOneUse()) return 0;
492   // Don't recurse exponentially.
493   if (Depth > 6) return 0;
495   switch (Op.getOpcode()) {
496   default: return false;
497   case ISD::ConstantFP:
498     // Don't invert constant FP values after legalize.  The negated constant
499     // isn't necessarily legal.
500     return LegalOperations ? 0 : 1;
501   case ISD::FADD:
502     // FIXME: determine better conditions for this xform.
503     if (!Options->UnsafeFPMath) return 0;
505     // After operation legalization, it might not be legal to create new FSUBs.
506     if (LegalOperations &&
507         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
508       return 0;
510     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
511     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
512                                     Options, Depth + 1))
513       return V;
514     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
515     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
516                               Depth + 1);
517   case ISD::FSUB:
518     // We can't turn -(A-B) into B-A when we honor signed zeros.
519     if (!Options->UnsafeFPMath) return 0;
521     // fold (fneg (fsub A, B)) -> (fsub B, A)
522     return 1;
524   case ISD::FMUL:
525   case ISD::FDIV:
526     if (Options->HonorSignDependentRoundingFPMath()) return 0;
528     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
529     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
530                                     Options, Depth + 1))
531       return V;
533     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
534                               Depth + 1);
536   case ISD::FP_EXTEND:
537   case ISD::FP_ROUND:
538   case ISD::FSIN:
539     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
540                               Depth + 1);
541   }
544 /// If isNegatibleForFree returns true, return the newly negated expression.
545 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
546                                     bool LegalOperations, unsigned Depth = 0) {
547   const TargetOptions &Options = DAG.getTarget().Options;
548   // fneg is removable even if it has multiple uses.
549   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
551   // Don't allow anything with multiple uses.
552   assert(Op.hasOneUse() && "Unknown reuse!");
554   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
555   switch (Op.getOpcode()) {
556   default: llvm_unreachable("Unknown code");
557   case ISD::ConstantFP: {
558     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
559     V.changeSign();
560     return DAG.getConstantFP(V, Op.getValueType());
561   }
562   case ISD::FADD:
563     // FIXME: determine better conditions for this xform.
564     assert(Options.UnsafeFPMath);
566     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
567     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
568                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
569       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
570                          GetNegatedExpression(Op.getOperand(0), DAG,
571                                               LegalOperations, Depth+1),
572                          Op.getOperand(1));
573     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
574     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
575                        GetNegatedExpression(Op.getOperand(1), DAG,
576                                             LegalOperations, Depth+1),
577                        Op.getOperand(0));
578   case ISD::FSUB:
579     // We can't turn -(A-B) into B-A when we honor signed zeros.
580     assert(Options.UnsafeFPMath);
582     // fold (fneg (fsub 0, B)) -> B
583     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
584       if (N0CFP->getValueAPF().isZero())
585         return Op.getOperand(1);
587     // fold (fneg (fsub A, B)) -> (fsub B, A)
588     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
589                        Op.getOperand(1), Op.getOperand(0));
591   case ISD::FMUL:
592   case ISD::FDIV:
593     assert(!Options.HonorSignDependentRoundingFPMath());
595     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
596     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
597                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
598       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
599                          GetNegatedExpression(Op.getOperand(0), DAG,
600                                               LegalOperations, Depth+1),
601                          Op.getOperand(1));
603     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
604     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
605                        Op.getOperand(0),
606                        GetNegatedExpression(Op.getOperand(1), DAG,
607                                             LegalOperations, Depth+1));
609   case ISD::FP_EXTEND:
610   case ISD::FSIN:
611     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
612                        GetNegatedExpression(Op.getOperand(0), DAG,
613                                             LegalOperations, Depth+1));
614   case ISD::FP_ROUND:
615       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
616                          GetNegatedExpression(Op.getOperand(0), DAG,
617                                               LegalOperations, Depth+1),
618                          Op.getOperand(1));
619   }
622 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
623 // that selects between the target values used for true and false, making it
624 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
625 // the appropriate nodes based on the type of node we are checking. This
626 // simplifies life a bit for the callers.
627 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
628                                     SDValue &CC) const {
629   if (N.getOpcode() == ISD::SETCC) {
630     LHS = N.getOperand(0);
631     RHS = N.getOperand(1);
632     CC  = N.getOperand(2);
633     return true;
634   }
636   if (N.getOpcode() != ISD::SELECT_CC ||
637       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
638       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
639     return false;
641   LHS = N.getOperand(0);
642   RHS = N.getOperand(1);
643   CC  = N.getOperand(4);
644   return true;
647 /// Return true if this is a SetCC-equivalent operation with only one use.
648 /// If this is true, it allows the users to invert the operation for free when
649 /// it is profitable to do so.
650 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
651   SDValue N0, N1, N2;
652   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
653     return true;
654   return false;
657 /// Returns true if N is a BUILD_VECTOR node whose
658 /// elements are all the same constant or undefined.
659 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
660   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
661   if (!C)
662     return false;
664   APInt SplatUndef;
665   unsigned SplatBitSize;
666   bool HasAnyUndefs;
667   EVT EltVT = N->getValueType(0).getVectorElementType();
668   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
669                              HasAnyUndefs) &&
670           EltVT.getSizeInBits() >= SplatBitSize);
673 // \brief Returns the SDNode if it is a constant BuildVector or constant.
674 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
675   if (isa<ConstantSDNode>(N))
676     return N.getNode();
677   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
678   if(BV && BV->isConstant())
679     return BV;
680   return nullptr;
683 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
684 // int.
685 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
686   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
687     return CN;
689   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
690     BitVector UndefElements;
691     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
693     // BuildVectors can truncate their operands. Ignore that case here.
694     // FIXME: We blindly ignore splats which include undef which is overly
695     // pessimistic.
696     if (CN && UndefElements.none() &&
697         CN->getValueType(0) == N.getValueType().getScalarType())
698       return CN;
699   }
701   return nullptr;
704 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
705 // float.
706 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
707   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
708     return CN;
710   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
711     BitVector UndefElements;
712     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
714     // BuildVectors can truncate their operands. Ignore that case here.
715     // FIXME: We blindly ignore splats which include undef which is overly
716     // pessimistic.
717     if (CN && UndefElements.none() &&
718         CN->getValueType(0) == N.getValueType().getScalarType())
719       return CN;
720   }
722   return nullptr;
725 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
726                                     SDValue N0, SDValue N1) {
727   EVT VT = N0.getValueType();
728   if (N0.getOpcode() == Opc) {
729     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
730       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
731         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
732         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
733         if (!OpNode.getNode())
734           return SDValue();
735         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
736       }
737       if (N0.hasOneUse()) {
738         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
739         // use
740         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
741         if (!OpNode.getNode())
742           return SDValue();
743         AddToWorklist(OpNode.getNode());
744         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
745       }
746     }
747   }
749   if (N1.getOpcode() == Opc) {
750     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
751       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
752         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
753         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
754         if (!OpNode.getNode())
755           return SDValue();
756         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
757       }
758       if (N1.hasOneUse()) {
759         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
760         // use
761         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
762         if (!OpNode.getNode())
763           return SDValue();
764         AddToWorklist(OpNode.getNode());
765         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
766       }
767     }
768   }
770   return SDValue();
773 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
774                                bool AddTo) {
775   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
776   ++NodesCombined;
777   DEBUG(dbgs() << "\nReplacing.1 ";
778         N->dump(&DAG);
779         dbgs() << "\nWith: ";
780         To[0].getNode()->dump(&DAG);
781         dbgs() << " and " << NumTo-1 << " other values\n";
782         for (unsigned i = 0, e = NumTo; i != e; ++i)
783           assert((!To[i].getNode() ||
784                   N->getValueType(i) == To[i].getValueType()) &&
785                  "Cannot combine value to value of different type!"));
786   WorklistRemover DeadNodes(*this);
787   DAG.ReplaceAllUsesWith(N, To);
788   if (AddTo) {
789     // Push the new nodes and any users onto the worklist
790     for (unsigned i = 0, e = NumTo; i != e; ++i) {
791       if (To[i].getNode()) {
792         AddToWorklist(To[i].getNode());
793         AddUsersToWorklist(To[i].getNode());
794       }
795     }
796   }
798   // Finally, if the node is now dead, remove it from the graph.  The node
799   // may not be dead if the replacement process recursively simplified to
800   // something else needing this node.
801   if (N->use_empty())
802     deleteAndRecombine(N);
803   return SDValue(N, 0);
806 void DAGCombiner::
807 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
808   // Replace all uses.  If any nodes become isomorphic to other nodes and
809   // are deleted, make sure to remove them from our worklist.
810   WorklistRemover DeadNodes(*this);
811   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
813   // Push the new node and any (possibly new) users onto the worklist.
814   AddToWorklist(TLO.New.getNode());
815   AddUsersToWorklist(TLO.New.getNode());
817   // Finally, if the node is now dead, remove it from the graph.  The node
818   // may not be dead if the replacement process recursively simplified to
819   // something else needing this node.
820   if (TLO.Old.getNode()->use_empty())
821     deleteAndRecombine(TLO.Old.getNode());
824 /// Check the specified integer node value to see if it can be simplified or if
825 /// things it uses can be simplified by bit propagation. If so, return true.
826 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
827   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
828   APInt KnownZero, KnownOne;
829   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
830     return false;
832   // Revisit the node.
833   AddToWorklist(Op.getNode());
835   // Replace the old value with the new one.
836   ++NodesCombined;
837   DEBUG(dbgs() << "\nReplacing.2 ";
838         TLO.Old.getNode()->dump(&DAG);
839         dbgs() << "\nWith: ";
840         TLO.New.getNode()->dump(&DAG);
841         dbgs() << '\n');
843   CommitTargetLoweringOpt(TLO);
844   return true;
847 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
848   SDLoc dl(Load);
849   EVT VT = Load->getValueType(0);
850   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
852   DEBUG(dbgs() << "\nReplacing.9 ";
853         Load->dump(&DAG);
854         dbgs() << "\nWith: ";
855         Trunc.getNode()->dump(&DAG);
856         dbgs() << '\n');
857   WorklistRemover DeadNodes(*this);
858   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
859   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
860   deleteAndRecombine(Load);
861   AddToWorklist(Trunc.getNode());
864 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
865   Replace = false;
866   SDLoc dl(Op);
867   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
868     EVT MemVT = LD->getMemoryVT();
869     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
870       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
871                                                   : ISD::EXTLOAD)
872       : LD->getExtensionType();
873     Replace = true;
874     return DAG.getExtLoad(ExtType, dl, PVT,
875                           LD->getChain(), LD->getBasePtr(),
876                           MemVT, LD->getMemOperand());
877   }
879   unsigned Opc = Op.getOpcode();
880   switch (Opc) {
881   default: break;
882   case ISD::AssertSext:
883     return DAG.getNode(ISD::AssertSext, dl, PVT,
884                        SExtPromoteOperand(Op.getOperand(0), PVT),
885                        Op.getOperand(1));
886   case ISD::AssertZext:
887     return DAG.getNode(ISD::AssertZext, dl, PVT,
888                        ZExtPromoteOperand(Op.getOperand(0), PVT),
889                        Op.getOperand(1));
890   case ISD::Constant: {
891     unsigned ExtOpc =
892       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
893     return DAG.getNode(ExtOpc, dl, PVT, Op);
894   }
895   }
897   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
898     return SDValue();
899   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
902 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
903   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
904     return SDValue();
905   EVT OldVT = Op.getValueType();
906   SDLoc dl(Op);
907   bool Replace = false;
908   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
909   if (!NewOp.getNode())
910     return SDValue();
911   AddToWorklist(NewOp.getNode());
913   if (Replace)
914     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
915   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
916                      DAG.getValueType(OldVT));
919 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
920   EVT OldVT = Op.getValueType();
921   SDLoc dl(Op);
922   bool Replace = false;
923   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
924   if (!NewOp.getNode())
925     return SDValue();
926   AddToWorklist(NewOp.getNode());
928   if (Replace)
929     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
930   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
933 /// Promote the specified integer binary operation if the target indicates it is
934 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
935 /// i32 since i16 instructions are longer.
936 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
937   if (!LegalOperations)
938     return SDValue();
940   EVT VT = Op.getValueType();
941   if (VT.isVector() || !VT.isInteger())
942     return SDValue();
944   // If operation type is 'undesirable', e.g. i16 on x86, consider
945   // promoting it.
946   unsigned Opc = Op.getOpcode();
947   if (TLI.isTypeDesirableForOp(Opc, VT))
948     return SDValue();
950   EVT PVT = VT;
951   // Consult target whether it is a good idea to promote this operation and
952   // what's the right type to promote it to.
953   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
954     assert(PVT != VT && "Don't know what type to promote to!");
956     bool Replace0 = false;
957     SDValue N0 = Op.getOperand(0);
958     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
959     if (!NN0.getNode())
960       return SDValue();
962     bool Replace1 = false;
963     SDValue N1 = Op.getOperand(1);
964     SDValue NN1;
965     if (N0 == N1)
966       NN1 = NN0;
967     else {
968       NN1 = PromoteOperand(N1, PVT, Replace1);
969       if (!NN1.getNode())
970         return SDValue();
971     }
973     AddToWorklist(NN0.getNode());
974     if (NN1.getNode())
975       AddToWorklist(NN1.getNode());
977     if (Replace0)
978       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
979     if (Replace1)
980       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
982     DEBUG(dbgs() << "\nPromoting ";
983           Op.getNode()->dump(&DAG));
984     SDLoc dl(Op);
985     return DAG.getNode(ISD::TRUNCATE, dl, VT,
986                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
987   }
988   return SDValue();
991 /// Promote the specified integer shift operation if the target indicates it is
992 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
993 /// i32 since i16 instructions are longer.
994 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
995   if (!LegalOperations)
996     return SDValue();
998   EVT VT = Op.getValueType();
999   if (VT.isVector() || !VT.isInteger())
1000     return SDValue();
1002   // If operation type is 'undesirable', e.g. i16 on x86, consider
1003   // promoting it.
1004   unsigned Opc = Op.getOpcode();
1005   if (TLI.isTypeDesirableForOp(Opc, VT))
1006     return SDValue();
1008   EVT PVT = VT;
1009   // Consult target whether it is a good idea to promote this operation and
1010   // what's the right type to promote it to.
1011   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1012     assert(PVT != VT && "Don't know what type to promote to!");
1014     bool Replace = false;
1015     SDValue N0 = Op.getOperand(0);
1016     if (Opc == ISD::SRA)
1017       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1018     else if (Opc == ISD::SRL)
1019       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1020     else
1021       N0 = PromoteOperand(N0, PVT, Replace);
1022     if (!N0.getNode())
1023       return SDValue();
1025     AddToWorklist(N0.getNode());
1026     if (Replace)
1027       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1029     DEBUG(dbgs() << "\nPromoting ";
1030           Op.getNode()->dump(&DAG));
1031     SDLoc dl(Op);
1032     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1033                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1034   }
1035   return SDValue();
1038 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1039   if (!LegalOperations)
1040     return SDValue();
1042   EVT VT = Op.getValueType();
1043   if (VT.isVector() || !VT.isInteger())
1044     return SDValue();
1046   // If operation type is 'undesirable', e.g. i16 on x86, consider
1047   // promoting it.
1048   unsigned Opc = Op.getOpcode();
1049   if (TLI.isTypeDesirableForOp(Opc, VT))
1050     return SDValue();
1052   EVT PVT = VT;
1053   // Consult target whether it is a good idea to promote this operation and
1054   // what's the right type to promote it to.
1055   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1056     assert(PVT != VT && "Don't know what type to promote to!");
1057     // fold (aext (aext x)) -> (aext x)
1058     // fold (aext (zext x)) -> (zext x)
1059     // fold (aext (sext x)) -> (sext x)
1060     DEBUG(dbgs() << "\nPromoting ";
1061           Op.getNode()->dump(&DAG));
1062     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1063   }
1064   return SDValue();
1067 bool DAGCombiner::PromoteLoad(SDValue Op) {
1068   if (!LegalOperations)
1069     return false;
1071   EVT VT = Op.getValueType();
1072   if (VT.isVector() || !VT.isInteger())
1073     return false;
1075   // If operation type is 'undesirable', e.g. i16 on x86, consider
1076   // promoting it.
1077   unsigned Opc = Op.getOpcode();
1078   if (TLI.isTypeDesirableForOp(Opc, VT))
1079     return false;
1081   EVT PVT = VT;
1082   // Consult target whether it is a good idea to promote this operation and
1083   // what's the right type to promote it to.
1084   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1085     assert(PVT != VT && "Don't know what type to promote to!");
1087     SDLoc dl(Op);
1088     SDNode *N = Op.getNode();
1089     LoadSDNode *LD = cast<LoadSDNode>(N);
1090     EVT MemVT = LD->getMemoryVT();
1091     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1092       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1093                                                   : ISD::EXTLOAD)
1094       : LD->getExtensionType();
1095     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1096                                    LD->getChain(), LD->getBasePtr(),
1097                                    MemVT, LD->getMemOperand());
1098     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1100     DEBUG(dbgs() << "\nPromoting ";
1101           N->dump(&DAG);
1102           dbgs() << "\nTo: ";
1103           Result.getNode()->dump(&DAG);
1104           dbgs() << '\n');
1105     WorklistRemover DeadNodes(*this);
1106     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1107     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1108     deleteAndRecombine(N);
1109     AddToWorklist(Result.getNode());
1110     return true;
1111   }
1112   return false;
1115 /// \brief Recursively delete a node which has no uses and any operands for
1116 /// which it is the only use.
1117 ///
1118 /// Note that this both deletes the nodes and removes them from the worklist.
1119 /// It also adds any nodes who have had a user deleted to the worklist as they
1120 /// may now have only one use and subject to other combines.
1121 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1122   if (!N->use_empty())
1123     return false;
1125   SmallSetVector<SDNode *, 16> Nodes;
1126   Nodes.insert(N);
1127   do {
1128     N = Nodes.pop_back_val();
1129     if (!N)
1130       continue;
1132     if (N->use_empty()) {
1133       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1134         Nodes.insert(N->getOperand(i).getNode());
1136       removeFromWorklist(N);
1137       DAG.DeleteNode(N);
1138     } else {
1139       AddToWorklist(N);
1140     }
1141   } while (!Nodes.empty());
1142   return true;
1145 //===----------------------------------------------------------------------===//
1146 //  Main DAG Combiner implementation
1147 //===----------------------------------------------------------------------===//
1149 void DAGCombiner::Run(CombineLevel AtLevel) {
1150   // set the instance variables, so that the various visit routines may use it.
1151   Level = AtLevel;
1152   LegalOperations = Level >= AfterLegalizeVectorOps;
1153   LegalTypes = Level >= AfterLegalizeTypes;
1155   // Add all the dag nodes to the worklist.
1156   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1157        E = DAG.allnodes_end(); I != E; ++I)
1158     AddToWorklist(I);
1160   // Create a dummy node (which is not added to allnodes), that adds a reference
1161   // to the root node, preventing it from being deleted, and tracking any
1162   // changes of the root.
1163   HandleSDNode Dummy(DAG.getRoot());
1165   // while the worklist isn't empty, find a node and
1166   // try and combine it.
1167   while (!WorklistMap.empty()) {
1168     SDNode *N;
1169     // The Worklist holds the SDNodes in order, but it may contain null entries.
1170     do {
1171       N = Worklist.pop_back_val();
1172     } while (!N);
1174     bool GoodWorklistEntry = WorklistMap.erase(N);
1175     (void)GoodWorklistEntry;
1176     assert(GoodWorklistEntry &&
1177            "Found a worklist entry without a corresponding map entry!");
1179     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1180     // N is deleted from the DAG, since they too may now be dead or may have a
1181     // reduced number of uses, allowing other xforms.
1182     if (recursivelyDeleteUnusedNodes(N))
1183       continue;
1185     WorklistRemover DeadNodes(*this);
1187     // If this combine is running after legalizing the DAG, re-legalize any
1188     // nodes pulled off the worklist.
1189     if (Level == AfterLegalizeDAG) {
1190       SmallSetVector<SDNode *, 16> UpdatedNodes;
1191       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1193       for (SDNode *LN : UpdatedNodes) {
1194         AddToWorklist(LN);
1195         AddUsersToWorklist(LN);
1196       }
1197       if (!NIsValid)
1198         continue;
1199     }
1201     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1203     // Add any operands of the new node which have not yet been combined to the
1204     // worklist as well. Because the worklist uniques things already, this
1205     // won't repeatedly process the same operand.
1206     CombinedNodes.insert(N);
1207     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1208       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1209         AddToWorklist(N->getOperand(i).getNode());
1211     SDValue RV = combine(N);
1213     if (!RV.getNode())
1214       continue;
1216     ++NodesCombined;
1218     // If we get back the same node we passed in, rather than a new node or
1219     // zero, we know that the node must have defined multiple values and
1220     // CombineTo was used.  Since CombineTo takes care of the worklist
1221     // mechanics for us, we have no work to do in this case.
1222     if (RV.getNode() == N)
1223       continue;
1225     assert(N->getOpcode() != ISD::DELETED_NODE &&
1226            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1227            "Node was deleted but visit returned new node!");
1229     DEBUG(dbgs() << " ... into: ";
1230           RV.getNode()->dump(&DAG));
1232     // Transfer debug value.
1233     DAG.TransferDbgValues(SDValue(N, 0), RV);
1234     if (N->getNumValues() == RV.getNode()->getNumValues())
1235       DAG.ReplaceAllUsesWith(N, RV.getNode());
1236     else {
1237       assert(N->getValueType(0) == RV.getValueType() &&
1238              N->getNumValues() == 1 && "Type mismatch");
1239       SDValue OpV = RV;
1240       DAG.ReplaceAllUsesWith(N, &OpV);
1241     }
1243     // Push the new node and any users onto the worklist
1244     AddToWorklist(RV.getNode());
1245     AddUsersToWorklist(RV.getNode());
1247     // Finally, if the node is now dead, remove it from the graph.  The node
1248     // may not be dead if the replacement process recursively simplified to
1249     // something else needing this node. This will also take care of adding any
1250     // operands which have lost a user to the worklist.
1251     recursivelyDeleteUnusedNodes(N);
1252   }
1254   // If the root changed (e.g. it was a dead load, update the root).
1255   DAG.setRoot(Dummy.getValue());
1256   DAG.RemoveDeadNodes();
1259 SDValue DAGCombiner::visit(SDNode *N) {
1260   switch (N->getOpcode()) {
1261   default: break;
1262   case ISD::TokenFactor:        return visitTokenFactor(N);
1263   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1264   case ISD::ADD:                return visitADD(N);
1265   case ISD::SUB:                return visitSUB(N);
1266   case ISD::ADDC:               return visitADDC(N);
1267   case ISD::SUBC:               return visitSUBC(N);
1268   case ISD::ADDE:               return visitADDE(N);
1269   case ISD::SUBE:               return visitSUBE(N);
1270   case ISD::MUL:                return visitMUL(N);
1271   case ISD::SDIV:               return visitSDIV(N);
1272   case ISD::UDIV:               return visitUDIV(N);
1273   case ISD::SREM:               return visitSREM(N);
1274   case ISD::UREM:               return visitUREM(N);
1275   case ISD::MULHU:              return visitMULHU(N);
1276   case ISD::MULHS:              return visitMULHS(N);
1277   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1278   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1279   case ISD::SMULO:              return visitSMULO(N);
1280   case ISD::UMULO:              return visitUMULO(N);
1281   case ISD::SDIVREM:            return visitSDIVREM(N);
1282   case ISD::UDIVREM:            return visitUDIVREM(N);
1283   case ISD::AND:                return visitAND(N);
1284   case ISD::OR:                 return visitOR(N);
1285   case ISD::XOR:                return visitXOR(N);
1286   case ISD::SHL:                return visitSHL(N);
1287   case ISD::SRA:                return visitSRA(N);
1288   case ISD::SRL:                return visitSRL(N);
1289   case ISD::ROTR:
1290   case ISD::ROTL:               return visitRotate(N);
1291   case ISD::CTLZ:               return visitCTLZ(N);
1292   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1293   case ISD::CTTZ:               return visitCTTZ(N);
1294   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1295   case ISD::CTPOP:              return visitCTPOP(N);
1296   case ISD::SELECT:             return visitSELECT(N);
1297   case ISD::VSELECT:            return visitVSELECT(N);
1298   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1299   case ISD::SETCC:              return visitSETCC(N);
1300   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1301   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1302   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1303   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1304   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1305   case ISD::BITCAST:            return visitBITCAST(N);
1306   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1307   case ISD::FADD:               return visitFADD(N);
1308   case ISD::FSUB:               return visitFSUB(N);
1309   case ISD::FMUL:               return visitFMUL(N);
1310   case ISD::FMA:                return visitFMA(N);
1311   case ISD::FDIV:               return visitFDIV(N);
1312   case ISD::FREM:               return visitFREM(N);
1313   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1314   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1315   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1316   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1317   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1318   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1319   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1320   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1321   case ISD::FNEG:               return visitFNEG(N);
1322   case ISD::FABS:               return visitFABS(N);
1323   case ISD::FFLOOR:             return visitFFLOOR(N);
1324   case ISD::FCEIL:              return visitFCEIL(N);
1325   case ISD::FTRUNC:             return visitFTRUNC(N);
1326   case ISD::BRCOND:             return visitBRCOND(N);
1327   case ISD::BR_CC:              return visitBR_CC(N);
1328   case ISD::LOAD:               return visitLOAD(N);
1329   case ISD::STORE:              return visitSTORE(N);
1330   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1331   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1332   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1333   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1334   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1335   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1336   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1337   }
1338   return SDValue();
1341 SDValue DAGCombiner::combine(SDNode *N) {
1342   SDValue RV = visit(N);
1344   // If nothing happened, try a target-specific DAG combine.
1345   if (!RV.getNode()) {
1346     assert(N->getOpcode() != ISD::DELETED_NODE &&
1347            "Node was deleted but visit returned NULL!");
1349     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1350         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1352       // Expose the DAG combiner to the target combiner impls.
1353       TargetLowering::DAGCombinerInfo
1354         DagCombineInfo(DAG, Level, false, this);
1356       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1357     }
1358   }
1360   // If nothing happened still, try promoting the operation.
1361   if (!RV.getNode()) {
1362     switch (N->getOpcode()) {
1363     default: break;
1364     case ISD::ADD:
1365     case ISD::SUB:
1366     case ISD::MUL:
1367     case ISD::AND:
1368     case ISD::OR:
1369     case ISD::XOR:
1370       RV = PromoteIntBinOp(SDValue(N, 0));
1371       break;
1372     case ISD::SHL:
1373     case ISD::SRA:
1374     case ISD::SRL:
1375       RV = PromoteIntShiftOp(SDValue(N, 0));
1376       break;
1377     case ISD::SIGN_EXTEND:
1378     case ISD::ZERO_EXTEND:
1379     case ISD::ANY_EXTEND:
1380       RV = PromoteExtend(SDValue(N, 0));
1381       break;
1382     case ISD::LOAD:
1383       if (PromoteLoad(SDValue(N, 0)))
1384         RV = SDValue(N, 0);
1385       break;
1386     }
1387   }
1389   // If N is a commutative binary node, try commuting it to enable more
1390   // sdisel CSE.
1391   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1392       N->getNumValues() == 1) {
1393     SDValue N0 = N->getOperand(0);
1394     SDValue N1 = N->getOperand(1);
1396     // Constant operands are canonicalized to RHS.
1397     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1398       SDValue Ops[] = {N1, N0};
1399       SDNode *CSENode;
1400       if (const BinaryWithFlagsSDNode *BinNode =
1401               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1402         CSENode = DAG.getNodeIfExists(
1403             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1404             BinNode->hasNoSignedWrap(), BinNode->isExact());
1405       } else {
1406         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1407       }
1408       if (CSENode)
1409         return SDValue(CSENode, 0);
1410     }
1411   }
1413   return RV;
1416 /// Given a node, return its input chain if it has one, otherwise return a null
1417 /// sd operand.
1418 static SDValue getInputChainForNode(SDNode *N) {
1419   if (unsigned NumOps = N->getNumOperands()) {
1420     if (N->getOperand(0).getValueType() == MVT::Other)
1421       return N->getOperand(0);
1422     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1423       return N->getOperand(NumOps-1);
1424     for (unsigned i = 1; i < NumOps-1; ++i)
1425       if (N->getOperand(i).getValueType() == MVT::Other)
1426         return N->getOperand(i);
1427   }
1428   return SDValue();
1431 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1432   // If N has two operands, where one has an input chain equal to the other,
1433   // the 'other' chain is redundant.
1434   if (N->getNumOperands() == 2) {
1435     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1436       return N->getOperand(0);
1437     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1438       return N->getOperand(1);
1439   }
1441   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1442   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1443   SmallPtrSet<SDNode*, 16> SeenOps;
1444   bool Changed = false;             // If we should replace this token factor.
1446   // Start out with this token factor.
1447   TFs.push_back(N);
1449   // Iterate through token factors.  The TFs grows when new token factors are
1450   // encountered.
1451   for (unsigned i = 0; i < TFs.size(); ++i) {
1452     SDNode *TF = TFs[i];
1454     // Check each of the operands.
1455     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1456       SDValue Op = TF->getOperand(i);
1458       switch (Op.getOpcode()) {
1459       case ISD::EntryToken:
1460         // Entry tokens don't need to be added to the list. They are
1461         // rededundant.
1462         Changed = true;
1463         break;
1465       case ISD::TokenFactor:
1466         if (Op.hasOneUse() &&
1467             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1468           // Queue up for processing.
1469           TFs.push_back(Op.getNode());
1470           // Clean up in case the token factor is removed.
1471           AddToWorklist(Op.getNode());
1472           Changed = true;
1473           break;
1474         }
1475         // Fall thru
1477       default:
1478         // Only add if it isn't already in the list.
1479         if (SeenOps.insert(Op.getNode()))
1480           Ops.push_back(Op);
1481         else
1482           Changed = true;
1483         break;
1484       }
1485     }
1486   }
1488   SDValue Result;
1490   // If we've change things around then replace token factor.
1491   if (Changed) {
1492     if (Ops.empty()) {
1493       // The entry token is the only possible outcome.
1494       Result = DAG.getEntryNode();
1495     } else {
1496       // New and improved token factor.
1497       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1498     }
1500     // Don't add users to work list.
1501     return CombineTo(N, Result, false);
1502   }
1504   return Result;
1507 /// MERGE_VALUES can always be eliminated.
1508 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1509   WorklistRemover DeadNodes(*this);
1510   // Replacing results may cause a different MERGE_VALUES to suddenly
1511   // be CSE'd with N, and carry its uses with it. Iterate until no
1512   // uses remain, to ensure that the node can be safely deleted.
1513   // First add the users of this node to the work list so that they
1514   // can be tried again once they have new operands.
1515   AddUsersToWorklist(N);
1516   do {
1517     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1518       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1519   } while (!N->use_empty());
1520   deleteAndRecombine(N);
1521   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1524 static
1525 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1526                               SelectionDAG &DAG) {
1527   EVT VT = N0.getValueType();
1528   SDValue N00 = N0.getOperand(0);
1529   SDValue N01 = N0.getOperand(1);
1530   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1532   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1533       isa<ConstantSDNode>(N00.getOperand(1))) {
1534     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1535     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1536                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1537                                  N00.getOperand(0), N01),
1538                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1539                                  N00.getOperand(1), N01));
1540     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1541   }
1543   return SDValue();
1546 SDValue DAGCombiner::visitADD(SDNode *N) {
1547   SDValue N0 = N->getOperand(0);
1548   SDValue N1 = N->getOperand(1);
1549   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1550   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1551   EVT VT = N0.getValueType();
1553   // fold vector ops
1554   if (VT.isVector()) {
1555     SDValue FoldedVOp = SimplifyVBinOp(N);
1556     if (FoldedVOp.getNode()) return FoldedVOp;
1558     // fold (add x, 0) -> x, vector edition
1559     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1560       return N0;
1561     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1562       return N1;
1563   }
1565   // fold (add x, undef) -> undef
1566   if (N0.getOpcode() == ISD::UNDEF)
1567     return N0;
1568   if (N1.getOpcode() == ISD::UNDEF)
1569     return N1;
1570   // fold (add c1, c2) -> c1+c2
1571   if (N0C && N1C)
1572     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1573   // canonicalize constant to RHS
1574   if (N0C && !N1C)
1575     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1576   // fold (add x, 0) -> x
1577   if (N1C && N1C->isNullValue())
1578     return N0;
1579   // fold (add Sym, c) -> Sym+c
1580   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1581     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1582         GA->getOpcode() == ISD::GlobalAddress)
1583       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1584                                   GA->getOffset() +
1585                                     (uint64_t)N1C->getSExtValue());
1586   // fold ((c1-A)+c2) -> (c1+c2)-A
1587   if (N1C && N0.getOpcode() == ISD::SUB)
1588     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1589       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1590                          DAG.getConstant(N1C->getAPIntValue()+
1591                                          N0C->getAPIntValue(), VT),
1592                          N0.getOperand(1));
1593   // reassociate add
1594   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1595   if (RADD.getNode())
1596     return RADD;
1597   // fold ((0-A) + B) -> B-A
1598   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1599       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1600     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1601   // fold (A + (0-B)) -> A-B
1602   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1603       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1604     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1605   // fold (A+(B-A)) -> B
1606   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1607     return N1.getOperand(0);
1608   // fold ((B-A)+A) -> B
1609   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1610     return N0.getOperand(0);
1611   // fold (A+(B-(A+C))) to (B-C)
1612   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1613       N0 == N1.getOperand(1).getOperand(0))
1614     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1615                        N1.getOperand(1).getOperand(1));
1616   // fold (A+(B-(C+A))) to (B-C)
1617   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1618       N0 == N1.getOperand(1).getOperand(1))
1619     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1620                        N1.getOperand(1).getOperand(0));
1621   // fold (A+((B-A)+or-C)) to (B+or-C)
1622   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1623       N1.getOperand(0).getOpcode() == ISD::SUB &&
1624       N0 == N1.getOperand(0).getOperand(1))
1625     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1626                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1628   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1629   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1630     SDValue N00 = N0.getOperand(0);
1631     SDValue N01 = N0.getOperand(1);
1632     SDValue N10 = N1.getOperand(0);
1633     SDValue N11 = N1.getOperand(1);
1635     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1636       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1637                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1638                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1639   }
1641   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1642     return SDValue(N, 0);
1644   // fold (a+b) -> (a|b) iff a and b share no bits.
1645   if (VT.isInteger() && !VT.isVector()) {
1646     APInt LHSZero, LHSOne;
1647     APInt RHSZero, RHSOne;
1648     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1650     if (LHSZero.getBoolValue()) {
1651       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1653       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1654       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1655       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1656         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1657           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1658       }
1659     }
1660   }
1662   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1663   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1664     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1665     if (Result.getNode()) return Result;
1666   }
1667   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1668     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1669     if (Result.getNode()) return Result;
1670   }
1672   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1673   if (N1.getOpcode() == ISD::SHL &&
1674       N1.getOperand(0).getOpcode() == ISD::SUB)
1675     if (ConstantSDNode *C =
1676           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1677       if (C->getAPIntValue() == 0)
1678         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1679                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1680                                        N1.getOperand(0).getOperand(1),
1681                                        N1.getOperand(1)));
1682   if (N0.getOpcode() == ISD::SHL &&
1683       N0.getOperand(0).getOpcode() == ISD::SUB)
1684     if (ConstantSDNode *C =
1685           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1686       if (C->getAPIntValue() == 0)
1687         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1688                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1689                                        N0.getOperand(0).getOperand(1),
1690                                        N0.getOperand(1)));
1692   if (N1.getOpcode() == ISD::AND) {
1693     SDValue AndOp0 = N1.getOperand(0);
1694     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1695     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1696     unsigned DestBits = VT.getScalarType().getSizeInBits();
1698     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1699     // and similar xforms where the inner op is either ~0 or 0.
1700     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1701       SDLoc DL(N);
1702       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1703     }
1704   }
1706   // add (sext i1), X -> sub X, (zext i1)
1707   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1708       N0.getOperand(0).getValueType() == MVT::i1 &&
1709       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1710     SDLoc DL(N);
1711     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1712     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1713   }
1715   return SDValue();
1718 SDValue DAGCombiner::visitADDC(SDNode *N) {
1719   SDValue N0 = N->getOperand(0);
1720   SDValue N1 = N->getOperand(1);
1721   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1722   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1723   EVT VT = N0.getValueType();
1725   // If the flag result is dead, turn this into an ADD.
1726   if (!N->hasAnyUseOfValue(1))
1727     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1728                      DAG.getNode(ISD::CARRY_FALSE,
1729                                  SDLoc(N), MVT::Glue));
1731   // canonicalize constant to RHS.
1732   if (N0C && !N1C)
1733     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1735   // fold (addc x, 0) -> x + no carry out
1736   if (N1C && N1C->isNullValue())
1737     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1738                                         SDLoc(N), MVT::Glue));
1740   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1741   APInt LHSZero, LHSOne;
1742   APInt RHSZero, RHSOne;
1743   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1745   if (LHSZero.getBoolValue()) {
1746     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1748     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1749     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1750     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1751       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1752                        DAG.getNode(ISD::CARRY_FALSE,
1753                                    SDLoc(N), MVT::Glue));
1754   }
1756   return SDValue();
1759 SDValue DAGCombiner::visitADDE(SDNode *N) {
1760   SDValue N0 = N->getOperand(0);
1761   SDValue N1 = N->getOperand(1);
1762   SDValue CarryIn = N->getOperand(2);
1763   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1764   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1766   // canonicalize constant to RHS
1767   if (N0C && !N1C)
1768     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1769                        N1, N0, CarryIn);
1771   // fold (adde x, y, false) -> (addc x, y)
1772   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1773     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1775   return SDValue();
1778 // Since it may not be valid to emit a fold to zero for vector initializers
1779 // check if we can before folding.
1780 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1781                              SelectionDAG &DAG,
1782                              bool LegalOperations, bool LegalTypes) {
1783   if (!VT.isVector())
1784     return DAG.getConstant(0, VT);
1785   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1786     return DAG.getConstant(0, VT);
1787   return SDValue();
1790 SDValue DAGCombiner::visitSUB(SDNode *N) {
1791   SDValue N0 = N->getOperand(0);
1792   SDValue N1 = N->getOperand(1);
1793   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1794   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1795   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1796     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1797   EVT VT = N0.getValueType();
1799   // fold vector ops
1800   if (VT.isVector()) {
1801     SDValue FoldedVOp = SimplifyVBinOp(N);
1802     if (FoldedVOp.getNode()) return FoldedVOp;
1804     // fold (sub x, 0) -> x, vector edition
1805     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1806       return N0;
1807   }
1809   // fold (sub x, x) -> 0
1810   // FIXME: Refactor this and xor and other similar operations together.
1811   if (N0 == N1)
1812     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1813   // fold (sub c1, c2) -> c1-c2
1814   if (N0C && N1C)
1815     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1816   // fold (sub x, c) -> (add x, -c)
1817   if (N1C)
1818     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1819                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1820   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1821   if (N0C && N0C->isAllOnesValue())
1822     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1823   // fold A-(A-B) -> B
1824   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1825     return N1.getOperand(1);
1826   // fold (A+B)-A -> B
1827   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1828     return N0.getOperand(1);
1829   // fold (A+B)-B -> A
1830   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1831     return N0.getOperand(0);
1832   // fold C2-(A+C1) -> (C2-C1)-A
1833   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1834     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1835                                    VT);
1836     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1837                        N1.getOperand(0));
1838   }
1839   // fold ((A+(B+or-C))-B) -> A+or-C
1840   if (N0.getOpcode() == ISD::ADD &&
1841       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1842        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1843       N0.getOperand(1).getOperand(0) == N1)
1844     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1845                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1846   // fold ((A+(C+B))-B) -> A+C
1847   if (N0.getOpcode() == ISD::ADD &&
1848       N0.getOperand(1).getOpcode() == ISD::ADD &&
1849       N0.getOperand(1).getOperand(1) == N1)
1850     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1851                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1852   // fold ((A-(B-C))-C) -> A-B
1853   if (N0.getOpcode() == ISD::SUB &&
1854       N0.getOperand(1).getOpcode() == ISD::SUB &&
1855       N0.getOperand(1).getOperand(1) == N1)
1856     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1857                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1859   // If either operand of a sub is undef, the result is undef
1860   if (N0.getOpcode() == ISD::UNDEF)
1861     return N0;
1862   if (N1.getOpcode() == ISD::UNDEF)
1863     return N1;
1865   // If the relocation model supports it, consider symbol offsets.
1866   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1867     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1868       // fold (sub Sym, c) -> Sym-c
1869       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1870         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1871                                     GA->getOffset() -
1872                                       (uint64_t)N1C->getSExtValue());
1873       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1874       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1875         if (GA->getGlobal() == GB->getGlobal())
1876           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1877                                  VT);
1878     }
1880   return SDValue();
1883 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1884   SDValue N0 = N->getOperand(0);
1885   SDValue N1 = N->getOperand(1);
1886   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1887   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1888   EVT VT = N0.getValueType();
1890   // If the flag result is dead, turn this into an SUB.
1891   if (!N->hasAnyUseOfValue(1))
1892     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1893                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1894                                  MVT::Glue));
1896   // fold (subc x, x) -> 0 + no borrow
1897   if (N0 == N1)
1898     return CombineTo(N, DAG.getConstant(0, VT),
1899                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1900                                  MVT::Glue));
1902   // fold (subc x, 0) -> x + no borrow
1903   if (N1C && N1C->isNullValue())
1904     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1905                                         MVT::Glue));
1907   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1908   if (N0C && N0C->isAllOnesValue())
1909     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1910                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1911                                  MVT::Glue));
1913   return SDValue();
1916 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1917   SDValue N0 = N->getOperand(0);
1918   SDValue N1 = N->getOperand(1);
1919   SDValue CarryIn = N->getOperand(2);
1921   // fold (sube x, y, false) -> (subc x, y)
1922   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1923     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1925   return SDValue();
1928 SDValue DAGCombiner::visitMUL(SDNode *N) {
1929   SDValue N0 = N->getOperand(0);
1930   SDValue N1 = N->getOperand(1);
1931   EVT VT = N0.getValueType();
1933   // fold (mul x, undef) -> 0
1934   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1935     return DAG.getConstant(0, VT);
1937   bool N0IsConst = false;
1938   bool N1IsConst = false;
1939   APInt ConstValue0, ConstValue1;
1940   // fold vector ops
1941   if (VT.isVector()) {
1942     SDValue FoldedVOp = SimplifyVBinOp(N);
1943     if (FoldedVOp.getNode()) return FoldedVOp;
1945     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1946     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1947   } else {
1948     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1949     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1950                             : APInt();
1951     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1952     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1953                             : APInt();
1954   }
1956   // fold (mul c1, c2) -> c1*c2
1957   if (N0IsConst && N1IsConst)
1958     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1960   // canonicalize constant to RHS
1961   if (N0IsConst && !N1IsConst)
1962     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1963   // fold (mul x, 0) -> 0
1964   if (N1IsConst && ConstValue1 == 0)
1965     return N1;
1966   // We require a splat of the entire scalar bit width for non-contiguous
1967   // bit patterns.
1968   bool IsFullSplat =
1969     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1970   // fold (mul x, 1) -> x
1971   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1972     return N0;
1973   // fold (mul x, -1) -> 0-x
1974   if (N1IsConst && ConstValue1.isAllOnesValue())
1975     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1976                        DAG.getConstant(0, VT), N0);
1977   // fold (mul x, (1 << c)) -> x << c
1978   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1979     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1980                        DAG.getConstant(ConstValue1.logBase2(),
1981                                        getShiftAmountTy(N0.getValueType())));
1982   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1983   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1984     unsigned Log2Val = (-ConstValue1).logBase2();
1985     // FIXME: If the input is something that is easily negated (e.g. a
1986     // single-use add), we should put the negate there.
1987     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1988                        DAG.getConstant(0, VT),
1989                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1990                             DAG.getConstant(Log2Val,
1991                                       getShiftAmountTy(N0.getValueType()))));
1992   }
1994   APInt Val;
1995   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1996   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1997       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1998                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1999     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2000                              N1, N0.getOperand(1));
2001     AddToWorklist(C3.getNode());
2002     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2003                        N0.getOperand(0), C3);
2004   }
2006   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2007   // use.
2008   {
2009     SDValue Sh(nullptr,0), Y(nullptr,0);
2010     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2011     if (N0.getOpcode() == ISD::SHL &&
2012         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2013                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2014         N0.getNode()->hasOneUse()) {
2015       Sh = N0; Y = N1;
2016     } else if (N1.getOpcode() == ISD::SHL &&
2017                isa<ConstantSDNode>(N1.getOperand(1)) &&
2018                N1.getNode()->hasOneUse()) {
2019       Sh = N1; Y = N0;
2020     }
2022     if (Sh.getNode()) {
2023       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2024                                 Sh.getOperand(0), Y);
2025       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2026                          Mul, Sh.getOperand(1));
2027     }
2028   }
2030   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2031   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2032       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2033                      isa<ConstantSDNode>(N0.getOperand(1))))
2034     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2035                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2036                                    N0.getOperand(0), N1),
2037                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2038                                    N0.getOperand(1), N1));
2040   // reassociate mul
2041   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2042   if (RMUL.getNode())
2043     return RMUL;
2045   return SDValue();
2048 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2049   SDValue N0 = N->getOperand(0);
2050   SDValue N1 = N->getOperand(1);
2051   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2052   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2053   EVT VT = N->getValueType(0);
2055   // fold vector ops
2056   if (VT.isVector()) {
2057     SDValue FoldedVOp = SimplifyVBinOp(N);
2058     if (FoldedVOp.getNode()) return FoldedVOp;
2059   }
2061   // fold (sdiv c1, c2) -> c1/c2
2062   if (N0C && N1C && !N1C->isNullValue())
2063     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2064   // fold (sdiv X, 1) -> X
2065   if (N1C && N1C->getAPIntValue() == 1LL)
2066     return N0;
2067   // fold (sdiv X, -1) -> 0-X
2068   if (N1C && N1C->isAllOnesValue())
2069     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2070                        DAG.getConstant(0, VT), N0);
2071   // If we know the sign bits of both operands are zero, strength reduce to a
2072   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2073   if (!VT.isVector()) {
2074     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2075       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2076                          N0, N1);
2077   }
2079   // fold (sdiv X, pow2) -> simple ops after legalize
2080   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2081                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2082     // If dividing by powers of two is cheap, then don't perform the following
2083     // fold.
2084     if (TLI.isPow2SDivCheap())
2085       return SDValue();
2087     // Target-specific implementation of sdiv x, pow2.
2088     SDValue Res = BuildSDIVPow2(N);
2089     if (Res.getNode())
2090       return Res;
2092     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2094     // Splat the sign bit into the register
2095     SDValue SGN =
2096         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2097                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2098                                     getShiftAmountTy(N0.getValueType())));
2099     AddToWorklist(SGN.getNode());
2101     // Add (N0 < 0) ? abs2 - 1 : 0;
2102     SDValue SRL =
2103         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2104                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2105                                     getShiftAmountTy(SGN.getValueType())));
2106     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2107     AddToWorklist(SRL.getNode());
2108     AddToWorklist(ADD.getNode());    // Divide by pow2
2109     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2110                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2112     // If we're dividing by a positive value, we're done.  Otherwise, we must
2113     // negate the result.
2114     if (N1C->getAPIntValue().isNonNegative())
2115       return SRA;
2117     AddToWorklist(SRA.getNode());
2118     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2119   }
2121   // if integer divide is expensive and we satisfy the requirements, emit an
2122   // alternate sequence.
2123   if (N1C && !TLI.isIntDivCheap()) {
2124     SDValue Op = BuildSDIV(N);
2125     if (Op.getNode()) return Op;
2126   }
2128   // undef / X -> 0
2129   if (N0.getOpcode() == ISD::UNDEF)
2130     return DAG.getConstant(0, VT);
2131   // X / undef -> undef
2132   if (N1.getOpcode() == ISD::UNDEF)
2133     return N1;
2135   return SDValue();
2138 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2139   SDValue N0 = N->getOperand(0);
2140   SDValue N1 = N->getOperand(1);
2141   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2142   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2143   EVT VT = N->getValueType(0);
2145   // fold vector ops
2146   if (VT.isVector()) {
2147     SDValue FoldedVOp = SimplifyVBinOp(N);
2148     if (FoldedVOp.getNode()) return FoldedVOp;
2149   }
2151   // fold (udiv c1, c2) -> c1/c2
2152   if (N0C && N1C && !N1C->isNullValue())
2153     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2154   // fold (udiv x, (1 << c)) -> x >>u c
2155   if (N1C && N1C->getAPIntValue().isPowerOf2())
2156     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2157                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2158                                        getShiftAmountTy(N0.getValueType())));
2159   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2160   if (N1.getOpcode() == ISD::SHL) {
2161     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2162       if (SHC->getAPIntValue().isPowerOf2()) {
2163         EVT ADDVT = N1.getOperand(1).getValueType();
2164         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2165                                   N1.getOperand(1),
2166                                   DAG.getConstant(SHC->getAPIntValue()
2167                                                                   .logBase2(),
2168                                                   ADDVT));
2169         AddToWorklist(Add.getNode());
2170         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2171       }
2172     }
2173   }
2174   // fold (udiv x, c) -> alternate
2175   if (N1C && !TLI.isIntDivCheap()) {
2176     SDValue Op = BuildUDIV(N);
2177     if (Op.getNode()) return Op;
2178   }
2180   // undef / X -> 0
2181   if (N0.getOpcode() == ISD::UNDEF)
2182     return DAG.getConstant(0, VT);
2183   // X / undef -> undef
2184   if (N1.getOpcode() == ISD::UNDEF)
2185     return N1;
2187   return SDValue();
2190 SDValue DAGCombiner::visitSREM(SDNode *N) {
2191   SDValue N0 = N->getOperand(0);
2192   SDValue N1 = N->getOperand(1);
2193   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2194   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2195   EVT VT = N->getValueType(0);
2197   // fold (srem c1, c2) -> c1%c2
2198   if (N0C && N1C && !N1C->isNullValue())
2199     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2200   // If we know the sign bits of both operands are zero, strength reduce to a
2201   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2202   if (!VT.isVector()) {
2203     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2204       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2205   }
2207   // If X/C can be simplified by the division-by-constant logic, lower
2208   // X%C to the equivalent of X-X/C*C.
2209   if (N1C && !N1C->isNullValue()) {
2210     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2211     AddToWorklist(Div.getNode());
2212     SDValue OptimizedDiv = combine(Div.getNode());
2213     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2214       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2215                                 OptimizedDiv, N1);
2216       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2217       AddToWorklist(Mul.getNode());
2218       return Sub;
2219     }
2220   }
2222   // undef % X -> 0
2223   if (N0.getOpcode() == ISD::UNDEF)
2224     return DAG.getConstant(0, VT);
2225   // X % undef -> undef
2226   if (N1.getOpcode() == ISD::UNDEF)
2227     return N1;
2229   return SDValue();
2232 SDValue DAGCombiner::visitUREM(SDNode *N) {
2233   SDValue N0 = N->getOperand(0);
2234   SDValue N1 = N->getOperand(1);
2235   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2236   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2237   EVT VT = N->getValueType(0);
2239   // fold (urem c1, c2) -> c1%c2
2240   if (N0C && N1C && !N1C->isNullValue())
2241     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2242   // fold (urem x, pow2) -> (and x, pow2-1)
2243   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2244     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2245                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2246   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2247   if (N1.getOpcode() == ISD::SHL) {
2248     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2249       if (SHC->getAPIntValue().isPowerOf2()) {
2250         SDValue Add =
2251           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2252                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2253                                  VT));
2254         AddToWorklist(Add.getNode());
2255         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2256       }
2257     }
2258   }
2260   // If X/C can be simplified by the division-by-constant logic, lower
2261   // X%C to the equivalent of X-X/C*C.
2262   if (N1C && !N1C->isNullValue()) {
2263     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2264     AddToWorklist(Div.getNode());
2265     SDValue OptimizedDiv = combine(Div.getNode());
2266     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2267       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2268                                 OptimizedDiv, N1);
2269       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2270       AddToWorklist(Mul.getNode());
2271       return Sub;
2272     }
2273   }
2275   // undef % X -> 0
2276   if (N0.getOpcode() == ISD::UNDEF)
2277     return DAG.getConstant(0, VT);
2278   // X % undef -> undef
2279   if (N1.getOpcode() == ISD::UNDEF)
2280     return N1;
2282   return SDValue();
2285 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2286   SDValue N0 = N->getOperand(0);
2287   SDValue N1 = N->getOperand(1);
2288   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2289   EVT VT = N->getValueType(0);
2290   SDLoc DL(N);
2292   // fold (mulhs x, 0) -> 0
2293   if (N1C && N1C->isNullValue())
2294     return N1;
2295   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2296   if (N1C && N1C->getAPIntValue() == 1)
2297     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2298                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2299                                        getShiftAmountTy(N0.getValueType())));
2300   // fold (mulhs x, undef) -> 0
2301   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2302     return DAG.getConstant(0, VT);
2304   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2305   // plus a shift.
2306   if (VT.isSimple() && !VT.isVector()) {
2307     MVT Simple = VT.getSimpleVT();
2308     unsigned SimpleSize = Simple.getSizeInBits();
2309     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2310     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2311       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2312       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2313       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2314       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2315             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2316       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2317     }
2318   }
2320   return SDValue();
2323 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2324   SDValue N0 = N->getOperand(0);
2325   SDValue N1 = N->getOperand(1);
2326   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2327   EVT VT = N->getValueType(0);
2328   SDLoc DL(N);
2330   // fold (mulhu x, 0) -> 0
2331   if (N1C && N1C->isNullValue())
2332     return N1;
2333   // fold (mulhu x, 1) -> 0
2334   if (N1C && N1C->getAPIntValue() == 1)
2335     return DAG.getConstant(0, N0.getValueType());
2336   // fold (mulhu x, undef) -> 0
2337   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2338     return DAG.getConstant(0, VT);
2340   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2341   // plus a shift.
2342   if (VT.isSimple() && !VT.isVector()) {
2343     MVT Simple = VT.getSimpleVT();
2344     unsigned SimpleSize = Simple.getSizeInBits();
2345     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2346     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2347       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2348       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2349       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2350       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2351             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2352       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2353     }
2354   }
2356   return SDValue();
2359 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2360 /// give the opcodes for the two computations that are being performed. Return
2361 /// true if a simplification was made.
2362 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2363                                                 unsigned HiOp) {
2364   // If the high half is not needed, just compute the low half.
2365   bool HiExists = N->hasAnyUseOfValue(1);
2366   if (!HiExists &&
2367       (!LegalOperations ||
2368        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2369     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2370     return CombineTo(N, Res, Res);
2371   }
2373   // If the low half is not needed, just compute the high half.
2374   bool LoExists = N->hasAnyUseOfValue(0);
2375   if (!LoExists &&
2376       (!LegalOperations ||
2377        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2378     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2379     return CombineTo(N, Res, Res);
2380   }
2382   // If both halves are used, return as it is.
2383   if (LoExists && HiExists)
2384     return SDValue();
2386   // If the two computed results can be simplified separately, separate them.
2387   if (LoExists) {
2388     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2389     AddToWorklist(Lo.getNode());
2390     SDValue LoOpt = combine(Lo.getNode());
2391     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2392         (!LegalOperations ||
2393          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2394       return CombineTo(N, LoOpt, LoOpt);
2395   }
2397   if (HiExists) {
2398     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2399     AddToWorklist(Hi.getNode());
2400     SDValue HiOpt = combine(Hi.getNode());
2401     if (HiOpt.getNode() && HiOpt != Hi &&
2402         (!LegalOperations ||
2403          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2404       return CombineTo(N, HiOpt, HiOpt);
2405   }
2407   return SDValue();
2410 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2411   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2412   if (Res.getNode()) return Res;
2414   EVT VT = N->getValueType(0);
2415   SDLoc DL(N);
2417   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2418   // plus a shift.
2419   if (VT.isSimple() && !VT.isVector()) {
2420     MVT Simple = VT.getSimpleVT();
2421     unsigned SimpleSize = Simple.getSizeInBits();
2422     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2423     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2424       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2425       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2426       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2427       // Compute the high part as N1.
2428       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2429             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2430       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2431       // Compute the low part as N0.
2432       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2433       return CombineTo(N, Lo, Hi);
2434     }
2435   }
2437   return SDValue();
2440 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2441   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2442   if (Res.getNode()) return Res;
2444   EVT VT = N->getValueType(0);
2445   SDLoc DL(N);
2447   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2448   // plus a shift.
2449   if (VT.isSimple() && !VT.isVector()) {
2450     MVT Simple = VT.getSimpleVT();
2451     unsigned SimpleSize = Simple.getSizeInBits();
2452     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2453     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2454       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2455       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2456       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2457       // Compute the high part as N1.
2458       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2459             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2460       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2461       // Compute the low part as N0.
2462       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2463       return CombineTo(N, Lo, Hi);
2464     }
2465   }
2467   return SDValue();
2470 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2471   // (smulo x, 2) -> (saddo x, x)
2472   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2473     if (C2->getAPIntValue() == 2)
2474       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2475                          N->getOperand(0), N->getOperand(0));
2477   return SDValue();
2480 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2481   // (umulo x, 2) -> (uaddo x, x)
2482   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2483     if (C2->getAPIntValue() == 2)
2484       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2485                          N->getOperand(0), N->getOperand(0));
2487   return SDValue();
2490 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2491   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2492   if (Res.getNode()) return Res;
2494   return SDValue();
2497 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2498   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2499   if (Res.getNode()) return Res;
2501   return SDValue();
2504 /// If this is a binary operator with two operands of the same opcode, try to
2505 /// simplify it.
2506 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2507   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2508   EVT VT = N0.getValueType();
2509   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2511   // Bail early if none of these transforms apply.
2512   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2514   // For each of OP in AND/OR/XOR:
2515   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2516   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2517   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2518   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2519   //
2520   // do not sink logical op inside of a vector extend, since it may combine
2521   // into a vsetcc.
2522   EVT Op0VT = N0.getOperand(0).getValueType();
2523   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2524        N0.getOpcode() == ISD::SIGN_EXTEND ||
2525        // Avoid infinite looping with PromoteIntBinOp.
2526        (N0.getOpcode() == ISD::ANY_EXTEND &&
2527         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2528        (N0.getOpcode() == ISD::TRUNCATE &&
2529         (!TLI.isZExtFree(VT, Op0VT) ||
2530          !TLI.isTruncateFree(Op0VT, VT)) &&
2531         TLI.isTypeLegal(Op0VT))) &&
2532       !VT.isVector() &&
2533       Op0VT == N1.getOperand(0).getValueType() &&
2534       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2535     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2536                                  N0.getOperand(0).getValueType(),
2537                                  N0.getOperand(0), N1.getOperand(0));
2538     AddToWorklist(ORNode.getNode());
2539     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2540   }
2542   // For each of OP in SHL/SRL/SRA/AND...
2543   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2544   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2545   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2546   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2547        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2548       N0.getOperand(1) == N1.getOperand(1)) {
2549     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2550                                  N0.getOperand(0).getValueType(),
2551                                  N0.getOperand(0), N1.getOperand(0));
2552     AddToWorklist(ORNode.getNode());
2553     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2554                        ORNode, N0.getOperand(1));
2555   }
2557   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2558   // Only perform this optimization after type legalization and before
2559   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2560   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2561   // we don't want to undo this promotion.
2562   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2563   // on scalars.
2564   if ((N0.getOpcode() == ISD::BITCAST ||
2565        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2566       Level == AfterLegalizeTypes) {
2567     SDValue In0 = N0.getOperand(0);
2568     SDValue In1 = N1.getOperand(0);
2569     EVT In0Ty = In0.getValueType();
2570     EVT In1Ty = In1.getValueType();
2571     SDLoc DL(N);
2572     // If both incoming values are integers, and the original types are the
2573     // same.
2574     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2575       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2576       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2577       AddToWorklist(Op.getNode());
2578       return BC;
2579     }
2580   }
2582   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2583   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2584   // If both shuffles use the same mask, and both shuffle within a single
2585   // vector, then it is worthwhile to move the swizzle after the operation.
2586   // The type-legalizer generates this pattern when loading illegal
2587   // vector types from memory. In many cases this allows additional shuffle
2588   // optimizations.
2589   // There are other cases where moving the shuffle after the xor/and/or
2590   // is profitable even if shuffles don't perform a swizzle.
2591   // If both shuffles use the same mask, and both shuffles have the same first
2592   // or second operand, then it might still be profitable to move the shuffle
2593   // after the xor/and/or operation.
2594   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2595     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2596     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2598     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2599            "Inputs to shuffles are not the same type");
2601     // Check that both shuffles use the same mask. The masks are known to be of
2602     // the same length because the result vector type is the same.
2603     // Check also that shuffles have only one use to avoid introducing extra
2604     // instructions.
2605     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2606         SVN0->getMask().equals(SVN1->getMask())) {
2607       SDValue ShOp = N0->getOperand(1);
2609       // Don't try to fold this node if it requires introducing a
2610       // build vector of all zeros that might be illegal at this stage.
2611       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2612         if (!LegalTypes)
2613           ShOp = DAG.getConstant(0, VT);
2614         else
2615           ShOp = SDValue();
2616       }
2618       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2619       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2620       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2621       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2622         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2623                                       N0->getOperand(0), N1->getOperand(0));
2624         AddToWorklist(NewNode.getNode());
2625         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2626                                     &SVN0->getMask()[0]);
2627       }
2629       // Don't try to fold this node if it requires introducing a
2630       // build vector of all zeros that might be illegal at this stage.
2631       ShOp = N0->getOperand(0);
2632       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2633         if (!LegalTypes)
2634           ShOp = DAG.getConstant(0, VT);
2635         else
2636           ShOp = SDValue();
2637       }
2639       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2640       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2641       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2642       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2643         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2644                                       N0->getOperand(1), N1->getOperand(1));
2645         AddToWorklist(NewNode.getNode());
2646         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2647                                     &SVN0->getMask()[0]);
2648       }
2649     }
2650   }
2652   return SDValue();
2655 SDValue DAGCombiner::visitAND(SDNode *N) {
2656   SDValue N0 = N->getOperand(0);
2657   SDValue N1 = N->getOperand(1);
2658   SDValue LL, LR, RL, RR, CC0, CC1;
2659   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2660   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2661   EVT VT = N1.getValueType();
2662   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2664   // fold vector ops
2665   if (VT.isVector()) {
2666     SDValue FoldedVOp = SimplifyVBinOp(N);
2667     if (FoldedVOp.getNode()) return FoldedVOp;
2669     // fold (and x, 0) -> 0, vector edition
2670     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2671       return N0;
2672     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2673       return N1;
2675     // fold (and x, -1) -> x, vector edition
2676     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2677       return N1;
2678     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2679       return N0;
2680   }
2682   // fold (and x, undef) -> 0
2683   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2684     return DAG.getConstant(0, VT);
2685   // fold (and c1, c2) -> c1&c2
2686   if (N0C && N1C)
2687     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2688   // canonicalize constant to RHS
2689   if (N0C && !N1C)
2690     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2691   // fold (and x, -1) -> x
2692   if (N1C && N1C->isAllOnesValue())
2693     return N0;
2694   // if (and x, c) is known to be zero, return 0
2695   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2696                                    APInt::getAllOnesValue(BitWidth)))
2697     return DAG.getConstant(0, VT);
2698   // reassociate and
2699   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2700   if (RAND.getNode())
2701     return RAND;
2702   // fold (and (or x, C), D) -> D if (C & D) == D
2703   if (N1C && N0.getOpcode() == ISD::OR)
2704     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2705       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2706         return N1;
2707   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2708   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2709     SDValue N0Op0 = N0.getOperand(0);
2710     APInt Mask = ~N1C->getAPIntValue();
2711     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2712     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2713       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2714                                  N0.getValueType(), N0Op0);
2716       // Replace uses of the AND with uses of the Zero extend node.
2717       CombineTo(N, Zext);
2719       // We actually want to replace all uses of the any_extend with the
2720       // zero_extend, to avoid duplicating things.  This will later cause this
2721       // AND to be folded.
2722       CombineTo(N0.getNode(), Zext);
2723       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2724     }
2725   }
2726   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2727   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2728   // already be zero by virtue of the width of the base type of the load.
2729   //
2730   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2731   // more cases.
2732   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2733        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2734       N0.getOpcode() == ISD::LOAD) {
2735     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2736                                          N0 : N0.getOperand(0) );
2738     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2739     // This can be a pure constant or a vector splat, in which case we treat the
2740     // vector as a scalar and use the splat value.
2741     APInt Constant = APInt::getNullValue(1);
2742     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2743       Constant = C->getAPIntValue();
2744     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2745       APInt SplatValue, SplatUndef;
2746       unsigned SplatBitSize;
2747       bool HasAnyUndefs;
2748       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2749                                              SplatBitSize, HasAnyUndefs);
2750       if (IsSplat) {
2751         // Undef bits can contribute to a possible optimisation if set, so
2752         // set them.
2753         SplatValue |= SplatUndef;
2755         // The splat value may be something like "0x00FFFFFF", which means 0 for
2756         // the first vector value and FF for the rest, repeating. We need a mask
2757         // that will apply equally to all members of the vector, so AND all the
2758         // lanes of the constant together.
2759         EVT VT = Vector->getValueType(0);
2760         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2762         // If the splat value has been compressed to a bitlength lower
2763         // than the size of the vector lane, we need to re-expand it to
2764         // the lane size.
2765         if (BitWidth > SplatBitSize)
2766           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2767                SplatBitSize < BitWidth;
2768                SplatBitSize = SplatBitSize * 2)
2769             SplatValue |= SplatValue.shl(SplatBitSize);
2771         Constant = APInt::getAllOnesValue(BitWidth);
2772         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2773           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2774       }
2775     }
2777     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2778     // actually legal and isn't going to get expanded, else this is a false
2779     // optimisation.
2780     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2781                                                     Load->getMemoryVT());
2783     // Resize the constant to the same size as the original memory access before
2784     // extension. If it is still the AllOnesValue then this AND is completely
2785     // unneeded.
2786     Constant =
2787       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2789     bool B;
2790     switch (Load->getExtensionType()) {
2791     default: B = false; break;
2792     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2793     case ISD::ZEXTLOAD:
2794     case ISD::NON_EXTLOAD: B = true; break;
2795     }
2797     if (B && Constant.isAllOnesValue()) {
2798       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2799       // preserve semantics once we get rid of the AND.
2800       SDValue NewLoad(Load, 0);
2801       if (Load->getExtensionType() == ISD::EXTLOAD) {
2802         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2803                               Load->getValueType(0), SDLoc(Load),
2804                               Load->getChain(), Load->getBasePtr(),
2805                               Load->getOffset(), Load->getMemoryVT(),
2806                               Load->getMemOperand());
2807         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2808         if (Load->getNumValues() == 3) {
2809           // PRE/POST_INC loads have 3 values.
2810           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2811                            NewLoad.getValue(2) };
2812           CombineTo(Load, To, 3, true);
2813         } else {
2814           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2815         }
2816       }
2818       // Fold the AND away, taking care not to fold to the old load node if we
2819       // replaced it.
2820       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2822       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2823     }
2824   }
2825   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2826   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2827     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2828     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2830     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2831         LL.getValueType().isInteger()) {
2832       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2833       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2834         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2835                                      LR.getValueType(), LL, RL);
2836         AddToWorklist(ORNode.getNode());
2837         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2838       }
2839       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2840       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2841         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2842                                       LR.getValueType(), LL, RL);
2843         AddToWorklist(ANDNode.getNode());
2844         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2845       }
2846       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2847       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2848         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2849                                      LR.getValueType(), LL, RL);
2850         AddToWorklist(ORNode.getNode());
2851         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2852       }
2853     }
2854     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2855     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2856         Op0 == Op1 && LL.getValueType().isInteger() &&
2857       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2858                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2859                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2860                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2861       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2862                                     LL, DAG.getConstant(1, LL.getValueType()));
2863       AddToWorklist(ADDNode.getNode());
2864       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2865                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2866     }
2867     // canonicalize equivalent to ll == rl
2868     if (LL == RR && LR == RL) {
2869       Op1 = ISD::getSetCCSwappedOperands(Op1);
2870       std::swap(RL, RR);
2871     }
2872     if (LL == RL && LR == RR) {
2873       bool isInteger = LL.getValueType().isInteger();
2874       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2875       if (Result != ISD::SETCC_INVALID &&
2876           (!LegalOperations ||
2877            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2878             TLI.isOperationLegal(ISD::SETCC,
2879                             getSetCCResultType(N0.getSimpleValueType())))))
2880         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2881                             LL, LR, Result);
2882     }
2883   }
2885   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2886   if (N0.getOpcode() == N1.getOpcode()) {
2887     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2888     if (Tmp.getNode()) return Tmp;
2889   }
2891   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2892   // fold (and (sra)) -> (and (srl)) when possible.
2893   if (!VT.isVector() &&
2894       SimplifyDemandedBits(SDValue(N, 0)))
2895     return SDValue(N, 0);
2897   // fold (zext_inreg (extload x)) -> (zextload x)
2898   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2899     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2900     EVT MemVT = LN0->getMemoryVT();
2901     // If we zero all the possible extended bits, then we can turn this into
2902     // a zextload if we are running before legalize or the operation is legal.
2903     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2904     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2905                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2906         ((!LegalOperations && !LN0->isVolatile()) ||
2907          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2908       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2909                                        LN0->getChain(), LN0->getBasePtr(),
2910                                        MemVT, LN0->getMemOperand());
2911       AddToWorklist(N);
2912       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2913       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2914     }
2915   }
2916   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2917   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2918       N0.hasOneUse()) {
2919     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2920     EVT MemVT = LN0->getMemoryVT();
2921     // If we zero all the possible extended bits, then we can turn this into
2922     // a zextload if we are running before legalize or the operation is legal.
2923     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2924     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2925                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2926         ((!LegalOperations && !LN0->isVolatile()) ||
2927          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2928       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2929                                        LN0->getChain(), LN0->getBasePtr(),
2930                                        MemVT, LN0->getMemOperand());
2931       AddToWorklist(N);
2932       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2933       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2934     }
2935   }
2937   // fold (and (load x), 255) -> (zextload x, i8)
2938   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2939   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2940   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2941               (N0.getOpcode() == ISD::ANY_EXTEND &&
2942                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2943     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2944     LoadSDNode *LN0 = HasAnyExt
2945       ? cast<LoadSDNode>(N0.getOperand(0))
2946       : cast<LoadSDNode>(N0);
2947     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2948         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2949       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2950       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2951         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2952         EVT LoadedVT = LN0->getMemoryVT();
2954         if (ExtVT == LoadedVT &&
2955             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2956           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2958           SDValue NewLoad =
2959             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2960                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2961                            LN0->getMemOperand());
2962           AddToWorklist(N);
2963           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2964           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2965         }
2967         // Do not change the width of a volatile load.
2968         // Do not generate loads of non-round integer types since these can
2969         // be expensive (and would be wrong if the type is not byte sized).
2970         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2971             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2972           EVT PtrType = LN0->getOperand(1).getValueType();
2974           unsigned Alignment = LN0->getAlignment();
2975           SDValue NewPtr = LN0->getBasePtr();
2977           // For big endian targets, we need to add an offset to the pointer
2978           // to load the correct bytes.  For little endian systems, we merely
2979           // need to read fewer bytes from the same pointer.
2980           if (TLI.isBigEndian()) {
2981             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2982             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2983             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2984             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2985                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2986             Alignment = MinAlign(Alignment, PtrOff);
2987           }
2989           AddToWorklist(NewPtr.getNode());
2991           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2992           SDValue Load =
2993             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2994                            LN0->getChain(), NewPtr,
2995                            LN0->getPointerInfo(),
2996                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2997                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
2998           AddToWorklist(N);
2999           CombineTo(LN0, Load, Load.getValue(1));
3000           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3001         }
3002       }
3003     }
3004   }
3006   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3007       VT.getSizeInBits() <= 64) {
3008     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3009       APInt ADDC = ADDI->getAPIntValue();
3010       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3011         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3012         // immediate for an add, but it is legal if its top c2 bits are set,
3013         // transform the ADD so the immediate doesn't need to be materialized
3014         // in a register.
3015         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3016           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3017                                              SRLI->getZExtValue());
3018           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3019             ADDC |= Mask;
3020             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3021               SDValue NewAdd =
3022                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3023                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
3024               CombineTo(N0.getNode(), NewAdd);
3025               return SDValue(N, 0); // Return N so it doesn't get rechecked!
3026             }
3027           }
3028         }
3029       }
3030     }
3031   }
3033   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3034   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3035     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3036                                        N0.getOperand(1), false);
3037     if (BSwap.getNode())
3038       return BSwap;
3039   }
3041   return SDValue();
3044 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3045 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3046                                         bool DemandHighBits) {
3047   if (!LegalOperations)
3048     return SDValue();
3050   EVT VT = N->getValueType(0);
3051   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3052     return SDValue();
3053   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3054     return SDValue();
3056   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3057   bool LookPassAnd0 = false;
3058   bool LookPassAnd1 = false;
3059   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3060       std::swap(N0, N1);
3061   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3062       std::swap(N0, N1);
3063   if (N0.getOpcode() == ISD::AND) {
3064     if (!N0.getNode()->hasOneUse())
3065       return SDValue();
3066     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3067     if (!N01C || N01C->getZExtValue() != 0xFF00)
3068       return SDValue();
3069     N0 = N0.getOperand(0);
3070     LookPassAnd0 = true;
3071   }
3073   if (N1.getOpcode() == ISD::AND) {
3074     if (!N1.getNode()->hasOneUse())
3075       return SDValue();
3076     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3077     if (!N11C || N11C->getZExtValue() != 0xFF)
3078       return SDValue();
3079     N1 = N1.getOperand(0);
3080     LookPassAnd1 = true;
3081   }
3083   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3084     std::swap(N0, N1);
3085   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3086     return SDValue();
3087   if (!N0.getNode()->hasOneUse() ||
3088       !N1.getNode()->hasOneUse())
3089     return SDValue();
3091   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3092   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3093   if (!N01C || !N11C)
3094     return SDValue();
3095   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3096     return SDValue();
3098   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3099   SDValue N00 = N0->getOperand(0);
3100   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3101     if (!N00.getNode()->hasOneUse())
3102       return SDValue();
3103     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3104     if (!N001C || N001C->getZExtValue() != 0xFF)
3105       return SDValue();
3106     N00 = N00.getOperand(0);
3107     LookPassAnd0 = true;
3108   }
3110   SDValue N10 = N1->getOperand(0);
3111   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3112     if (!N10.getNode()->hasOneUse())
3113       return SDValue();
3114     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3115     if (!N101C || N101C->getZExtValue() != 0xFF00)
3116       return SDValue();
3117     N10 = N10.getOperand(0);
3118     LookPassAnd1 = true;
3119   }
3121   if (N00 != N10)
3122     return SDValue();
3124   // Make sure everything beyond the low halfword gets set to zero since the SRL
3125   // 16 will clear the top bits.
3126   unsigned OpSizeInBits = VT.getSizeInBits();
3127   if (DemandHighBits && OpSizeInBits > 16) {
3128     // If the left-shift isn't masked out then the only way this is a bswap is
3129     // if all bits beyond the low 8 are 0. In that case the entire pattern
3130     // reduces to a left shift anyway: leave it for other parts of the combiner.
3131     if (!LookPassAnd0)
3132       return SDValue();
3134     // However, if the right shift isn't masked out then it might be because
3135     // it's not needed. See if we can spot that too.
3136     if (!LookPassAnd1 &&
3137         !DAG.MaskedValueIsZero(
3138             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3139       return SDValue();
3140   }
3142   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3143   if (OpSizeInBits > 16)
3144     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3145                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3146   return Res;
3149 /// Return true if the specified node is an element that makes up a 32-bit
3150 /// packed halfword byteswap.
3151 /// ((x & 0x000000ff) << 8) |
3152 /// ((x & 0x0000ff00) >> 8) |
3153 /// ((x & 0x00ff0000) << 8) |
3154 /// ((x & 0xff000000) >> 8)
3155 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3156   if (!N.getNode()->hasOneUse())
3157     return false;
3159   unsigned Opc = N.getOpcode();
3160   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3161     return false;
3163   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3164   if (!N1C)
3165     return false;
3167   unsigned Num;
3168   switch (N1C->getZExtValue()) {
3169   default:
3170     return false;
3171   case 0xFF:       Num = 0; break;
3172   case 0xFF00:     Num = 1; break;
3173   case 0xFF0000:   Num = 2; break;
3174   case 0xFF000000: Num = 3; break;
3175   }
3177   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3178   SDValue N0 = N.getOperand(0);
3179   if (Opc == ISD::AND) {
3180     if (Num == 0 || Num == 2) {
3181       // (x >> 8) & 0xff
3182       // (x >> 8) & 0xff0000
3183       if (N0.getOpcode() != ISD::SRL)
3184         return false;
3185       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3186       if (!C || C->getZExtValue() != 8)
3187         return false;
3188     } else {
3189       // (x << 8) & 0xff00
3190       // (x << 8) & 0xff000000
3191       if (N0.getOpcode() != ISD::SHL)
3192         return false;
3193       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3194       if (!C || C->getZExtValue() != 8)
3195         return false;
3196     }
3197   } else if (Opc == ISD::SHL) {
3198     // (x & 0xff) << 8
3199     // (x & 0xff0000) << 8
3200     if (Num != 0 && Num != 2)
3201       return false;
3202     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3203     if (!C || C->getZExtValue() != 8)
3204       return false;
3205   } else { // Opc == ISD::SRL
3206     // (x & 0xff00) >> 8
3207     // (x & 0xff000000) >> 8
3208     if (Num != 1 && Num != 3)
3209       return false;
3210     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3211     if (!C || C->getZExtValue() != 8)
3212       return false;
3213   }
3215   if (Parts[Num])
3216     return false;
3218   Parts[Num] = N0.getOperand(0).getNode();
3219   return true;
3222 /// Match a 32-bit packed halfword bswap. That is
3223 /// ((x & 0x000000ff) << 8) |
3224 /// ((x & 0x0000ff00) >> 8) |
3225 /// ((x & 0x00ff0000) << 8) |
3226 /// ((x & 0xff000000) >> 8)
3227 /// => (rotl (bswap x), 16)
3228 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3229   if (!LegalOperations)
3230     return SDValue();
3232   EVT VT = N->getValueType(0);
3233   if (VT != MVT::i32)
3234     return SDValue();
3235   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3236     return SDValue();
3238   SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3239   // Look for either
3240   // (or (or (and), (and)), (or (and), (and)))
3241   // (or (or (or (and), (and)), (and)), (and))
3242   if (N0.getOpcode() != ISD::OR)
3243     return SDValue();
3244   SDValue N00 = N0.getOperand(0);
3245   SDValue N01 = N0.getOperand(1);
3247   if (N1.getOpcode() == ISD::OR &&
3248       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3249     // (or (or (and), (and)), (or (and), (and)))
3250     SDValue N000 = N00.getOperand(0);
3251     if (!isBSwapHWordElement(N000, Parts))
3252       return SDValue();
3254     SDValue N001 = N00.getOperand(1);
3255     if (!isBSwapHWordElement(N001, Parts))
3256       return SDValue();
3257     SDValue N010 = N01.getOperand(0);
3258     if (!isBSwapHWordElement(N010, Parts))
3259       return SDValue();
3260     SDValue N011 = N01.getOperand(1);
3261     if (!isBSwapHWordElement(N011, Parts))
3262       return SDValue();
3263   } else {
3264     // (or (or (or (and), (and)), (and)), (and))
3265     if (!isBSwapHWordElement(N1, Parts))
3266       return SDValue();
3267     if (!isBSwapHWordElement(N01, Parts))
3268       return SDValue();
3269     if (N00.getOpcode() != ISD::OR)
3270       return SDValue();
3271     SDValue N000 = N00.getOperand(0);
3272     if (!isBSwapHWordElement(N000, Parts))
3273       return SDValue();
3274     SDValue N001 = N00.getOperand(1);
3275     if (!isBSwapHWordElement(N001, Parts))
3276       return SDValue();
3277   }
3279   // Make sure the parts are all coming from the same node.
3280   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3281     return SDValue();
3283   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3284                               SDValue(Parts[0],0));
3286   // Result of the bswap should be rotated by 16. If it's not legal, then
3287   // do  (x << 16) | (x >> 16).
3288   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3289   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3290     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3291   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3292     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3293   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3294                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3295                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3298 SDValue DAGCombiner::visitOR(SDNode *N) {
3299   SDValue N0 = N->getOperand(0);
3300   SDValue N1 = N->getOperand(1);
3301   SDValue LL, LR, RL, RR, CC0, CC1;
3302   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3303   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3304   EVT VT = N1.getValueType();
3306   // fold vector ops
3307   if (VT.isVector()) {
3308     SDValue FoldedVOp = SimplifyVBinOp(N);
3309     if (FoldedVOp.getNode()) return FoldedVOp;
3311     // fold (or x, 0) -> x, vector edition
3312     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3313       return N1;
3314     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3315       return N0;
3317     // fold (or x, -1) -> -1, vector edition
3318     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3319       return N0;
3320     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3321       return N1;
3323     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3324     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3325     // Do this only if the resulting shuffle is legal.
3326     if (isa<ShuffleVectorSDNode>(N0) &&
3327         isa<ShuffleVectorSDNode>(N1) &&
3328         // Avoid folding a node with illegal type.
3329         TLI.isTypeLegal(VT) &&
3330         N0->getOperand(1) == N1->getOperand(1) &&
3331         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3332       bool CanFold = true;
3333       unsigned NumElts = VT.getVectorNumElements();
3334       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3335       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3336       // We construct two shuffle masks:
3337       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3338       // and N1 as the second operand.
3339       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3340       // and N0 as the second operand.
3341       // We do this because OR is commutable and therefore there might be
3342       // two ways to fold this node into a shuffle.
3343       SmallVector<int,4> Mask1;
3344       SmallVector<int,4> Mask2;
3346       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3347         int M0 = SV0->getMaskElt(i);
3348         int M1 = SV1->getMaskElt(i);
3350         // Both shuffle indexes are undef. Propagate Undef.
3351         if (M0 < 0 && M1 < 0) {
3352           Mask1.push_back(M0);
3353           Mask2.push_back(M0);
3354           continue;
3355         }
3357         if (M0 < 0 || M1 < 0 ||
3358             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3359             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3360           CanFold = false;
3361           break;
3362         }
3364         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3365         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3366       }
3368       if (CanFold) {
3369         // Fold this sequence only if the resulting shuffle is 'legal'.
3370         if (TLI.isShuffleMaskLegal(Mask1, VT))
3371           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3372                                       N1->getOperand(0), &Mask1[0]);
3373         if (TLI.isShuffleMaskLegal(Mask2, VT))
3374           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3375                                       N0->getOperand(0), &Mask2[0]);
3376       }
3377     }
3378   }
3380   // fold (or x, undef) -> -1
3381   if (!LegalOperations &&
3382       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3383     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3384     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3385   }
3386   // fold (or c1, c2) -> c1|c2
3387   if (N0C && N1C)
3388     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3389   // canonicalize constant to RHS
3390   if (N0C && !N1C)
3391     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3392   // fold (or x, 0) -> x
3393   if (N1C && N1C->isNullValue())
3394     return N0;
3395   // fold (or x, -1) -> -1
3396   if (N1C && N1C->isAllOnesValue())
3397     return N1;
3398   // fold (or x, c) -> c iff (x & ~c) == 0
3399   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3400     return N1;
3402   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3403   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3404   if (BSwap.getNode())
3405     return BSwap;
3406   BSwap = MatchBSwapHWordLow(N, N0, N1);
3407   if (BSwap.getNode())
3408     return BSwap;
3410   // reassociate or
3411   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3412   if (ROR.getNode())
3413     return ROR;
3414   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3415   // iff (c1 & c2) == 0.
3416   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3417              isa<ConstantSDNode>(N0.getOperand(1))) {
3418     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3419     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3420       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3421       if (!COR.getNode())
3422         return SDValue();
3423       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3424                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3425                                      N0.getOperand(0), N1), COR);
3426     }
3427   }
3428   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3429   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3430     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3431     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3433     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3434         LL.getValueType().isInteger()) {
3435       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3436       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3437       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3438           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3439         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3440                                      LR.getValueType(), LL, RL);
3441         AddToWorklist(ORNode.getNode());
3442         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3443       }
3444       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3445       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3446       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3447           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3448         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3449                                       LR.getValueType(), LL, RL);
3450         AddToWorklist(ANDNode.getNode());
3451         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3452       }
3453     }
3454     // canonicalize equivalent to ll == rl
3455     if (LL == RR && LR == RL) {
3456       Op1 = ISD::getSetCCSwappedOperands(Op1);
3457       std::swap(RL, RR);
3458     }
3459     if (LL == RL && LR == RR) {
3460       bool isInteger = LL.getValueType().isInteger();
3461       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3462       if (Result != ISD::SETCC_INVALID &&
3463           (!LegalOperations ||
3464            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3465             TLI.isOperationLegal(ISD::SETCC,
3466               getSetCCResultType(N0.getValueType())))))
3467         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3468                             LL, LR, Result);
3469     }
3470   }
3472   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3473   if (N0.getOpcode() == N1.getOpcode()) {
3474     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3475     if (Tmp.getNode()) return Tmp;
3476   }
3478   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3479   if (N0.getOpcode() == ISD::AND &&
3480       N1.getOpcode() == ISD::AND &&
3481       N0.getOperand(1).getOpcode() == ISD::Constant &&
3482       N1.getOperand(1).getOpcode() == ISD::Constant &&
3483       // Don't increase # computations.
3484       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3485     // We can only do this xform if we know that bits from X that are set in C2
3486     // but not in C1 are already zero.  Likewise for Y.
3487     const APInt &LHSMask =
3488       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3489     const APInt &RHSMask =
3490       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3492     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3493         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3494       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3495                               N0.getOperand(0), N1.getOperand(0));
3496       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3497                          DAG.getConstant(LHSMask | RHSMask, VT));
3498     }
3499   }
3501   // See if this is some rotate idiom.
3502   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3503     return SDValue(Rot, 0);
3505   // Simplify the operands using demanded-bits information.
3506   if (!VT.isVector() &&
3507       SimplifyDemandedBits(SDValue(N, 0)))
3508     return SDValue(N, 0);
3510   return SDValue();
3513 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3514 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3515   if (Op.getOpcode() == ISD::AND) {
3516     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3517       Mask = Op.getOperand(1);
3518       Op = Op.getOperand(0);
3519     } else {
3520       return false;
3521     }
3522   }
3524   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3525     Shift = Op;
3526     return true;
3527   }
3529   return false;
3532 // Return true if we can prove that, whenever Neg and Pos are both in the
3533 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3534 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3535 //
3536 //     (or (shift1 X, Neg), (shift2 X, Pos))
3537 //
3538 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3539 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3540 // to consider shift amounts with defined behavior.
3541 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3542   // If OpSize is a power of 2 then:
3543   //
3544   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3545   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3546   //
3547   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3548   // for the stronger condition:
3549   //
3550   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3551   //
3552   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3553   // we can just replace Neg with Neg' for the rest of the function.
3554   //
3555   // In other cases we check for the even stronger condition:
3556   //
3557   //     Neg == OpSize - Pos                                    [B]
3558   //
3559   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3560   // behavior if Pos == 0 (and consequently Neg == OpSize).
3561   //
3562   // We could actually use [A] whenever OpSize is a power of 2, but the
3563   // only extra cases that it would match are those uninteresting ones
3564   // where Neg and Pos are never in range at the same time.  E.g. for
3565   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3566   // as well as (sub 32, Pos), but:
3567   //
3568   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3569   //
3570   // always invokes undefined behavior for 32-bit X.
3571   //
3572   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3573   unsigned MaskLoBits = 0;
3574   if (Neg.getOpcode() == ISD::AND &&
3575       isPowerOf2_64(OpSize) &&
3576       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3577       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3578     Neg = Neg.getOperand(0);
3579     MaskLoBits = Log2_64(OpSize);
3580   }
3582   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3583   if (Neg.getOpcode() != ISD::SUB)
3584     return 0;
3585   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3586   if (!NegC)
3587     return 0;
3588   SDValue NegOp1 = Neg.getOperand(1);
3590   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3591   // Pos'.  The truncation is redundant for the purpose of the equality.
3592   if (MaskLoBits &&
3593       Pos.getOpcode() == ISD::AND &&
3594       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3595       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3596     Pos = Pos.getOperand(0);
3598   // The condition we need is now:
3599   //
3600   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3601   //
3602   // If NegOp1 == Pos then we need:
3603   //
3604   //              OpSize & Mask == NegC & Mask
3605   //
3606   // (because "x & Mask" is a truncation and distributes through subtraction).
3607   APInt Width;
3608   if (Pos == NegOp1)
3609     Width = NegC->getAPIntValue();
3610   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3611   // Then the condition we want to prove becomes:
3612   //
3613   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3614   //
3615   // which, again because "x & Mask" is a truncation, becomes:
3616   //
3617   //                NegC & Mask == (OpSize - PosC) & Mask
3618   //              OpSize & Mask == (NegC + PosC) & Mask
3619   else if (Pos.getOpcode() == ISD::ADD &&
3620            Pos.getOperand(0) == NegOp1 &&
3621            Pos.getOperand(1).getOpcode() == ISD::Constant)
3622     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3623              NegC->getAPIntValue());
3624   else
3625     return false;
3627   // Now we just need to check that OpSize & Mask == Width & Mask.
3628   if (MaskLoBits)
3629     // Opsize & Mask is 0 since Mask is Opsize - 1.
3630     return Width.getLoBits(MaskLoBits) == 0;
3631   return Width == OpSize;
3634 // A subroutine of MatchRotate used once we have found an OR of two opposite
3635 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3636 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3637 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3638 // Neg with outer conversions stripped away.
3639 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3640                                        SDValue Neg, SDValue InnerPos,
3641                                        SDValue InnerNeg, unsigned PosOpcode,
3642                                        unsigned NegOpcode, SDLoc DL) {
3643   // fold (or (shl x, (*ext y)),
3644   //          (srl x, (*ext (sub 32, y)))) ->
3645   //   (rotl x, y) or (rotr x, (sub 32, y))
3646   //
3647   // fold (or (shl x, (*ext (sub 32, y))),
3648   //          (srl x, (*ext y))) ->
3649   //   (rotr x, y) or (rotl x, (sub 32, y))
3650   EVT VT = Shifted.getValueType();
3651   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3652     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3653     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3654                        HasPos ? Pos : Neg).getNode();
3655   }
3657   return nullptr;
3660 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3661 // idioms for rotate, and if the target supports rotation instructions, generate
3662 // a rot[lr].
3663 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3664   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3665   EVT VT = LHS.getValueType();
3666   if (!TLI.isTypeLegal(VT)) return nullptr;
3668   // The target must have at least one rotate flavor.
3669   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3670   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3671   if (!HasROTL && !HasROTR) return nullptr;
3673   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3674   SDValue LHSShift;   // The shift.
3675   SDValue LHSMask;    // AND value if any.
3676   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3677     return nullptr; // Not part of a rotate.
3679   SDValue RHSShift;   // The shift.
3680   SDValue RHSMask;    // AND value if any.
3681   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3682     return nullptr; // Not part of a rotate.
3684   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3685     return nullptr;   // Not shifting the same value.
3687   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3688     return nullptr;   // Shifts must disagree.
3690   // Canonicalize shl to left side in a shl/srl pair.
3691   if (RHSShift.getOpcode() == ISD::SHL) {
3692     std::swap(LHS, RHS);
3693     std::swap(LHSShift, RHSShift);
3694     std::swap(LHSMask , RHSMask );
3695   }
3697   unsigned OpSizeInBits = VT.getSizeInBits();
3698   SDValue LHSShiftArg = LHSShift.getOperand(0);
3699   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3700   SDValue RHSShiftArg = RHSShift.getOperand(0);
3701   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3703   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3704   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3705   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3706       RHSShiftAmt.getOpcode() == ISD::Constant) {
3707     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3708     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3709     if ((LShVal + RShVal) != OpSizeInBits)
3710       return nullptr;
3712     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3713                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3715     // If there is an AND of either shifted operand, apply it to the result.
3716     if (LHSMask.getNode() || RHSMask.getNode()) {
3717       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3719       if (LHSMask.getNode()) {
3720         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3721         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3722       }
3723       if (RHSMask.getNode()) {
3724         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3725         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3726       }
3728       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3729     }
3731     return Rot.getNode();
3732   }
3734   // If there is a mask here, and we have a variable shift, we can't be sure
3735   // that we're masking out the right stuff.
3736   if (LHSMask.getNode() || RHSMask.getNode())
3737     return nullptr;
3739   // If the shift amount is sign/zext/any-extended just peel it off.
3740   SDValue LExtOp0 = LHSShiftAmt;
3741   SDValue RExtOp0 = RHSShiftAmt;
3742   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3743        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3744        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3745        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3746       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3747        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3748        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3749        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3750     LExtOp0 = LHSShiftAmt.getOperand(0);
3751     RExtOp0 = RHSShiftAmt.getOperand(0);
3752   }
3754   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3755                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3756   if (TryL)
3757     return TryL;
3759   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3760                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3761   if (TryR)
3762     return TryR;
3764   return nullptr;
3767 SDValue DAGCombiner::visitXOR(SDNode *N) {
3768   SDValue N0 = N->getOperand(0);
3769   SDValue N1 = N->getOperand(1);
3770   SDValue LHS, RHS, CC;
3771   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3772   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3773   EVT VT = N0.getValueType();
3775   // fold vector ops
3776   if (VT.isVector()) {
3777     SDValue FoldedVOp = SimplifyVBinOp(N);
3778     if (FoldedVOp.getNode()) return FoldedVOp;
3780     // fold (xor x, 0) -> x, vector edition
3781     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3782       return N1;
3783     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3784       return N0;
3785   }
3787   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3788   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3789     return DAG.getConstant(0, VT);
3790   // fold (xor x, undef) -> undef
3791   if (N0.getOpcode() == ISD::UNDEF)
3792     return N0;
3793   if (N1.getOpcode() == ISD::UNDEF)
3794     return N1;
3795   // fold (xor c1, c2) -> c1^c2
3796   if (N0C && N1C)
3797     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3798   // canonicalize constant to RHS
3799   if (N0C && !N1C)
3800     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3801   // fold (xor x, 0) -> x
3802   if (N1C && N1C->isNullValue())
3803     return N0;
3804   // reassociate xor
3805   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3806   if (RXOR.getNode())
3807     return RXOR;
3809   // fold !(x cc y) -> (x !cc y)
3810   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3811     bool isInt = LHS.getValueType().isInteger();
3812     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3813                                                isInt);
3815     if (!LegalOperations ||
3816         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3817       switch (N0.getOpcode()) {
3818       default:
3819         llvm_unreachable("Unhandled SetCC Equivalent!");
3820       case ISD::SETCC:
3821         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3822       case ISD::SELECT_CC:
3823         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3824                                N0.getOperand(3), NotCC);
3825       }
3826     }
3827   }
3829   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3830   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3831       N0.getNode()->hasOneUse() &&
3832       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3833     SDValue V = N0.getOperand(0);
3834     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3835                     DAG.getConstant(1, V.getValueType()));
3836     AddToWorklist(V.getNode());
3837     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3838   }
3840   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3841   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3842       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3843     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3844     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3845       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3846       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3847       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3848       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3849       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3850     }
3851   }
3852   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3853   if (N1C && N1C->isAllOnesValue() &&
3854       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3855     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3856     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3857       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3858       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3859       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3860       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3861       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3862     }
3863   }
3864   // fold (xor (and x, y), y) -> (and (not x), y)
3865   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3866       N0->getOperand(1) == N1) {
3867     SDValue X = N0->getOperand(0);
3868     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3869     AddToWorklist(NotX.getNode());
3870     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3871   }
3872   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3873   if (N1C && N0.getOpcode() == ISD::XOR) {
3874     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3875     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3876     if (N00C)
3877       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3878                          DAG.getConstant(N1C->getAPIntValue() ^
3879                                          N00C->getAPIntValue(), VT));
3880     if (N01C)
3881       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3882                          DAG.getConstant(N1C->getAPIntValue() ^
3883                                          N01C->getAPIntValue(), VT));
3884   }
3885   // fold (xor x, x) -> 0
3886   if (N0 == N1)
3887     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3889   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3890   if (N0.getOpcode() == N1.getOpcode()) {
3891     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3892     if (Tmp.getNode()) return Tmp;
3893   }
3895   // Simplify the expression using non-local knowledge.
3896   if (!VT.isVector() &&
3897       SimplifyDemandedBits(SDValue(N, 0)))
3898     return SDValue(N, 0);
3900   return SDValue();
3903 /// Handle transforms common to the three shifts, when the shift amount is a
3904 /// constant.
3905 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3906   // We can't and shouldn't fold opaque constants.
3907   if (Amt->isOpaque())
3908     return SDValue();
3910   SDNode *LHS = N->getOperand(0).getNode();
3911   if (!LHS->hasOneUse()) return SDValue();
3913   // We want to pull some binops through shifts, so that we have (and (shift))
3914   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3915   // thing happens with address calculations, so it's important to canonicalize
3916   // it.
3917   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3919   switch (LHS->getOpcode()) {
3920   default: return SDValue();
3921   case ISD::OR:
3922   case ISD::XOR:
3923     HighBitSet = false; // We can only transform sra if the high bit is clear.
3924     break;
3925   case ISD::AND:
3926     HighBitSet = true;  // We can only transform sra if the high bit is set.
3927     break;
3928   case ISD::ADD:
3929     if (N->getOpcode() != ISD::SHL)
3930       return SDValue(); // only shl(add) not sr[al](add).
3931     HighBitSet = false; // We can only transform sra if the high bit is clear.
3932     break;
3933   }
3935   // We require the RHS of the binop to be a constant and not opaque as well.
3936   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3937   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3939   // FIXME: disable this unless the input to the binop is a shift by a constant.
3940   // If it is not a shift, it pessimizes some common cases like:
3941   //
3942   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3943   //    int bar(int *X, int i) { return X[i & 255]; }
3944   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3945   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3946        BinOpLHSVal->getOpcode() != ISD::SRA &&
3947        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3948       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3949     return SDValue();
3951   EVT VT = N->getValueType(0);
3953   // If this is a signed shift right, and the high bit is modified by the
3954   // logical operation, do not perform the transformation. The highBitSet
3955   // boolean indicates the value of the high bit of the constant which would
3956   // cause it to be modified for this operation.
3957   if (N->getOpcode() == ISD::SRA) {
3958     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3959     if (BinOpRHSSignSet != HighBitSet)
3960       return SDValue();
3961   }
3963   if (!TLI.isDesirableToCommuteWithShift(LHS))
3964     return SDValue();
3966   // Fold the constants, shifting the binop RHS by the shift amount.
3967   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3968                                N->getValueType(0),
3969                                LHS->getOperand(1), N->getOperand(1));
3970   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3972   // Create the new shift.
3973   SDValue NewShift = DAG.getNode(N->getOpcode(),
3974                                  SDLoc(LHS->getOperand(0)),
3975                                  VT, LHS->getOperand(0), N->getOperand(1));
3977   // Create the new binop.
3978   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3981 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3982   assert(N->getOpcode() == ISD::TRUNCATE);
3983   assert(N->getOperand(0).getOpcode() == ISD::AND);
3985   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3986   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3987     SDValue N01 = N->getOperand(0).getOperand(1);
3989     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3990       EVT TruncVT = N->getValueType(0);
3991       SDValue N00 = N->getOperand(0).getOperand(0);
3992       APInt TruncC = N01C->getAPIntValue();
3993       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3995       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3996                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3997                          DAG.getConstant(TruncC, TruncVT));
3998     }
3999   }
4001   return SDValue();
4004 SDValue DAGCombiner::visitRotate(SDNode *N) {
4005   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4006   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4007       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4008     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4009     if (NewOp1.getNode())
4010       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4011                          N->getOperand(0), NewOp1);
4012   }
4013   return SDValue();
4016 SDValue DAGCombiner::visitSHL(SDNode *N) {
4017   SDValue N0 = N->getOperand(0);
4018   SDValue N1 = N->getOperand(1);
4019   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4020   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4021   EVT VT = N0.getValueType();
4022   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4024   // fold vector ops
4025   if (VT.isVector()) {
4026     SDValue FoldedVOp = SimplifyVBinOp(N);
4027     if (FoldedVOp.getNode()) return FoldedVOp;
4029     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4030     // If setcc produces all-one true value then:
4031     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4032     if (N1CV && N1CV->isConstant()) {
4033       if (N0.getOpcode() == ISD::AND) {
4034         SDValue N00 = N0->getOperand(0);
4035         SDValue N01 = N0->getOperand(1);
4036         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4038         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4039             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4040                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4041           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4042           if (C.getNode())
4043             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4044         }
4045       } else {
4046         N1C = isConstOrConstSplat(N1);
4047       }
4048     }
4049   }
4051   // fold (shl c1, c2) -> c1<<c2
4052   if (N0C && N1C)
4053     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4054   // fold (shl 0, x) -> 0
4055   if (N0C && N0C->isNullValue())
4056     return N0;
4057   // fold (shl x, c >= size(x)) -> undef
4058   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4059     return DAG.getUNDEF(VT);
4060   // fold (shl x, 0) -> x
4061   if (N1C && N1C->isNullValue())
4062     return N0;
4063   // fold (shl undef, x) -> 0
4064   if (N0.getOpcode() == ISD::UNDEF)
4065     return DAG.getConstant(0, VT);
4066   // if (shl x, c) is known to be zero, return 0
4067   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4068                             APInt::getAllOnesValue(OpSizeInBits)))
4069     return DAG.getConstant(0, VT);
4070   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4071   if (N1.getOpcode() == ISD::TRUNCATE &&
4072       N1.getOperand(0).getOpcode() == ISD::AND) {
4073     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4074     if (NewOp1.getNode())
4075       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4076   }
4078   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4079     return SDValue(N, 0);
4081   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4082   if (N1C && N0.getOpcode() == ISD::SHL) {
4083     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4084       uint64_t c1 = N0C1->getZExtValue();
4085       uint64_t c2 = N1C->getZExtValue();
4086       if (c1 + c2 >= OpSizeInBits)
4087         return DAG.getConstant(0, VT);
4088       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4089                          DAG.getConstant(c1 + c2, N1.getValueType()));
4090     }
4091   }
4093   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4094   // For this to be valid, the second form must not preserve any of the bits
4095   // that are shifted out by the inner shift in the first form.  This means
4096   // the outer shift size must be >= the number of bits added by the ext.
4097   // As a corollary, we don't care what kind of ext it is.
4098   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4099               N0.getOpcode() == ISD::ANY_EXTEND ||
4100               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4101       N0.getOperand(0).getOpcode() == ISD::SHL) {
4102     SDValue N0Op0 = N0.getOperand(0);
4103     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4104       uint64_t c1 = N0Op0C1->getZExtValue();
4105       uint64_t c2 = N1C->getZExtValue();
4106       EVT InnerShiftVT = N0Op0.getValueType();
4107       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4108       if (c2 >= OpSizeInBits - InnerShiftSize) {
4109         if (c1 + c2 >= OpSizeInBits)
4110           return DAG.getConstant(0, VT);
4111         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4112                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4113                                        N0Op0->getOperand(0)),
4114                            DAG.getConstant(c1 + c2, N1.getValueType()));
4115       }
4116     }
4117   }
4119   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4120   // Only fold this if the inner zext has no other uses to avoid increasing
4121   // the total number of instructions.
4122   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4123       N0.getOperand(0).getOpcode() == ISD::SRL) {
4124     SDValue N0Op0 = N0.getOperand(0);
4125     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4126       uint64_t c1 = N0Op0C1->getZExtValue();
4127       if (c1 < VT.getScalarSizeInBits()) {
4128         uint64_t c2 = N1C->getZExtValue();
4129         if (c1 == c2) {
4130           SDValue NewOp0 = N0.getOperand(0);
4131           EVT CountVT = NewOp0.getOperand(1).getValueType();
4132           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4133                                        NewOp0, DAG.getConstant(c2, CountVT));
4134           AddToWorklist(NewSHL.getNode());
4135           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4136         }
4137       }
4138     }
4139   }
4141   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4142   //                               (and (srl x, (sub c1, c2), MASK)
4143   // Only fold this if the inner shift has no other uses -- if it does, folding
4144   // this will increase the total number of instructions.
4145   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4146     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4147       uint64_t c1 = N0C1->getZExtValue();
4148       if (c1 < OpSizeInBits) {
4149         uint64_t c2 = N1C->getZExtValue();
4150         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4151         SDValue Shift;
4152         if (c2 > c1) {
4153           Mask = Mask.shl(c2 - c1);
4154           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4155                               DAG.getConstant(c2 - c1, N1.getValueType()));
4156         } else {
4157           Mask = Mask.lshr(c1 - c2);
4158           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4159                               DAG.getConstant(c1 - c2, N1.getValueType()));
4160         }
4161         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4162                            DAG.getConstant(Mask, VT));
4163       }
4164     }
4165   }
4166   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4167   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4168     unsigned BitSize = VT.getScalarSizeInBits();
4169     SDValue HiBitsMask =
4170       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4171                                             BitSize - N1C->getZExtValue()), VT);
4172     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4173                        HiBitsMask);
4174   }
4176   if (N1C) {
4177     SDValue NewSHL = visitShiftByConstant(N, N1C);
4178     if (NewSHL.getNode())
4179       return NewSHL;
4180   }
4182   return SDValue();
4185 SDValue DAGCombiner::visitSRA(SDNode *N) {
4186   SDValue N0 = N->getOperand(0);
4187   SDValue N1 = N->getOperand(1);
4188   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4189   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4190   EVT VT = N0.getValueType();
4191   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4193   // fold vector ops
4194   if (VT.isVector()) {
4195     SDValue FoldedVOp = SimplifyVBinOp(N);
4196     if (FoldedVOp.getNode()) return FoldedVOp;
4198     N1C = isConstOrConstSplat(N1);
4199   }
4201   // fold (sra c1, c2) -> (sra c1, c2)
4202   if (N0C && N1C)
4203     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4204   // fold (sra 0, x) -> 0
4205   if (N0C && N0C->isNullValue())
4206     return N0;
4207   // fold (sra -1, x) -> -1
4208   if (N0C && N0C->isAllOnesValue())
4209     return N0;
4210   // fold (sra x, (setge c, size(x))) -> undef
4211   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4212     return DAG.getUNDEF(VT);
4213   // fold (sra x, 0) -> x
4214   if (N1C && N1C->isNullValue())
4215     return N0;
4216   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4217   // sext_inreg.
4218   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4219     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4220     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4221     if (VT.isVector())
4222       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4223                                ExtVT, VT.getVectorNumElements());
4224     if ((!LegalOperations ||
4225          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4226       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4227                          N0.getOperand(0), DAG.getValueType(ExtVT));
4228   }
4230   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4231   if (N1C && N0.getOpcode() == ISD::SRA) {
4232     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4233       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4234       if (Sum >= OpSizeInBits)
4235         Sum = OpSizeInBits - 1;
4236       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4237                          DAG.getConstant(Sum, N1.getValueType()));
4238     }
4239   }
4241   // fold (sra (shl X, m), (sub result_size, n))
4242   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4243   // result_size - n != m.
4244   // If truncate is free for the target sext(shl) is likely to result in better
4245   // code.
4246   if (N0.getOpcode() == ISD::SHL && N1C) {
4247     // Get the two constanst of the shifts, CN0 = m, CN = n.
4248     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4249     if (N01C) {
4250       LLVMContext &Ctx = *DAG.getContext();
4251       // Determine what the truncate's result bitsize and type would be.
4252       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4254       if (VT.isVector())
4255         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4257       // Determine the residual right-shift amount.
4258       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4260       // If the shift is not a no-op (in which case this should be just a sign
4261       // extend already), the truncated to type is legal, sign_extend is legal
4262       // on that type, and the truncate to that type is both legal and free,
4263       // perform the transform.
4264       if ((ShiftAmt > 0) &&
4265           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4266           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4267           TLI.isTruncateFree(VT, TruncVT)) {
4269           SDValue Amt = DAG.getConstant(ShiftAmt,
4270               getShiftAmountTy(N0.getOperand(0).getValueType()));
4271           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4272                                       N0.getOperand(0), Amt);
4273           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4274                                       Shift);
4275           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4276                              N->getValueType(0), Trunc);
4277       }
4278     }
4279   }
4281   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4282   if (N1.getOpcode() == ISD::TRUNCATE &&
4283       N1.getOperand(0).getOpcode() == ISD::AND) {
4284     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4285     if (NewOp1.getNode())
4286       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4287   }
4289   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4290   //      if c1 is equal to the number of bits the trunc removes
4291   if (N0.getOpcode() == ISD::TRUNCATE &&
4292       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4293        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4294       N0.getOperand(0).hasOneUse() &&
4295       N0.getOperand(0).getOperand(1).hasOneUse() &&
4296       N1C) {
4297     SDValue N0Op0 = N0.getOperand(0);
4298     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4299       unsigned LargeShiftVal = LargeShift->getZExtValue();
4300       EVT LargeVT = N0Op0.getValueType();
4302       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4303         SDValue Amt =
4304           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4305                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4306         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4307                                   N0Op0.getOperand(0), Amt);
4308         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4309       }
4310     }
4311   }
4313   // Simplify, based on bits shifted out of the LHS.
4314   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4315     return SDValue(N, 0);
4318   // If the sign bit is known to be zero, switch this to a SRL.
4319   if (DAG.SignBitIsZero(N0))
4320     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4322   if (N1C) {
4323     SDValue NewSRA = visitShiftByConstant(N, N1C);
4324     if (NewSRA.getNode())
4325       return NewSRA;
4326   }
4328   return SDValue();
4331 SDValue DAGCombiner::visitSRL(SDNode *N) {
4332   SDValue N0 = N->getOperand(0);
4333   SDValue N1 = N->getOperand(1);
4334   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4335   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4336   EVT VT = N0.getValueType();
4337   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4339   // fold vector ops
4340   if (VT.isVector()) {
4341     SDValue FoldedVOp = SimplifyVBinOp(N);
4342     if (FoldedVOp.getNode()) return FoldedVOp;
4344     N1C = isConstOrConstSplat(N1);
4345   }
4347   // fold (srl c1, c2) -> c1 >>u c2
4348   if (N0C && N1C)
4349     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4350   // fold (srl 0, x) -> 0
4351   if (N0C && N0C->isNullValue())
4352     return N0;
4353   // fold (srl x, c >= size(x)) -> undef
4354   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4355     return DAG.getUNDEF(VT);
4356   // fold (srl x, 0) -> x
4357   if (N1C && N1C->isNullValue())
4358     return N0;
4359   // if (srl x, c) is known to be zero, return 0
4360   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4361                                    APInt::getAllOnesValue(OpSizeInBits)))
4362     return DAG.getConstant(0, VT);
4364   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4365   if (N1C && N0.getOpcode() == ISD::SRL) {
4366     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4367       uint64_t c1 = N01C->getZExtValue();
4368       uint64_t c2 = N1C->getZExtValue();
4369       if (c1 + c2 >= OpSizeInBits)
4370         return DAG.getConstant(0, VT);
4371       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4372                          DAG.getConstant(c1 + c2, N1.getValueType()));
4373     }
4374   }
4376   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4377   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4378       N0.getOperand(0).getOpcode() == ISD::SRL &&
4379       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4380     uint64_t c1 =
4381       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4382     uint64_t c2 = N1C->getZExtValue();
4383     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4384     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4385     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4386     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4387     if (c1 + OpSizeInBits == InnerShiftSize) {
4388       if (c1 + c2 >= InnerShiftSize)
4389         return DAG.getConstant(0, VT);
4390       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4391                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4392                                      N0.getOperand(0)->getOperand(0),
4393                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4394     }
4395   }
4397   // fold (srl (shl x, c), c) -> (and x, cst2)
4398   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4399     unsigned BitSize = N0.getScalarValueSizeInBits();
4400     if (BitSize <= 64) {
4401       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4402       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4403                          DAG.getConstant(~0ULL >> ShAmt, VT));
4404     }
4405   }
4407   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4408   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4409     // Shifting in all undef bits?
4410     EVT SmallVT = N0.getOperand(0).getValueType();
4411     unsigned BitSize = SmallVT.getScalarSizeInBits();
4412     if (N1C->getZExtValue() >= BitSize)
4413       return DAG.getUNDEF(VT);
4415     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4416       uint64_t ShiftAmt = N1C->getZExtValue();
4417       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4418                                        N0.getOperand(0),
4419                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4420       AddToWorklist(SmallShift.getNode());
4421       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4422       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4423                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4424                          DAG.getConstant(Mask, VT));
4425     }
4426   }
4428   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4429   // bit, which is unmodified by sra.
4430   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4431     if (N0.getOpcode() == ISD::SRA)
4432       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4433   }
4435   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4436   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4437       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4438     APInt KnownZero, KnownOne;
4439     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4441     // If any of the input bits are KnownOne, then the input couldn't be all
4442     // zeros, thus the result of the srl will always be zero.
4443     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4445     // If all of the bits input the to ctlz node are known to be zero, then
4446     // the result of the ctlz is "32" and the result of the shift is one.
4447     APInt UnknownBits = ~KnownZero;
4448     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4450     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4451     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4452       // Okay, we know that only that the single bit specified by UnknownBits
4453       // could be set on input to the CTLZ node. If this bit is set, the SRL
4454       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4455       // to an SRL/XOR pair, which is likely to simplify more.
4456       unsigned ShAmt = UnknownBits.countTrailingZeros();
4457       SDValue Op = N0.getOperand(0);
4459       if (ShAmt) {
4460         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4461                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4462         AddToWorklist(Op.getNode());
4463       }
4465       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4466                          Op, DAG.getConstant(1, VT));
4467     }
4468   }
4470   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4471   if (N1.getOpcode() == ISD::TRUNCATE &&
4472       N1.getOperand(0).getOpcode() == ISD::AND) {
4473     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4474     if (NewOp1.getNode())
4475       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4476   }
4478   // fold operands of srl based on knowledge that the low bits are not
4479   // demanded.
4480   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4481     return SDValue(N, 0);
4483   if (N1C) {
4484     SDValue NewSRL = visitShiftByConstant(N, N1C);
4485     if (NewSRL.getNode())
4486       return NewSRL;
4487   }
4489   // Attempt to convert a srl of a load into a narrower zero-extending load.
4490   SDValue NarrowLoad = ReduceLoadWidth(N);
4491   if (NarrowLoad.getNode())
4492     return NarrowLoad;
4494   // Here is a common situation. We want to optimize:
4495   //
4496   //   %a = ...
4497   //   %b = and i32 %a, 2
4498   //   %c = srl i32 %b, 1
4499   //   brcond i32 %c ...
4500   //
4501   // into
4502   //
4503   //   %a = ...
4504   //   %b = and %a, 2
4505   //   %c = setcc eq %b, 0
4506   //   brcond %c ...
4507   //
4508   // However when after the source operand of SRL is optimized into AND, the SRL
4509   // itself may not be optimized further. Look for it and add the BRCOND into
4510   // the worklist.
4511   if (N->hasOneUse()) {
4512     SDNode *Use = *N->use_begin();
4513     if (Use->getOpcode() == ISD::BRCOND)
4514       AddToWorklist(Use);
4515     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4516       // Also look pass the truncate.
4517       Use = *Use->use_begin();
4518       if (Use->getOpcode() == ISD::BRCOND)
4519         AddToWorklist(Use);
4520     }
4521   }
4523   return SDValue();
4526 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4527   SDValue N0 = N->getOperand(0);
4528   EVT VT = N->getValueType(0);
4530   // fold (ctlz c1) -> c2
4531   if (isa<ConstantSDNode>(N0))
4532     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4533   return SDValue();
4536 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4537   SDValue N0 = N->getOperand(0);
4538   EVT VT = N->getValueType(0);
4540   // fold (ctlz_zero_undef c1) -> c2
4541   if (isa<ConstantSDNode>(N0))
4542     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4543   return SDValue();
4546 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4547   SDValue N0 = N->getOperand(0);
4548   EVT VT = N->getValueType(0);
4550   // fold (cttz c1) -> c2
4551   if (isa<ConstantSDNode>(N0))
4552     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4553   return SDValue();
4556 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4557   SDValue N0 = N->getOperand(0);
4558   EVT VT = N->getValueType(0);
4560   // fold (cttz_zero_undef c1) -> c2
4561   if (isa<ConstantSDNode>(N0))
4562     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4563   return SDValue();
4566 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4567   SDValue N0 = N->getOperand(0);
4568   EVT VT = N->getValueType(0);
4570   // fold (ctpop c1) -> c2
4571   if (isa<ConstantSDNode>(N0))
4572     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4573   return SDValue();
4576 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4577   SDValue N0 = N->getOperand(0);
4578   SDValue N1 = N->getOperand(1);
4579   SDValue N2 = N->getOperand(2);
4580   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4581   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4582   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4583   EVT VT = N->getValueType(0);
4584   EVT VT0 = N0.getValueType();
4586   // fold (select C, X, X) -> X
4587   if (N1 == N2)
4588     return N1;
4589   // fold (select true, X, Y) -> X
4590   if (N0C && !N0C->isNullValue())
4591     return N1;
4592   // fold (select false, X, Y) -> Y
4593   if (N0C && N0C->isNullValue())
4594     return N2;
4595   // fold (select C, 1, X) -> (or C, X)
4596   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4597     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4598   // fold (select C, 0, 1) -> (xor C, 1)
4599   // We can't do this reliably if integer based booleans have different contents
4600   // to floating point based booleans. This is because we can't tell whether we
4601   // have an integer-based boolean or a floating-point-based boolean unless we
4602   // can find the SETCC that produced it and inspect its operands. This is
4603   // fairly easy if C is the SETCC node, but it can potentially be
4604   // undiscoverable (or not reasonably discoverable). For example, it could be
4605   // in another basic block or it could require searching a complicated
4606   // expression.
4607   if (VT.isInteger() &&
4608       (VT0 == MVT::i1 || (VT0.isInteger() &&
4609                           TLI.getBooleanContents(false, false) ==
4610                               TLI.getBooleanContents(false, true) &&
4611                           TLI.getBooleanContents(false, false) ==
4612                               TargetLowering::ZeroOrOneBooleanContent)) &&
4613       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4614     SDValue XORNode;
4615     if (VT == VT0)
4616       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4617                          N0, DAG.getConstant(1, VT0));
4618     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4619                           N0, DAG.getConstant(1, VT0));
4620     AddToWorklist(XORNode.getNode());
4621     if (VT.bitsGT(VT0))
4622       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4623     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4624   }
4625   // fold (select C, 0, X) -> (and (not C), X)
4626   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4627     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4628     AddToWorklist(NOTNode.getNode());
4629     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4630   }
4631   // fold (select C, X, 1) -> (or (not C), X)
4632   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4633     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4634     AddToWorklist(NOTNode.getNode());
4635     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4636   }
4637   // fold (select C, X, 0) -> (and C, X)
4638   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4639     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4640   // fold (select X, X, Y) -> (or X, Y)
4641   // fold (select X, 1, Y) -> (or X, Y)
4642   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4643     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4644   // fold (select X, Y, X) -> (and X, Y)
4645   // fold (select X, Y, 0) -> (and X, Y)
4646   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4647     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4649   // If we can fold this based on the true/false value, do so.
4650   if (SimplifySelectOps(N, N1, N2))
4651     return SDValue(N, 0);  // Don't revisit N.
4653   // fold selects based on a setcc into other things, such as min/max/abs
4654   if (N0.getOpcode() == ISD::SETCC) {
4655     if ((!LegalOperations &&
4656          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4657         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4658       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4659                          N0.getOperand(0), N0.getOperand(1),
4660                          N1, N2, N0.getOperand(2));
4661     return SimplifySelect(SDLoc(N), N0, N1, N2);
4662   }
4664   return SDValue();
4667 static
4668 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4669   SDLoc DL(N);
4670   EVT LoVT, HiVT;
4671   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4673   // Split the inputs.
4674   SDValue Lo, Hi, LL, LH, RL, RH;
4675   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4676   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4678   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4679   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4681   return std::make_pair(Lo, Hi);
4684 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4685 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4686 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4687   SDLoc dl(N);
4688   SDValue Cond = N->getOperand(0);
4689   SDValue LHS = N->getOperand(1);
4690   SDValue RHS = N->getOperand(2);
4691   EVT VT = N->getValueType(0);
4692   int NumElems = VT.getVectorNumElements();
4693   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4694          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4695          Cond.getOpcode() == ISD::BUILD_VECTOR);
4697   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4698   // binary ones here.
4699   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4700     return SDValue();
4702   // We're sure we have an even number of elements due to the
4703   // concat_vectors we have as arguments to vselect.
4704   // Skip BV elements until we find one that's not an UNDEF
4705   // After we find an UNDEF element, keep looping until we get to half the
4706   // length of the BV and see if all the non-undef nodes are the same.
4707   ConstantSDNode *BottomHalf = nullptr;
4708   for (int i = 0; i < NumElems / 2; ++i) {
4709     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4710       continue;
4712     if (BottomHalf == nullptr)
4713       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4714     else if (Cond->getOperand(i).getNode() != BottomHalf)
4715       return SDValue();
4716   }
4718   // Do the same for the second half of the BuildVector
4719   ConstantSDNode *TopHalf = nullptr;
4720   for (int i = NumElems / 2; i < NumElems; ++i) {
4721     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4722       continue;
4724     if (TopHalf == nullptr)
4725       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4726     else if (Cond->getOperand(i).getNode() != TopHalf)
4727       return SDValue();
4728   }
4730   assert(TopHalf && BottomHalf &&
4731          "One half of the selector was all UNDEFs and the other was all the "
4732          "same value. This should have been addressed before this function.");
4733   return DAG.getNode(
4734       ISD::CONCAT_VECTORS, dl, VT,
4735       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4736       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4739 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4740   SDValue N0 = N->getOperand(0);
4741   SDValue N1 = N->getOperand(1);
4742   SDValue N2 = N->getOperand(2);
4743   SDLoc DL(N);
4745   // Canonicalize integer abs.
4746   // vselect (setg[te] X,  0),  X, -X ->
4747   // vselect (setgt    X, -1),  X, -X ->
4748   // vselect (setl[te] X,  0), -X,  X ->
4749   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4750   if (N0.getOpcode() == ISD::SETCC) {
4751     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4752     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4753     bool isAbs = false;
4754     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4756     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4757          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4758         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4759       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4760     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4761              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4762       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4764     if (isAbs) {
4765       EVT VT = LHS.getValueType();
4766       SDValue Shift = DAG.getNode(
4767           ISD::SRA, DL, VT, LHS,
4768           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4769       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4770       AddToWorklist(Shift.getNode());
4771       AddToWorklist(Add.getNode());
4772       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4773     }
4774   }
4776   // If the VSELECT result requires splitting and the mask is provided by a
4777   // SETCC, then split both nodes and its operands before legalization. This
4778   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4779   // and enables future optimizations (e.g. min/max pattern matching on X86).
4780   if (N0.getOpcode() == ISD::SETCC) {
4781     EVT VT = N->getValueType(0);
4783     // Check if any splitting is required.
4784     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4785         TargetLowering::TypeSplitVector)
4786       return SDValue();
4788     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4789     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4790     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4791     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4793     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4794     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4796     // Add the new VSELECT nodes to the work list in case they need to be split
4797     // again.
4798     AddToWorklist(Lo.getNode());
4799     AddToWorklist(Hi.getNode());
4801     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4802   }
4804   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4805   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4806     return N1;
4807   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4808   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4809     return N2;
4811   // The ConvertSelectToConcatVector function is assuming both the above
4812   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4813   // and addressed.
4814   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4815       N2.getOpcode() == ISD::CONCAT_VECTORS &&
4816       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4817     SDValue CV = ConvertSelectToConcatVector(N, DAG);
4818     if (CV.getNode())
4819       return CV;
4820   }
4822   return SDValue();
4825 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4826   SDValue N0 = N->getOperand(0);
4827   SDValue N1 = N->getOperand(1);
4828   SDValue N2 = N->getOperand(2);
4829   SDValue N3 = N->getOperand(3);
4830   SDValue N4 = N->getOperand(4);
4831   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4833   // fold select_cc lhs, rhs, x, x, cc -> x
4834   if (N2 == N3)
4835     return N2;
4837   // Determine if the condition we're dealing with is constant
4838   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4839                               N0, N1, CC, SDLoc(N), false);
4840   if (SCC.getNode()) {
4841     AddToWorklist(SCC.getNode());
4843     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4844       if (!SCCC->isNullValue())
4845         return N2;    // cond always true -> true val
4846       else
4847         return N3;    // cond always false -> false val
4848     }
4850     // Fold to a simpler select_cc
4851     if (SCC.getOpcode() == ISD::SETCC)
4852       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4853                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4854                          SCC.getOperand(2));
4855   }
4857   // If we can fold this based on the true/false value, do so.
4858   if (SimplifySelectOps(N, N2, N3))
4859     return SDValue(N, 0);  // Don't revisit N.
4861   // fold select_cc into other things, such as min/max/abs
4862   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4865 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4866   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4867                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4868                        SDLoc(N));
4871 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4872 // dag node into a ConstantSDNode or a build_vector of constants.
4873 // This function is called by the DAGCombiner when visiting sext/zext/aext
4874 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4875 // Vector extends are not folded if operations are legal; this is to
4876 // avoid introducing illegal build_vector dag nodes.
4877 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4878                                          SelectionDAG &DAG, bool LegalTypes,
4879                                          bool LegalOperations) {
4880   unsigned Opcode = N->getOpcode();
4881   SDValue N0 = N->getOperand(0);
4882   EVT VT = N->getValueType(0);
4884   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4885          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4887   // fold (sext c1) -> c1
4888   // fold (zext c1) -> c1
4889   // fold (aext c1) -> c1
4890   if (isa<ConstantSDNode>(N0))
4891     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4893   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4894   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4895   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4896   EVT SVT = VT.getScalarType();
4897   if (!(VT.isVector() &&
4898       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4899       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4900     return nullptr;
4902   // We can fold this node into a build_vector.
4903   unsigned VTBits = SVT.getSizeInBits();
4904   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4905   unsigned ShAmt = VTBits - EVTBits;
4906   SmallVector<SDValue, 8> Elts;
4907   unsigned NumElts = N0->getNumOperands();
4908   SDLoc DL(N);
4910   for (unsigned i=0; i != NumElts; ++i) {
4911     SDValue Op = N0->getOperand(i);
4912     if (Op->getOpcode() == ISD::UNDEF) {
4913       Elts.push_back(DAG.getUNDEF(SVT));
4914       continue;
4915     }
4917     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4918     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4919     if (Opcode == ISD::SIGN_EXTEND)
4920       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4921                                      SVT));
4922     else
4923       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4924                                      SVT));
4925   }
4927   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4930 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4931 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4932 // transformation. Returns true if extension are possible and the above
4933 // mentioned transformation is profitable.
4934 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4935                                     unsigned ExtOpc,
4936                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4937                                     const TargetLowering &TLI) {
4938   bool HasCopyToRegUses = false;
4939   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4940   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4941                             UE = N0.getNode()->use_end();
4942        UI != UE; ++UI) {
4943     SDNode *User = *UI;
4944     if (User == N)
4945       continue;
4946     if (UI.getUse().getResNo() != N0.getResNo())
4947       continue;
4948     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4949     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4950       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4951       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4952         // Sign bits will be lost after a zext.
4953         return false;
4954       bool Add = false;
4955       for (unsigned i = 0; i != 2; ++i) {
4956         SDValue UseOp = User->getOperand(i);
4957         if (UseOp == N0)
4958           continue;
4959         if (!isa<ConstantSDNode>(UseOp))
4960           return false;
4961         Add = true;
4962       }
4963       if (Add)
4964         ExtendNodes.push_back(User);
4965       continue;
4966     }
4967     // If truncates aren't free and there are users we can't
4968     // extend, it isn't worthwhile.
4969     if (!isTruncFree)
4970       return false;
4971     // Remember if this value is live-out.
4972     if (User->getOpcode() == ISD::CopyToReg)
4973       HasCopyToRegUses = true;
4974   }
4976   if (HasCopyToRegUses) {
4977     bool BothLiveOut = false;
4978     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4979          UI != UE; ++UI) {
4980       SDUse &Use = UI.getUse();
4981       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4982         BothLiveOut = true;
4983         break;
4984       }
4985     }
4986     if (BothLiveOut)
4987       // Both unextended and extended values are live out. There had better be
4988       // a good reason for the transformation.
4989       return ExtendNodes.size();
4990   }
4991   return true;
4994 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4995                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4996                                   ISD::NodeType ExtType) {
4997   // Extend SetCC uses if necessary.
4998   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4999     SDNode *SetCC = SetCCs[i];
5000     SmallVector<SDValue, 4> Ops;
5002     for (unsigned j = 0; j != 2; ++j) {
5003       SDValue SOp = SetCC->getOperand(j);
5004       if (SOp == Trunc)
5005         Ops.push_back(ExtLoad);
5006       else
5007         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5008     }
5010     Ops.push_back(SetCC->getOperand(2));
5011     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5012   }
5015 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5016   SDValue N0 = N->getOperand(0);
5017   EVT VT = N->getValueType(0);
5019   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5020                                               LegalOperations))
5021     return SDValue(Res, 0);
5023   // fold (sext (sext x)) -> (sext x)
5024   // fold (sext (aext x)) -> (sext x)
5025   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5026     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5027                        N0.getOperand(0));
5029   if (N0.getOpcode() == ISD::TRUNCATE) {
5030     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5031     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5032     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5033     if (NarrowLoad.getNode()) {
5034       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5035       if (NarrowLoad.getNode() != N0.getNode()) {
5036         CombineTo(N0.getNode(), NarrowLoad);
5037         // CombineTo deleted the truncate, if needed, but not what's under it.
5038         AddToWorklist(oye);
5039       }
5040       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5041     }
5043     // See if the value being truncated is already sign extended.  If so, just
5044     // eliminate the trunc/sext pair.
5045     SDValue Op = N0.getOperand(0);
5046     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5047     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5048     unsigned DestBits = VT.getScalarType().getSizeInBits();
5049     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5051     if (OpBits == DestBits) {
5052       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5053       // bits, it is already ready.
5054       if (NumSignBits > DestBits-MidBits)
5055         return Op;
5056     } else if (OpBits < DestBits) {
5057       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5058       // bits, just sext from i32.
5059       if (NumSignBits > OpBits-MidBits)
5060         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5061     } else {
5062       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5063       // bits, just truncate to i32.
5064       if (NumSignBits > OpBits-MidBits)
5065         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5066     }
5068     // fold (sext (truncate x)) -> (sextinreg x).
5069     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5070                                                  N0.getValueType())) {
5071       if (OpBits < DestBits)
5072         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5073       else if (OpBits > DestBits)
5074         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5075       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5076                          DAG.getValueType(N0.getValueType()));
5077     }
5078   }
5080   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5081   // None of the supported targets knows how to perform load and sign extend
5082   // on vectors in one instruction.  We only perform this transformation on
5083   // scalars.
5084   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5085       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5086       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5087        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5088     bool DoXform = true;
5089     SmallVector<SDNode*, 4> SetCCs;
5090     if (!N0.hasOneUse())
5091       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5092     if (DoXform) {
5093       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5094       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5095                                        LN0->getChain(),
5096                                        LN0->getBasePtr(), N0.getValueType(),
5097                                        LN0->getMemOperand());
5098       CombineTo(N, ExtLoad);
5099       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5100                                   N0.getValueType(), ExtLoad);
5101       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5102       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5103                       ISD::SIGN_EXTEND);
5104       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5105     }
5106   }
5108   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5109   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5110   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5111       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5112     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5113     EVT MemVT = LN0->getMemoryVT();
5114     if ((!LegalOperations && !LN0->isVolatile()) ||
5115         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5116       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5117                                        LN0->getChain(),
5118                                        LN0->getBasePtr(), MemVT,
5119                                        LN0->getMemOperand());
5120       CombineTo(N, ExtLoad);
5121       CombineTo(N0.getNode(),
5122                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5123                             N0.getValueType(), ExtLoad),
5124                 ExtLoad.getValue(1));
5125       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5126     }
5127   }
5129   // fold (sext (and/or/xor (load x), cst)) ->
5130   //      (and/or/xor (sextload x), (sext cst))
5131   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5132        N0.getOpcode() == ISD::XOR) &&
5133       isa<LoadSDNode>(N0.getOperand(0)) &&
5134       N0.getOperand(1).getOpcode() == ISD::Constant &&
5135       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5136       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5137     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5138     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5139       bool DoXform = true;
5140       SmallVector<SDNode*, 4> SetCCs;
5141       if (!N0.hasOneUse())
5142         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5143                                           SetCCs, TLI);
5144       if (DoXform) {
5145         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5146                                          LN0->getChain(), LN0->getBasePtr(),
5147                                          LN0->getMemoryVT(),
5148                                          LN0->getMemOperand());
5149         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5150         Mask = Mask.sext(VT.getSizeInBits());
5151         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5152                                   ExtLoad, DAG.getConstant(Mask, VT));
5153         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5154                                     SDLoc(N0.getOperand(0)),
5155                                     N0.getOperand(0).getValueType(), ExtLoad);
5156         CombineTo(N, And);
5157         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5158         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5159                         ISD::SIGN_EXTEND);
5160         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5161       }
5162     }
5163   }
5165   if (N0.getOpcode() == ISD::SETCC) {
5166     EVT N0VT = N0.getOperand(0).getValueType();
5167     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5168     // Only do this before legalize for now.
5169     if (VT.isVector() && !LegalOperations &&
5170         TLI.getBooleanContents(N0VT) ==
5171             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5172       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5173       // of the same size as the compared operands. Only optimize sext(setcc())
5174       // if this is the case.
5175       EVT SVT = getSetCCResultType(N0VT);
5177       // We know that the # elements of the results is the same as the
5178       // # elements of the compare (and the # elements of the compare result
5179       // for that matter).  Check to see that they are the same size.  If so,
5180       // we know that the element size of the sext'd result matches the
5181       // element size of the compare operands.
5182       if (VT.getSizeInBits() == SVT.getSizeInBits())
5183         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5184                              N0.getOperand(1),
5185                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5187       // If the desired elements are smaller or larger than the source
5188       // elements we can use a matching integer vector type and then
5189       // truncate/sign extend
5190       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5191       if (SVT == MatchingVectorType) {
5192         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5193                                N0.getOperand(0), N0.getOperand(1),
5194                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5195         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5196       }
5197     }
5199     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5200     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5201     SDValue NegOne =
5202       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5203     SDValue SCC =
5204       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5205                        NegOne, DAG.getConstant(0, VT),
5206                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5207     if (SCC.getNode()) return SCC;
5209     if (!VT.isVector()) {
5210       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5211       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5212         SDLoc DL(N);
5213         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5214         SDValue SetCC = DAG.getSetCC(DL,
5215                                      SetCCVT,
5216                                      N0.getOperand(0), N0.getOperand(1), CC);
5217         EVT SelectVT = getSetCCResultType(VT);
5218         return DAG.getSelect(DL, VT,
5219                              DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5220                              NegOne, DAG.getConstant(0, VT));
5222       }
5223     }
5224   }
5226   // fold (sext x) -> (zext x) if the sign bit is known zero.
5227   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5228       DAG.SignBitIsZero(N0))
5229     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5231   return SDValue();
5234 // isTruncateOf - If N is a truncate of some other value, return true, record
5235 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5236 // This function computes KnownZero to avoid a duplicated call to
5237 // computeKnownBits in the caller.
5238 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5239                          APInt &KnownZero) {
5240   APInt KnownOne;
5241   if (N->getOpcode() == ISD::TRUNCATE) {
5242     Op = N->getOperand(0);
5243     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5244     return true;
5245   }
5247   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5248       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5249     return false;
5251   SDValue Op0 = N->getOperand(0);
5252   SDValue Op1 = N->getOperand(1);
5253   assert(Op0.getValueType() == Op1.getValueType());
5255   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5256   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5257   if (COp0 && COp0->isNullValue())
5258     Op = Op1;
5259   else if (COp1 && COp1->isNullValue())
5260     Op = Op0;
5261   else
5262     return false;
5264   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5266   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5267     return false;
5269   return true;
5272 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5273   SDValue N0 = N->getOperand(0);
5274   EVT VT = N->getValueType(0);
5276   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5277                                               LegalOperations))
5278     return SDValue(Res, 0);
5280   // fold (zext (zext x)) -> (zext x)
5281   // fold (zext (aext x)) -> (zext x)
5282   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5283     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5284                        N0.getOperand(0));
5286   // fold (zext (truncate x)) -> (zext x) or
5287   //      (zext (truncate x)) -> (truncate x)
5288   // This is valid when the truncated bits of x are already zero.
5289   // FIXME: We should extend this to work for vectors too.
5290   SDValue Op;
5291   APInt KnownZero;
5292   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5293     APInt TruncatedBits =
5294       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5295       APInt(Op.getValueSizeInBits(), 0) :
5296       APInt::getBitsSet(Op.getValueSizeInBits(),
5297                         N0.getValueSizeInBits(),
5298                         std::min(Op.getValueSizeInBits(),
5299                                  VT.getSizeInBits()));
5300     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5301       if (VT.bitsGT(Op.getValueType()))
5302         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5303       if (VT.bitsLT(Op.getValueType()))
5304         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5306       return Op;
5307     }
5308   }
5310   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5311   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5312   if (N0.getOpcode() == ISD::TRUNCATE) {
5313     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5314     if (NarrowLoad.getNode()) {
5315       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5316       if (NarrowLoad.getNode() != N0.getNode()) {
5317         CombineTo(N0.getNode(), NarrowLoad);
5318         // CombineTo deleted the truncate, if needed, but not what's under it.
5319         AddToWorklist(oye);
5320       }
5321       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5322     }
5323   }
5325   // fold (zext (truncate x)) -> (and x, mask)
5326   if (N0.getOpcode() == ISD::TRUNCATE &&
5327       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5329     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5330     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5331     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5332     if (NarrowLoad.getNode()) {
5333       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5334       if (NarrowLoad.getNode() != N0.getNode()) {
5335         CombineTo(N0.getNode(), NarrowLoad);
5336         // CombineTo deleted the truncate, if needed, but not what's under it.
5337         AddToWorklist(oye);
5338       }
5339       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5340     }
5342     SDValue Op = N0.getOperand(0);
5343     if (Op.getValueType().bitsLT(VT)) {
5344       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5345       AddToWorklist(Op.getNode());
5346     } else if (Op.getValueType().bitsGT(VT)) {
5347       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5348       AddToWorklist(Op.getNode());
5349     }
5350     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5351                                   N0.getValueType().getScalarType());
5352   }
5354   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5355   // if either of the casts is not free.
5356   if (N0.getOpcode() == ISD::AND &&
5357       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5358       N0.getOperand(1).getOpcode() == ISD::Constant &&
5359       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5360                            N0.getValueType()) ||
5361        !TLI.isZExtFree(N0.getValueType(), VT))) {
5362     SDValue X = N0.getOperand(0).getOperand(0);
5363     if (X.getValueType().bitsLT(VT)) {
5364       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5365     } else if (X.getValueType().bitsGT(VT)) {
5366       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5367     }
5368     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5369     Mask = Mask.zext(VT.getSizeInBits());
5370     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5371                        X, DAG.getConstant(Mask, VT));
5372   }
5374   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5375   // None of the supported targets knows how to perform load and vector_zext
5376   // on vectors in one instruction.  We only perform this transformation on
5377   // scalars.
5378   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5379       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5380       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5381        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5382     bool DoXform = true;
5383     SmallVector<SDNode*, 4> SetCCs;
5384     if (!N0.hasOneUse())
5385       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5386     if (DoXform) {
5387       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5388       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5389                                        LN0->getChain(),
5390                                        LN0->getBasePtr(), N0.getValueType(),
5391                                        LN0->getMemOperand());
5392       CombineTo(N, ExtLoad);
5393       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5394                                   N0.getValueType(), ExtLoad);
5395       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5397       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5398                       ISD::ZERO_EXTEND);
5399       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5400     }
5401   }
5403   // fold (zext (and/or/xor (load x), cst)) ->
5404   //      (and/or/xor (zextload x), (zext cst))
5405   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5406        N0.getOpcode() == ISD::XOR) &&
5407       isa<LoadSDNode>(N0.getOperand(0)) &&
5408       N0.getOperand(1).getOpcode() == ISD::Constant &&
5409       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5410       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5411     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5412     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5413       bool DoXform = true;
5414       SmallVector<SDNode*, 4> SetCCs;
5415       if (!N0.hasOneUse())
5416         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5417                                           SetCCs, TLI);
5418       if (DoXform) {
5419         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5420                                          LN0->getChain(), LN0->getBasePtr(),
5421                                          LN0->getMemoryVT(),
5422                                          LN0->getMemOperand());
5423         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5424         Mask = Mask.zext(VT.getSizeInBits());
5425         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5426                                   ExtLoad, DAG.getConstant(Mask, VT));
5427         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5428                                     SDLoc(N0.getOperand(0)),
5429                                     N0.getOperand(0).getValueType(), ExtLoad);
5430         CombineTo(N, And);
5431         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5432         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5433                         ISD::ZERO_EXTEND);
5434         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5435       }
5436     }
5437   }
5439   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5440   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5441   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5442       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5443     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5444     EVT MemVT = LN0->getMemoryVT();
5445     if ((!LegalOperations && !LN0->isVolatile()) ||
5446         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5447       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5448                                        LN0->getChain(),
5449                                        LN0->getBasePtr(), MemVT,
5450                                        LN0->getMemOperand());
5451       CombineTo(N, ExtLoad);
5452       CombineTo(N0.getNode(),
5453                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5454                             ExtLoad),
5455                 ExtLoad.getValue(1));
5456       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5457     }
5458   }
5460   if (N0.getOpcode() == ISD::SETCC) {
5461     if (!LegalOperations && VT.isVector() &&
5462         N0.getValueType().getVectorElementType() == MVT::i1) {
5463       EVT N0VT = N0.getOperand(0).getValueType();
5464       if (getSetCCResultType(N0VT) == N0.getValueType())
5465         return SDValue();
5467       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5468       // Only do this before legalize for now.
5469       EVT EltVT = VT.getVectorElementType();
5470       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5471                                     DAG.getConstant(1, EltVT));
5472       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5473         // We know that the # elements of the results is the same as the
5474         // # elements of the compare (and the # elements of the compare result
5475         // for that matter).  Check to see that they are the same size.  If so,
5476         // we know that the element size of the sext'd result matches the
5477         // element size of the compare operands.
5478         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5479                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5480                                          N0.getOperand(1),
5481                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5482                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5483                                        OneOps));
5485       // If the desired elements are smaller or larger than the source
5486       // elements we can use a matching integer vector type and then
5487       // truncate/sign extend
5488       EVT MatchingElementType =
5489         EVT::getIntegerVT(*DAG.getContext(),
5490                           N0VT.getScalarType().getSizeInBits());
5491       EVT MatchingVectorType =
5492         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5493                          N0VT.getVectorNumElements());
5494       SDValue VsetCC =
5495         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5496                       N0.getOperand(1),
5497                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5498       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5499                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5500                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5501     }
5503     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5504     SDValue SCC =
5505       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5506                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5507                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5508     if (SCC.getNode()) return SCC;
5509   }
5511   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5512   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5513       isa<ConstantSDNode>(N0.getOperand(1)) &&
5514       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5515       N0.hasOneUse()) {
5516     SDValue ShAmt = N0.getOperand(1);
5517     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5518     if (N0.getOpcode() == ISD::SHL) {
5519       SDValue InnerZExt = N0.getOperand(0);
5520       // If the original shl may be shifting out bits, do not perform this
5521       // transformation.
5522       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5523         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5524       if (ShAmtVal > KnownZeroBits)
5525         return SDValue();
5526     }
5528     SDLoc DL(N);
5530     // Ensure that the shift amount is wide enough for the shifted value.
5531     if (VT.getSizeInBits() >= 256)
5532       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5534     return DAG.getNode(N0.getOpcode(), DL, VT,
5535                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5536                        ShAmt);
5537   }
5539   return SDValue();
5542 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5543   SDValue N0 = N->getOperand(0);
5544   EVT VT = N->getValueType(0);
5546   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5547                                               LegalOperations))
5548     return SDValue(Res, 0);
5550   // fold (aext (aext x)) -> (aext x)
5551   // fold (aext (zext x)) -> (zext x)
5552   // fold (aext (sext x)) -> (sext x)
5553   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5554       N0.getOpcode() == ISD::ZERO_EXTEND ||
5555       N0.getOpcode() == ISD::SIGN_EXTEND)
5556     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5558   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5559   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5560   if (N0.getOpcode() == ISD::TRUNCATE) {
5561     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5562     if (NarrowLoad.getNode()) {
5563       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5564       if (NarrowLoad.getNode() != N0.getNode()) {
5565         CombineTo(N0.getNode(), NarrowLoad);
5566         // CombineTo deleted the truncate, if needed, but not what's under it.
5567         AddToWorklist(oye);
5568       }
5569       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5570     }
5571   }
5573   // fold (aext (truncate x))
5574   if (N0.getOpcode() == ISD::TRUNCATE) {
5575     SDValue TruncOp = N0.getOperand(0);
5576     if (TruncOp.getValueType() == VT)
5577       return TruncOp; // x iff x size == zext size.
5578     if (TruncOp.getValueType().bitsGT(VT))
5579       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5580     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5581   }
5583   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5584   // if the trunc is not free.
5585   if (N0.getOpcode() == ISD::AND &&
5586       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5587       N0.getOperand(1).getOpcode() == ISD::Constant &&
5588       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5589                           N0.getValueType())) {
5590     SDValue X = N0.getOperand(0).getOperand(0);
5591     if (X.getValueType().bitsLT(VT)) {
5592       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5593     } else if (X.getValueType().bitsGT(VT)) {
5594       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5595     }
5596     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5597     Mask = Mask.zext(VT.getSizeInBits());
5598     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5599                        X, DAG.getConstant(Mask, VT));
5600   }
5602   // fold (aext (load x)) -> (aext (truncate (extload x)))
5603   // None of the supported targets knows how to perform load and any_ext
5604   // on vectors in one instruction.  We only perform this transformation on
5605   // scalars.
5606   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5607       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5608       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5609     bool DoXform = true;
5610     SmallVector<SDNode*, 4> SetCCs;
5611     if (!N0.hasOneUse())
5612       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5613     if (DoXform) {
5614       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5615       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5616                                        LN0->getChain(),
5617                                        LN0->getBasePtr(), N0.getValueType(),
5618                                        LN0->getMemOperand());
5619       CombineTo(N, ExtLoad);
5620       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5621                                   N0.getValueType(), ExtLoad);
5622       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5623       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5624                       ISD::ANY_EXTEND);
5625       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5626     }
5627   }
5629   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5630   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5631   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5632   if (N0.getOpcode() == ISD::LOAD &&
5633       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5634       N0.hasOneUse()) {
5635     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5636     ISD::LoadExtType ExtType = LN0->getExtensionType();
5637     EVT MemVT = LN0->getMemoryVT();
5638     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5639       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5640                                        VT, LN0->getChain(), LN0->getBasePtr(),
5641                                        MemVT, LN0->getMemOperand());
5642       CombineTo(N, ExtLoad);
5643       CombineTo(N0.getNode(),
5644                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5645                             N0.getValueType(), ExtLoad),
5646                 ExtLoad.getValue(1));
5647       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5648     }
5649   }
5651   if (N0.getOpcode() == ISD::SETCC) {
5652     // For vectors:
5653     // aext(setcc) -> vsetcc
5654     // aext(setcc) -> truncate(vsetcc)
5655     // aext(setcc) -> aext(vsetcc)
5656     // Only do this before legalize for now.
5657     if (VT.isVector() && !LegalOperations) {
5658       EVT N0VT = N0.getOperand(0).getValueType();
5659         // We know that the # elements of the results is the same as the
5660         // # elements of the compare (and the # elements of the compare result
5661         // for that matter).  Check to see that they are the same size.  If so,
5662         // we know that the element size of the sext'd result matches the
5663         // element size of the compare operands.
5664       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5665         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5666                              N0.getOperand(1),
5667                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5668       // If the desired elements are smaller or larger than the source
5669       // elements we can use a matching integer vector type and then
5670       // truncate/any extend
5671       else {
5672         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5673         SDValue VsetCC =
5674           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5675                         N0.getOperand(1),
5676                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5677         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5678       }
5679     }
5681     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5682     SDValue SCC =
5683       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5684                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5685                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5686     if (SCC.getNode())
5687       return SCC;
5688   }
5690   return SDValue();
5693 /// See if the specified operand can be simplified with the knowledge that only
5694 /// the bits specified by Mask are used.  If so, return the simpler operand,
5695 /// otherwise return a null SDValue.
5696 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5697   switch (V.getOpcode()) {
5698   default: break;
5699   case ISD::Constant: {
5700     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5701     assert(CV && "Const value should be ConstSDNode.");
5702     const APInt &CVal = CV->getAPIntValue();
5703     APInt NewVal = CVal & Mask;
5704     if (NewVal != CVal)
5705       return DAG.getConstant(NewVal, V.getValueType());
5706     break;
5707   }
5708   case ISD::OR:
5709   case ISD::XOR:
5710     // If the LHS or RHS don't contribute bits to the or, drop them.
5711     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5712       return V.getOperand(1);
5713     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5714       return V.getOperand(0);
5715     break;
5716   case ISD::SRL:
5717     // Only look at single-use SRLs.
5718     if (!V.getNode()->hasOneUse())
5719       break;
5720     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5721       // See if we can recursively simplify the LHS.
5722       unsigned Amt = RHSC->getZExtValue();
5724       // Watch out for shift count overflow though.
5725       if (Amt >= Mask.getBitWidth()) break;
5726       APInt NewMask = Mask << Amt;
5727       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5728       if (SimplifyLHS.getNode())
5729         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5730                            SimplifyLHS, V.getOperand(1));
5731     }
5732   }
5733   return SDValue();
5736 /// If the result of a wider load is shifted to right of N  bits and then
5737 /// truncated to a narrower type and where N is a multiple of number of bits of
5738 /// the narrower type, transform it to a narrower load from address + N / num of
5739 /// bits of new type. If the result is to be extended, also fold the extension
5740 /// to form a extending load.
5741 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5742   unsigned Opc = N->getOpcode();
5744   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5745   SDValue N0 = N->getOperand(0);
5746   EVT VT = N->getValueType(0);
5747   EVT ExtVT = VT;
5749   // This transformation isn't valid for vector loads.
5750   if (VT.isVector())
5751     return SDValue();
5753   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5754   // extended to VT.
5755   if (Opc == ISD::SIGN_EXTEND_INREG) {
5756     ExtType = ISD::SEXTLOAD;
5757     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5758   } else if (Opc == ISD::SRL) {
5759     // Another special-case: SRL is basically zero-extending a narrower value.
5760     ExtType = ISD::ZEXTLOAD;
5761     N0 = SDValue(N, 0);
5762     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5763     if (!N01) return SDValue();
5764     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5765                               VT.getSizeInBits() - N01->getZExtValue());
5766   }
5767   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5768     return SDValue();
5770   unsigned EVTBits = ExtVT.getSizeInBits();
5772   // Do not generate loads of non-round integer types since these can
5773   // be expensive (and would be wrong if the type is not byte sized).
5774   if (!ExtVT.isRound())
5775     return SDValue();
5777   unsigned ShAmt = 0;
5778   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5779     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5780       ShAmt = N01->getZExtValue();
5781       // Is the shift amount a multiple of size of VT?
5782       if ((ShAmt & (EVTBits-1)) == 0) {
5783         N0 = N0.getOperand(0);
5784         // Is the load width a multiple of size of VT?
5785         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5786           return SDValue();
5787       }
5789       // At this point, we must have a load or else we can't do the transform.
5790       if (!isa<LoadSDNode>(N0)) return SDValue();
5792       // Because a SRL must be assumed to *need* to zero-extend the high bits
5793       // (as opposed to anyext the high bits), we can't combine the zextload
5794       // lowering of SRL and an sextload.
5795       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5796         return SDValue();
5798       // If the shift amount is larger than the input type then we're not
5799       // accessing any of the loaded bytes.  If the load was a zextload/extload
5800       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5801       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5802         return SDValue();
5803     }
5804   }
5806   // If the load is shifted left (and the result isn't shifted back right),
5807   // we can fold the truncate through the shift.
5808   unsigned ShLeftAmt = 0;
5809   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5810       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5811     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5812       ShLeftAmt = N01->getZExtValue();
5813       N0 = N0.getOperand(0);
5814     }
5815   }
5817   // If we haven't found a load, we can't narrow it.  Don't transform one with
5818   // multiple uses, this would require adding a new load.
5819   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5820     return SDValue();
5822   // Don't change the width of a volatile load.
5823   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5824   if (LN0->isVolatile())
5825     return SDValue();
5827   // Verify that we are actually reducing a load width here.
5828   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5829     return SDValue();
5831   // For the transform to be legal, the load must produce only two values
5832   // (the value loaded and the chain).  Don't transform a pre-increment
5833   // load, for example, which produces an extra value.  Otherwise the
5834   // transformation is not equivalent, and the downstream logic to replace
5835   // uses gets things wrong.
5836   if (LN0->getNumValues() > 2)
5837     return SDValue();
5839   // If the load that we're shrinking is an extload and we're not just
5840   // discarding the extension we can't simply shrink the load. Bail.
5841   // TODO: It would be possible to merge the extensions in some cases.
5842   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5843       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5844     return SDValue();
5846   EVT PtrType = N0.getOperand(1).getValueType();
5848   if (PtrType == MVT::Untyped || PtrType.isExtended())
5849     // It's not possible to generate a constant of extended or untyped type.
5850     return SDValue();
5852   // For big endian targets, we need to adjust the offset to the pointer to
5853   // load the correct bytes.
5854   if (TLI.isBigEndian()) {
5855     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5856     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5857     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5858   }
5860   uint64_t PtrOff = ShAmt / 8;
5861   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5862   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5863                                PtrType, LN0->getBasePtr(),
5864                                DAG.getConstant(PtrOff, PtrType));
5865   AddToWorklist(NewPtr.getNode());
5867   SDValue Load;
5868   if (ExtType == ISD::NON_EXTLOAD)
5869     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5870                         LN0->getPointerInfo().getWithOffset(PtrOff),
5871                         LN0->isVolatile(), LN0->isNonTemporal(),
5872                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5873   else
5874     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5875                           LN0->getPointerInfo().getWithOffset(PtrOff),
5876                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5877                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5879   // Replace the old load's chain with the new load's chain.
5880   WorklistRemover DeadNodes(*this);
5881   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5883   // Shift the result left, if we've swallowed a left shift.
5884   SDValue Result = Load;
5885   if (ShLeftAmt != 0) {
5886     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5887     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5888       ShImmTy = VT;
5889     // If the shift amount is as large as the result size (but, presumably,
5890     // no larger than the source) then the useful bits of the result are
5891     // zero; we can't simply return the shortened shift, because the result
5892     // of that operation is undefined.
5893     if (ShLeftAmt >= VT.getSizeInBits())
5894       Result = DAG.getConstant(0, VT);
5895     else
5896       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5897                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5898   }
5900   // Return the new loaded value.
5901   return Result;
5904 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5905   SDValue N0 = N->getOperand(0);
5906   SDValue N1 = N->getOperand(1);
5907   EVT VT = N->getValueType(0);
5908   EVT EVT = cast<VTSDNode>(N1)->getVT();
5909   unsigned VTBits = VT.getScalarType().getSizeInBits();
5910   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5912   // fold (sext_in_reg c1) -> c1
5913   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5914     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5916   // If the input is already sign extended, just drop the extension.
5917   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5918     return N0;
5920   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5921   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5922       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5923     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5924                        N0.getOperand(0), N1);
5926   // fold (sext_in_reg (sext x)) -> (sext x)
5927   // fold (sext_in_reg (aext x)) -> (sext x)
5928   // if x is small enough.
5929   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5930     SDValue N00 = N0.getOperand(0);
5931     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5932         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5933       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5934   }
5936   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5937   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5938     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5940   // fold operands of sext_in_reg based on knowledge that the top bits are not
5941   // demanded.
5942   if (SimplifyDemandedBits(SDValue(N, 0)))
5943     return SDValue(N, 0);
5945   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5946   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5947   SDValue NarrowLoad = ReduceLoadWidth(N);
5948   if (NarrowLoad.getNode())
5949     return NarrowLoad;
5951   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5952   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5953   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5954   if (N0.getOpcode() == ISD::SRL) {
5955     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5956       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5957         // We can turn this into an SRA iff the input to the SRL is already sign
5958         // extended enough.
5959         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5960         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5961           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5962                              N0.getOperand(0), N0.getOperand(1));
5963       }
5964   }
5966   // fold (sext_inreg (extload x)) -> (sextload x)
5967   if (ISD::isEXTLoad(N0.getNode()) &&
5968       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5969       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5970       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5971        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5972     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5973     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5974                                      LN0->getChain(),
5975                                      LN0->getBasePtr(), EVT,
5976                                      LN0->getMemOperand());
5977     CombineTo(N, ExtLoad);
5978     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5979     AddToWorklist(ExtLoad.getNode());
5980     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5981   }
5982   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5983   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5984       N0.hasOneUse() &&
5985       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5986       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5987        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5988     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5989     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5990                                      LN0->getChain(),
5991                                      LN0->getBasePtr(), EVT,
5992                                      LN0->getMemOperand());
5993     CombineTo(N, ExtLoad);
5994     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5995     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5996   }
5998   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5999   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6000     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6001                                        N0.getOperand(1), false);
6002     if (BSwap.getNode())
6003       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6004                          BSwap, N1);
6005   }
6007   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6008   // into a build_vector.
6009   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6010     SmallVector<SDValue, 8> Elts;
6011     unsigned NumElts = N0->getNumOperands();
6012     unsigned ShAmt = VTBits - EVTBits;
6014     for (unsigned i = 0; i != NumElts; ++i) {
6015       SDValue Op = N0->getOperand(i);
6016       if (Op->getOpcode() == ISD::UNDEF) {
6017         Elts.push_back(Op);
6018         continue;
6019       }
6021       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6022       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6023       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6024                                      Op.getValueType()));
6025     }
6027     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6028   }
6030   return SDValue();
6033 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6034   SDValue N0 = N->getOperand(0);
6035   EVT VT = N->getValueType(0);
6036   bool isLE = TLI.isLittleEndian();
6038   // noop truncate
6039   if (N0.getValueType() == N->getValueType(0))
6040     return N0;
6041   // fold (truncate c1) -> c1
6042   if (isa<ConstantSDNode>(N0))
6043     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6044   // fold (truncate (truncate x)) -> (truncate x)
6045   if (N0.getOpcode() == ISD::TRUNCATE)
6046     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6047   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6048   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6049       N0.getOpcode() == ISD::SIGN_EXTEND ||
6050       N0.getOpcode() == ISD::ANY_EXTEND) {
6051     if (N0.getOperand(0).getValueType().bitsLT(VT))
6052       // if the source is smaller than the dest, we still need an extend
6053       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6054                          N0.getOperand(0));
6055     if (N0.getOperand(0).getValueType().bitsGT(VT))
6056       // if the source is larger than the dest, than we just need the truncate
6057       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6058     // if the source and dest are the same type, we can drop both the extend
6059     // and the truncate.
6060     return N0.getOperand(0);
6061   }
6063   // Fold extract-and-trunc into a narrow extract. For example:
6064   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6065   //   i32 y = TRUNCATE(i64 x)
6066   //        -- becomes --
6067   //   v16i8 b = BITCAST (v2i64 val)
6068   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6069   //
6070   // Note: We only run this optimization after type legalization (which often
6071   // creates this pattern) and before operation legalization after which
6072   // we need to be more careful about the vector instructions that we generate.
6073   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6074       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6076     EVT VecTy = N0.getOperand(0).getValueType();
6077     EVT ExTy = N0.getValueType();
6078     EVT TrTy = N->getValueType(0);
6080     unsigned NumElem = VecTy.getVectorNumElements();
6081     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6083     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6084     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6086     SDValue EltNo = N0->getOperand(1);
6087     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6088       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6089       EVT IndexTy = TLI.getVectorIdxTy();
6090       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6092       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6093                               NVT, N0.getOperand(0));
6095       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6096                          SDLoc(N), TrTy, V,
6097                          DAG.getConstant(Index, IndexTy));
6098     }
6099   }
6101   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6102   if (N0.getOpcode() == ISD::SELECT) {
6103     EVT SrcVT = N0.getValueType();
6104     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6105         TLI.isTruncateFree(SrcVT, VT)) {
6106       SDLoc SL(N0);
6107       SDValue Cond = N0.getOperand(0);
6108       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6109       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6110       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6111     }
6112   }
6114   // Fold a series of buildvector, bitcast, and truncate if possible.
6115   // For example fold
6116   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6117   //   (2xi32 (buildvector x, y)).
6118   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6119       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6120       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6121       N0.getOperand(0).hasOneUse()) {
6123     SDValue BuildVect = N0.getOperand(0);
6124     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6125     EVT TruncVecEltTy = VT.getVectorElementType();
6127     // Check that the element types match.
6128     if (BuildVectEltTy == TruncVecEltTy) {
6129       // Now we only need to compute the offset of the truncated elements.
6130       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6131       unsigned TruncVecNumElts = VT.getVectorNumElements();
6132       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6134       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6135              "Invalid number of elements");
6137       SmallVector<SDValue, 8> Opnds;
6138       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6139         Opnds.push_back(BuildVect.getOperand(i));
6141       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6142     }
6143   }
6145   // See if we can simplify the input to this truncate through knowledge that
6146   // only the low bits are being used.
6147   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6148   // Currently we only perform this optimization on scalars because vectors
6149   // may have different active low bits.
6150   if (!VT.isVector()) {
6151     SDValue Shorter =
6152       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6153                                                VT.getSizeInBits()));
6154     if (Shorter.getNode())
6155       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6156   }
6157   // fold (truncate (load x)) -> (smaller load x)
6158   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6159   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6160     SDValue Reduced = ReduceLoadWidth(N);
6161     if (Reduced.getNode())
6162       return Reduced;
6163     // Handle the case where the load remains an extending load even
6164     // after truncation.
6165     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6166       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6167       if (!LN0->isVolatile() &&
6168           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6169         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6170                                          VT, LN0->getChain(), LN0->getBasePtr(),
6171                                          LN0->getMemoryVT(),
6172                                          LN0->getMemOperand());
6173         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6174         return NewLoad;
6175       }
6176     }
6177   }
6178   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6179   // where ... are all 'undef'.
6180   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6181     SmallVector<EVT, 8> VTs;
6182     SDValue V;
6183     unsigned Idx = 0;
6184     unsigned NumDefs = 0;
6186     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6187       SDValue X = N0.getOperand(i);
6188       if (X.getOpcode() != ISD::UNDEF) {
6189         V = X;
6190         Idx = i;
6191         NumDefs++;
6192       }
6193       // Stop if more than one members are non-undef.
6194       if (NumDefs > 1)
6195         break;
6196       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6197                                      VT.getVectorElementType(),
6198                                      X.getValueType().getVectorNumElements()));
6199     }
6201     if (NumDefs == 0)
6202       return DAG.getUNDEF(VT);
6204     if (NumDefs == 1) {
6205       assert(V.getNode() && "The single defined operand is empty!");
6206       SmallVector<SDValue, 8> Opnds;
6207       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6208         if (i != Idx) {
6209           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6210           continue;
6211         }
6212         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6213         AddToWorklist(NV.getNode());
6214         Opnds.push_back(NV);
6215       }
6216       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6217     }
6218   }
6220   // Simplify the operands using demanded-bits information.
6221   if (!VT.isVector() &&
6222       SimplifyDemandedBits(SDValue(N, 0)))
6223     return SDValue(N, 0);
6225   return SDValue();
6228 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6229   SDValue Elt = N->getOperand(i);
6230   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6231     return Elt.getNode();
6232   return Elt.getOperand(Elt.getResNo()).getNode();
6235 /// build_pair (load, load) -> load
6236 /// if load locations are consecutive.
6237 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6238   assert(N->getOpcode() == ISD::BUILD_PAIR);
6240   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6241   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6242   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6243       LD1->getAddressSpace() != LD2->getAddressSpace())
6244     return SDValue();
6245   EVT LD1VT = LD1->getValueType(0);
6247   if (ISD::isNON_EXTLoad(LD2) &&
6248       LD2->hasOneUse() &&
6249       // If both are volatile this would reduce the number of volatile loads.
6250       // If one is volatile it might be ok, but play conservative and bail out.
6251       !LD1->isVolatile() &&
6252       !LD2->isVolatile() &&
6253       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6254     unsigned Align = LD1->getAlignment();
6255     unsigned NewAlign = TLI.getDataLayout()->
6256       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6258     if (NewAlign <= Align &&
6259         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6260       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6261                          LD1->getBasePtr(), LD1->getPointerInfo(),
6262                          false, false, false, Align);
6263   }
6265   return SDValue();
6268 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6269   SDValue N0 = N->getOperand(0);
6270   EVT VT = N->getValueType(0);
6272   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6273   // Only do this before legalize, since afterward the target may be depending
6274   // on the bitconvert.
6275   // First check to see if this is all constant.
6276   if (!LegalTypes &&
6277       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6278       VT.isVector()) {
6279     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6281     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6282     assert(!DestEltVT.isVector() &&
6283            "Element type of vector ValueType must not be vector!");
6284     if (isSimple)
6285       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6286   }
6288   // If the input is a constant, let getNode fold it.
6289   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6290     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6291     if (Res.getNode() != N) {
6292       if (!LegalOperations ||
6293           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6294         return Res;
6296       // Folding it resulted in an illegal node, and it's too late to
6297       // do that. Clean up the old node and forego the transformation.
6298       // Ideally this won't happen very often, because instcombine
6299       // and the earlier dagcombine runs (where illegal nodes are
6300       // permitted) should have folded most of them already.
6301       deleteAndRecombine(Res.getNode());
6302     }
6303   }
6305   // (conv (conv x, t1), t2) -> (conv x, t2)
6306   if (N0.getOpcode() == ISD::BITCAST)
6307     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6308                        N0.getOperand(0));
6310   // fold (conv (load x)) -> (load (conv*)x)
6311   // If the resultant load doesn't need a higher alignment than the original!
6312   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6313       // Do not change the width of a volatile load.
6314       !cast<LoadSDNode>(N0)->isVolatile() &&
6315       // Do not remove the cast if the types differ in endian layout.
6316       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6317       TLI.hasBigEndianPartOrdering(VT) &&
6318       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6319       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6320     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6321     unsigned Align = TLI.getDataLayout()->
6322       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6323     unsigned OrigAlign = LN0->getAlignment();
6325     if (Align <= OrigAlign) {
6326       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6327                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6328                                  LN0->isVolatile(), LN0->isNonTemporal(),
6329                                  LN0->isInvariant(), OrigAlign,
6330                                  LN0->getAAInfo());
6331       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6332       return Load;
6333     }
6334   }
6336   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6337   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6338   // This often reduces constant pool loads.
6339   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6340        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6341       N0.getNode()->hasOneUse() && VT.isInteger() &&
6342       !VT.isVector() && !N0.getValueType().isVector()) {
6343     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6344                                   N0.getOperand(0));
6345     AddToWorklist(NewConv.getNode());
6347     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6348     if (N0.getOpcode() == ISD::FNEG)
6349       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6350                          NewConv, DAG.getConstant(SignBit, VT));
6351     assert(N0.getOpcode() == ISD::FABS);
6352     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6353                        NewConv, DAG.getConstant(~SignBit, VT));
6354   }
6356   // fold (bitconvert (fcopysign cst, x)) ->
6357   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6358   // Note that we don't handle (copysign x, cst) because this can always be
6359   // folded to an fneg or fabs.
6360   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6361       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6362       VT.isInteger() && !VT.isVector()) {
6363     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6364     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6365     if (isTypeLegal(IntXVT)) {
6366       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6367                               IntXVT, N0.getOperand(1));
6368       AddToWorklist(X.getNode());
6370       // If X has a different width than the result/lhs, sext it or truncate it.
6371       unsigned VTWidth = VT.getSizeInBits();
6372       if (OrigXWidth < VTWidth) {
6373         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6374         AddToWorklist(X.getNode());
6375       } else if (OrigXWidth > VTWidth) {
6376         // To get the sign bit in the right place, we have to shift it right
6377         // before truncating.
6378         X = DAG.getNode(ISD::SRL, SDLoc(X),
6379                         X.getValueType(), X,
6380                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6381         AddToWorklist(X.getNode());
6382         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6383         AddToWorklist(X.getNode());
6384       }
6386       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6387       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6388                       X, DAG.getConstant(SignBit, VT));
6389       AddToWorklist(X.getNode());
6391       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6392                                 VT, N0.getOperand(0));
6393       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6394                         Cst, DAG.getConstant(~SignBit, VT));
6395       AddToWorklist(Cst.getNode());
6397       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6398     }
6399   }
6401   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6402   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6403     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6404     if (CombineLD.getNode())
6405       return CombineLD;
6406   }
6408   return SDValue();
6411 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6412   EVT VT = N->getValueType(0);
6413   return CombineConsecutiveLoads(N, VT);
6416 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6417 /// operands. DstEltVT indicates the destination element value type.
6418 SDValue DAGCombiner::
6419 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6420   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6422   // If this is already the right type, we're done.
6423   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6425   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6426   unsigned DstBitSize = DstEltVT.getSizeInBits();
6428   // If this is a conversion of N elements of one type to N elements of another
6429   // type, convert each element.  This handles FP<->INT cases.
6430   if (SrcBitSize == DstBitSize) {
6431     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6432                               BV->getValueType(0).getVectorNumElements());
6434     // Due to the FP element handling below calling this routine recursively,
6435     // we can end up with a scalar-to-vector node here.
6436     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6437       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6438                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6439                                      DstEltVT, BV->getOperand(0)));
6441     SmallVector<SDValue, 8> Ops;
6442     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6443       SDValue Op = BV->getOperand(i);
6444       // If the vector element type is not legal, the BUILD_VECTOR operands
6445       // are promoted and implicitly truncated.  Make that explicit here.
6446       if (Op.getValueType() != SrcEltVT)
6447         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6448       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6449                                 DstEltVT, Op));
6450       AddToWorklist(Ops.back().getNode());
6451     }
6452     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6453   }
6455   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6456   // handle annoying details of growing/shrinking FP values, we convert them to
6457   // int first.
6458   if (SrcEltVT.isFloatingPoint()) {
6459     // Convert the input float vector to a int vector where the elements are the
6460     // same sizes.
6461     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6462     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6463     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6464     SrcEltVT = IntVT;
6465   }
6467   // Now we know the input is an integer vector.  If the output is a FP type,
6468   // convert to integer first, then to FP of the right size.
6469   if (DstEltVT.isFloatingPoint()) {
6470     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6471     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6472     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6474     // Next, convert to FP elements of the same size.
6475     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6476   }
6478   // Okay, we know the src/dst types are both integers of differing types.
6479   // Handling growing first.
6480   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6481   if (SrcBitSize < DstBitSize) {
6482     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6484     SmallVector<SDValue, 8> Ops;
6485     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6486          i += NumInputsPerOutput) {
6487       bool isLE = TLI.isLittleEndian();
6488       APInt NewBits = APInt(DstBitSize, 0);
6489       bool EltIsUndef = true;
6490       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6491         // Shift the previously computed bits over.
6492         NewBits <<= SrcBitSize;
6493         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6494         if (Op.getOpcode() == ISD::UNDEF) continue;
6495         EltIsUndef = false;
6497         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6498                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6499       }
6501       if (EltIsUndef)
6502         Ops.push_back(DAG.getUNDEF(DstEltVT));
6503       else
6504         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6505     }
6507     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6508     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6509   }
6511   // Finally, this must be the case where we are shrinking elements: each input
6512   // turns into multiple outputs.
6513   bool isS2V = ISD::isScalarToVector(BV);
6514   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6515   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6516                             NumOutputsPerInput*BV->getNumOperands());
6517   SmallVector<SDValue, 8> Ops;
6519   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6520     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6521       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6522         Ops.push_back(DAG.getUNDEF(DstEltVT));
6523       continue;
6524     }
6526     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6527                   getAPIntValue().zextOrTrunc(SrcBitSize);
6529     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6530       APInt ThisVal = OpVal.trunc(DstBitSize);
6531       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6532       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6533         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6534         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6535                            Ops[0]);
6536       OpVal = OpVal.lshr(DstBitSize);
6537     }
6539     // For big endian targets, swap the order of the pieces of each element.
6540     if (TLI.isBigEndian())
6541       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6542   }
6544   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6547 SDValue DAGCombiner::visitFADD(SDNode *N) {
6548   SDValue N0 = N->getOperand(0);
6549   SDValue N1 = N->getOperand(1);
6550   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6551   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6552   EVT VT = N->getValueType(0);
6553   const TargetOptions &Options = DAG.getTarget().Options;
6554   
6555   // fold vector ops
6556   if (VT.isVector()) {
6557     SDValue FoldedVOp = SimplifyVBinOp(N);
6558     if (FoldedVOp.getNode()) return FoldedVOp;
6559   }
6561   // fold (fadd c1, c2) -> c1 + c2
6562   if (N0CFP && N1CFP)
6563     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6564   // canonicalize constant to RHS
6565   if (N0CFP && !N1CFP)
6566     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6567   // fold (fadd A, 0) -> A
6568   if (Options.UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
6569     return N0;
6570   // fold (fadd A, (fneg B)) -> (fsub A, B)
6571   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6572     isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6573     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6574                        GetNegatedExpression(N1, DAG, LegalOperations));
6575   // fold (fadd (fneg A), B) -> (fsub B, A)
6576   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6577     isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6578     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6579                        GetNegatedExpression(N0, DAG, LegalOperations));
6581   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6582   if (Options.UnsafeFPMath && N1CFP &&
6583       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6584       isa<ConstantFPSDNode>(N0.getOperand(1)))
6585     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6586                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6587                                    N0.getOperand(1), N1));
6589   // No FP constant should be created after legalization as Instruction
6590   // Selection pass has hard time in dealing with FP constant.
6591   //
6592   // We don't need test this condition for transformation like following, as
6593   // the DAG being transformed implies it is legal to take FP constant as
6594   // operand.
6595   //
6596   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6597   //
6598   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6600   // If allow, fold (fadd (fneg x), x) -> 0.0
6601   if (AllowNewFpConst && Options.UnsafeFPMath &&
6602       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6603     return DAG.getConstantFP(0.0, VT);
6605   // If allow, fold (fadd x, (fneg x)) -> 0.0
6606   if (AllowNewFpConst && Options.UnsafeFPMath &&
6607       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6608     return DAG.getConstantFP(0.0, VT);
6610   // In unsafe math mode, we can fold chains of FADD's of the same value
6611   // into multiplications.  This transform is not safe in general because
6612   // we are reducing the number of rounding steps.
6613   if (Options.UnsafeFPMath && TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6614       !N0CFP && !N1CFP) {
6615     if (N0.getOpcode() == ISD::FMUL) {
6616       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6617       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6619       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6620       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6621         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6622                                      SDValue(CFP00, 0),
6623                                      DAG.getConstantFP(1.0, VT));
6624         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6625                            N1, NewCFP);
6626       }
6628       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6629       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6630         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6631                                      SDValue(CFP01, 0),
6632                                      DAG.getConstantFP(1.0, VT));
6633         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6634                            N1, NewCFP);
6635       }
6637       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6638       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6639           N1.getOperand(0) == N1.getOperand(1) &&
6640           N0.getOperand(1) == N1.getOperand(0)) {
6641         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6642                                      SDValue(CFP00, 0),
6643                                      DAG.getConstantFP(2.0, VT));
6644         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6645                            N0.getOperand(1), NewCFP);
6646       }
6648       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6649       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6650           N1.getOperand(0) == N1.getOperand(1) &&
6651           N0.getOperand(0) == N1.getOperand(0)) {
6652         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6653                                      SDValue(CFP01, 0),
6654                                      DAG.getConstantFP(2.0, VT));
6655         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6656                            N0.getOperand(0), NewCFP);
6657       }
6658     }
6660     if (N1.getOpcode() == ISD::FMUL) {
6661       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6662       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6664       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6665       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6666         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6667                                      SDValue(CFP10, 0),
6668                                      DAG.getConstantFP(1.0, VT));
6669         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6670                            N0, NewCFP);
6671       }
6673       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6674       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6675         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6676                                      SDValue(CFP11, 0),
6677                                      DAG.getConstantFP(1.0, VT));
6678         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6679                            N0, NewCFP);
6680       }
6683       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6684       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6685           N0.getOperand(0) == N0.getOperand(1) &&
6686           N1.getOperand(1) == N0.getOperand(0)) {
6687         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6688                                      SDValue(CFP10, 0),
6689                                      DAG.getConstantFP(2.0, VT));
6690         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6691                            N1.getOperand(1), NewCFP);
6692       }
6694       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6695       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6696           N0.getOperand(0) == N0.getOperand(1) &&
6697           N1.getOperand(0) == N0.getOperand(0)) {
6698         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6699                                      SDValue(CFP11, 0),
6700                                      DAG.getConstantFP(2.0, VT));
6701         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6702                            N1.getOperand(0), NewCFP);
6703       }
6704     }
6706     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6707       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6708       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6709       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6710           (N0.getOperand(0) == N1))
6711         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6712                            N1, DAG.getConstantFP(3.0, VT));
6713     }
6715     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6716       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6717       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6718       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6719           N1.getOperand(0) == N0)
6720         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6721                            N0, DAG.getConstantFP(3.0, VT));
6722     }
6724     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6725     if (AllowNewFpConst &&
6726         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6727         N0.getOperand(0) == N0.getOperand(1) &&
6728         N1.getOperand(0) == N1.getOperand(1) &&
6729         N0.getOperand(0) == N1.getOperand(0))
6730       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6731                          N0.getOperand(0),
6732                          DAG.getConstantFP(4.0, VT));
6733   }
6735   // FADD -> FMA combines:
6736   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6737       DAG.getTarget()
6738           .getSubtargetImpl()
6739           ->getTargetLowering()
6740           ->isFMAFasterThanFMulAndFAdd(VT) &&
6741       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6743     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6744     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6745       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6746                          N0.getOperand(0), N0.getOperand(1), N1);
6748     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6749     // Note: Commutes FADD operands.
6750     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6751       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6752                          N1.getOperand(0), N1.getOperand(1), N0);
6753   }
6755   return SDValue();
6758 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6759   SDValue N0 = N->getOperand(0);
6760   SDValue N1 = N->getOperand(1);
6761   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6762   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6763   EVT VT = N->getValueType(0);
6764   SDLoc dl(N);
6765   const TargetOptions &Options = DAG.getTarget().Options;
6767   // fold vector ops
6768   if (VT.isVector()) {
6769     SDValue FoldedVOp = SimplifyVBinOp(N);
6770     if (FoldedVOp.getNode()) return FoldedVOp;
6771   }
6773   // fold (fsub c1, c2) -> c1-c2
6774   if (N0CFP && N1CFP)
6775     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6777   // fold (fsub A, (fneg B)) -> (fadd A, B)
6778   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6779     return DAG.getNode(ISD::FADD, dl, VT, N0,
6780                        GetNegatedExpression(N1, DAG, LegalOperations));
6782   // If 'unsafe math' is enabled, fold lots of things.
6783   if (Options.UnsafeFPMath) {
6784     // (fsub A, 0) -> A
6785     if (N1CFP && N1CFP->getValueAPF().isZero())
6786       return N0;
6788     // (fsub 0, B) -> -B
6789     if (N0CFP && N0CFP->getValueAPF().isZero()) {
6790       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6791         return GetNegatedExpression(N1, DAG, LegalOperations);
6792       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6793         return DAG.getNode(ISD::FNEG, dl, VT, N1);
6794     }
6796     // (fsub x, x) -> 0.0
6797     if (N0 == N1)
6798       return DAG.getConstantFP(0.0f, VT);
6800     // (fsub x, (fadd x, y)) -> (fneg y)
6801     // (fsub x, (fadd y, x)) -> (fneg y)
6802     if (N1.getOpcode() == ISD::FADD) {
6803       SDValue N10 = N1->getOperand(0);
6804       SDValue N11 = N1->getOperand(1);
6806       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
6807         return GetNegatedExpression(N11, DAG, LegalOperations);
6809       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
6810         return GetNegatedExpression(N10, DAG, LegalOperations);
6811     }
6812   }
6814   // FSUB -> FMA combines:
6815   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6816       DAG.getTarget().getSubtargetImpl()
6817           ->getTargetLowering()
6818           ->isFMAFasterThanFMulAndFAdd(VT) &&
6819       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6821     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6822     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6823       return DAG.getNode(ISD::FMA, dl, VT,
6824                          N0.getOperand(0), N0.getOperand(1),
6825                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6827     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6828     // Note: Commutes FSUB operands.
6829     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6830       return DAG.getNode(ISD::FMA, dl, VT,
6831                          DAG.getNode(ISD::FNEG, dl, VT,
6832                          N1.getOperand(0)),
6833                          N1.getOperand(1), N0);
6835     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6836     if (N0.getOpcode() == ISD::FNEG &&
6837         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6838         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6839       SDValue N00 = N0.getOperand(0).getOperand(0);
6840       SDValue N01 = N0.getOperand(0).getOperand(1);
6841       return DAG.getNode(ISD::FMA, dl, VT,
6842                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6843                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6844     }
6845   }
6847   return SDValue();
6850 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6851   SDValue N0 = N->getOperand(0);
6852   SDValue N1 = N->getOperand(1);
6853   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6854   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6855   EVT VT = N->getValueType(0);
6856   const TargetOptions &Options = DAG.getTarget().Options;
6858   // fold vector ops
6859   if (VT.isVector()) {
6860     SDValue FoldedVOp = SimplifyVBinOp(N);
6861     if (FoldedVOp.getNode()) return FoldedVOp;
6862   }
6864   // fold (fmul c1, c2) -> c1*c2
6865   if (N0CFP && N1CFP)
6866     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6867   // canonicalize constant to RHS
6868   if (N0CFP && !N1CFP)
6869     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6870   // fold (fmul A, 0) -> 0
6871   if (Options.UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
6872     return N1;
6873   // fold (fmul A, 1.0) -> A
6874   if (N1CFP && N1CFP->isExactlyValue(1.0))
6875     return N0;
6877   // fold (fmul X, 2.0) -> (fadd X, X)
6878   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6879     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6880   // fold (fmul X, -1.0) -> (fneg X)
6881   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6882     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6883       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6885   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6886   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
6887     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
6888       // Both can be negated for free, check to see if at least one is cheaper
6889       // negated.
6890       if (LHSNeg == 2 || RHSNeg == 2)
6891         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6892                            GetNegatedExpression(N0, DAG, LegalOperations),
6893                            GetNegatedExpression(N1, DAG, LegalOperations));
6894     }
6895   }
6897   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6898   if (Options.UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
6899       N0.getNode()->hasOneUse() && isConstOrConstSplatFP(N0.getOperand(1))) {
6900     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6901                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6902                                    N0.getOperand(1), N1));
6903   }
6905   return SDValue();
6908 SDValue DAGCombiner::visitFMA(SDNode *N) {
6909   SDValue N0 = N->getOperand(0);
6910   SDValue N1 = N->getOperand(1);
6911   SDValue N2 = N->getOperand(2);
6912   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6913   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6914   EVT VT = N->getValueType(0);
6915   SDLoc dl(N);
6916   const TargetOptions &Options = DAG.getTarget().Options;
6918   // Constant fold FMA.
6919   if (isa<ConstantFPSDNode>(N0) &&
6920       isa<ConstantFPSDNode>(N1) &&
6921       isa<ConstantFPSDNode>(N2)) {
6922     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6923   }
6925   if (Options.UnsafeFPMath) {
6926     if (N0CFP && N0CFP->isZero())
6927       return N2;
6928     if (N1CFP && N1CFP->isZero())
6929       return N2;
6930   }
6931   if (N0CFP && N0CFP->isExactlyValue(1.0))
6932     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6933   if (N1CFP && N1CFP->isExactlyValue(1.0))
6934     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6936   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6937   if (N0CFP && !N1CFP)
6938     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6940   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6941   if (Options.UnsafeFPMath && N1CFP &&
6942       N2.getOpcode() == ISD::FMUL &&
6943       N0 == N2.getOperand(0) &&
6944       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6945     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6946                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6947   }
6950   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6951   if (Options.UnsafeFPMath &&
6952       N0.getOpcode() == ISD::FMUL && N1CFP &&
6953       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6954     return DAG.getNode(ISD::FMA, dl, VT,
6955                        N0.getOperand(0),
6956                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6957                        N2);
6958   }
6960   // (fma x, 1, y) -> (fadd x, y)
6961   // (fma x, -1, y) -> (fadd (fneg x), y)
6962   if (N1CFP) {
6963     if (N1CFP->isExactlyValue(1.0))
6964       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6966     if (N1CFP->isExactlyValue(-1.0) &&
6967         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6968       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6969       AddToWorklist(RHSNeg.getNode());
6970       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6971     }
6972   }
6974   // (fma x, c, x) -> (fmul x, (c+1))
6975   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
6976     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6977                        DAG.getNode(ISD::FADD, dl, VT,
6978                                    N1, DAG.getConstantFP(1.0, VT)));
6980   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6981   if (Options.UnsafeFPMath && N1CFP &&
6982       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6983     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6984                        DAG.getNode(ISD::FADD, dl, VT,
6985                                    N1, DAG.getConstantFP(-1.0, VT)));
6988   return SDValue();
6991 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6992   SDValue N0 = N->getOperand(0);
6993   SDValue N1 = N->getOperand(1);
6994   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6995   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6996   EVT VT = N->getValueType(0);
6997   const TargetOptions &Options = DAG.getTarget().Options;
6999   // fold vector ops
7000   if (VT.isVector()) {
7001     SDValue FoldedVOp = SimplifyVBinOp(N);
7002     if (FoldedVOp.getNode()) return FoldedVOp;
7003   }
7005   // fold (fdiv c1, c2) -> c1/c2
7006   if (N0CFP && N1CFP)
7007     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7009   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7010   if (N1CFP && Options.UnsafeFPMath) {
7011     // Compute the reciprocal 1.0 / c2.
7012     APFloat N1APF = N1CFP->getValueAPF();
7013     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7014     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7015     // Only do the transform if the reciprocal is a legal fp immediate that
7016     // isn't too nasty (eg NaN, denormal, ...).
7017     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7018         (!LegalOperations ||
7019          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7020          // backend)... we should handle this gracefully after Legalize.
7021          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7022          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7023          TLI.isFPImmLegal(Recip, VT)))
7024       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7025                          DAG.getConstantFP(Recip, VT));
7026   }
7028   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7029   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7030     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7031       // Both can be negated for free, check to see if at least one is cheaper
7032       // negated.
7033       if (LHSNeg == 2 || RHSNeg == 2)
7034         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7035                            GetNegatedExpression(N0, DAG, LegalOperations),
7036                            GetNegatedExpression(N1, DAG, LegalOperations));
7037     }
7038   }
7040   return SDValue();
7043 SDValue DAGCombiner::visitFREM(SDNode *N) {
7044   SDValue N0 = N->getOperand(0);
7045   SDValue N1 = N->getOperand(1);
7046   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7047   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7048   EVT VT = N->getValueType(0);
7050   // fold (frem c1, c2) -> fmod(c1,c2)
7051   if (N0CFP && N1CFP)
7052     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7054   return SDValue();
7057 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7058   SDValue N0 = N->getOperand(0);
7059   SDValue N1 = N->getOperand(1);
7060   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7061   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7062   EVT VT = N->getValueType(0);
7064   if (N0CFP && N1CFP)  // Constant fold
7065     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7067   if (N1CFP) {
7068     const APFloat& V = N1CFP->getValueAPF();
7069     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7070     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7071     if (!V.isNegative()) {
7072       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7073         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7074     } else {
7075       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7076         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7077                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7078     }
7079   }
7081   // copysign(fabs(x), y) -> copysign(x, y)
7082   // copysign(fneg(x), y) -> copysign(x, y)
7083   // copysign(copysign(x,z), y) -> copysign(x, y)
7084   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7085       N0.getOpcode() == ISD::FCOPYSIGN)
7086     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7087                        N0.getOperand(0), N1);
7089   // copysign(x, abs(y)) -> abs(x)
7090   if (N1.getOpcode() == ISD::FABS)
7091     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7093   // copysign(x, copysign(y,z)) -> copysign(x, z)
7094   if (N1.getOpcode() == ISD::FCOPYSIGN)
7095     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7096                        N0, N1.getOperand(1));
7098   // copysign(x, fp_extend(y)) -> copysign(x, y)
7099   // copysign(x, fp_round(y)) -> copysign(x, y)
7100   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7101     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7102                        N0, N1.getOperand(0));
7104   return SDValue();
7107 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7108   SDValue N0 = N->getOperand(0);
7109   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7110   EVT VT = N->getValueType(0);
7111   EVT OpVT = N0.getValueType();
7113   // fold (sint_to_fp c1) -> c1fp
7114   if (N0C &&
7115       // ...but only if the target supports immediate floating-point values
7116       (!LegalOperations ||
7117        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7118     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7120   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7121   // but UINT_TO_FP is legal on this target, try to convert.
7122   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7123       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7124     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7125     if (DAG.SignBitIsZero(N0))
7126       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7127   }
7129   // The next optimizations are desirable only if SELECT_CC can be lowered.
7130   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7131     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7132     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7133         !VT.isVector() &&
7134         (!LegalOperations ||
7135          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7136       SDValue Ops[] =
7137         { N0.getOperand(0), N0.getOperand(1),
7138           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7139           N0.getOperand(2) };
7140       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7141     }
7143     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7144     //      (select_cc x, y, 1.0, 0.0,, cc)
7145     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7146         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7147         (!LegalOperations ||
7148          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7149       SDValue Ops[] =
7150         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7151           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7152           N0.getOperand(0).getOperand(2) };
7153       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7154     }
7155   }
7157   return SDValue();
7160 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7161   SDValue N0 = N->getOperand(0);
7162   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7163   EVT VT = N->getValueType(0);
7164   EVT OpVT = N0.getValueType();
7166   // fold (uint_to_fp c1) -> c1fp
7167   if (N0C &&
7168       // ...but only if the target supports immediate floating-point values
7169       (!LegalOperations ||
7170        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7171     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7173   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7174   // but SINT_TO_FP is legal on this target, try to convert.
7175   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7176       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7177     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7178     if (DAG.SignBitIsZero(N0))
7179       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7180   }
7182   // The next optimizations are desirable only if SELECT_CC can be lowered.
7183   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7184     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7186     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7187         (!LegalOperations ||
7188          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7189       SDValue Ops[] =
7190         { N0.getOperand(0), N0.getOperand(1),
7191           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7192           N0.getOperand(2) };
7193       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7194     }
7195   }
7197   return SDValue();
7200 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7201   SDValue N0 = N->getOperand(0);
7202   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7203   EVT VT = N->getValueType(0);
7205   // fold (fp_to_sint c1fp) -> c1
7206   if (N0CFP)
7207     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7209   return SDValue();
7212 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7213   SDValue N0 = N->getOperand(0);
7214   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7215   EVT VT = N->getValueType(0);
7217   // fold (fp_to_uint c1fp) -> c1
7218   if (N0CFP)
7219     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7221   return SDValue();
7224 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7225   SDValue N0 = N->getOperand(0);
7226   SDValue N1 = N->getOperand(1);
7227   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7228   EVT VT = N->getValueType(0);
7230   // fold (fp_round c1fp) -> c1fp
7231   if (N0CFP)
7232     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7234   // fold (fp_round (fp_extend x)) -> x
7235   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7236     return N0.getOperand(0);
7238   // fold (fp_round (fp_round x)) -> (fp_round x)
7239   if (N0.getOpcode() == ISD::FP_ROUND) {
7240     // This is a value preserving truncation if both round's are.
7241     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7242                    N0.getNode()->getConstantOperandVal(1) == 1;
7243     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7244                        DAG.getIntPtrConstant(IsTrunc));
7245   }
7247   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7248   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7249     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7250                               N0.getOperand(0), N1);
7251     AddToWorklist(Tmp.getNode());
7252     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7253                        Tmp, N0.getOperand(1));
7254   }
7256   return SDValue();
7259 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7260   SDValue N0 = N->getOperand(0);
7261   EVT VT = N->getValueType(0);
7262   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7263   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7265   // fold (fp_round_inreg c1fp) -> c1fp
7266   if (N0CFP && isTypeLegal(EVT)) {
7267     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7268     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7269   }
7271   return SDValue();
7274 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7275   SDValue N0 = N->getOperand(0);
7276   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7277   EVT VT = N->getValueType(0);
7279   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7280   if (N->hasOneUse() &&
7281       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7282     return SDValue();
7284   // fold (fp_extend c1fp) -> c1fp
7285   if (N0CFP)
7286     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7288   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7289   // value of X.
7290   if (N0.getOpcode() == ISD::FP_ROUND
7291       && N0.getNode()->getConstantOperandVal(1) == 1) {
7292     SDValue In = N0.getOperand(0);
7293     if (In.getValueType() == VT) return In;
7294     if (VT.bitsLT(In.getValueType()))
7295       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7296                          In, N0.getOperand(1));
7297     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7298   }
7300   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7301   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7302        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7303     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7304     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7305                                      LN0->getChain(),
7306                                      LN0->getBasePtr(), N0.getValueType(),
7307                                      LN0->getMemOperand());
7308     CombineTo(N, ExtLoad);
7309     CombineTo(N0.getNode(),
7310               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7311                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7312               ExtLoad.getValue(1));
7313     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7314   }
7316   return SDValue();
7319 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7320   SDValue N0 = N->getOperand(0);
7321   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7322   EVT VT = N->getValueType(0);
7324   // fold (fceil c1) -> fceil(c1)
7325   if (N0CFP)
7326     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7328   return SDValue();
7331 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7332   SDValue N0 = N->getOperand(0);
7333   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7334   EVT VT = N->getValueType(0);
7336   // fold (ftrunc c1) -> ftrunc(c1)
7337   if (N0CFP)
7338     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7340   return SDValue();
7343 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7344   SDValue N0 = N->getOperand(0);
7345   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7346   EVT VT = N->getValueType(0);
7348   // fold (ffloor c1) -> ffloor(c1)
7349   if (N0CFP)
7350     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7352   return SDValue();
7355 // FIXME: FNEG and FABS have a lot in common; refactor.
7356 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7357   SDValue N0 = N->getOperand(0);
7358   EVT VT = N->getValueType(0);
7360   if (VT.isVector()) {
7361     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7362     if (FoldedVOp.getNode()) return FoldedVOp;
7363   }
7365   // Constant fold FNEG.
7366   if (isa<ConstantFPSDNode>(N0))
7367     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7369   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7370                          &DAG.getTarget().Options))
7371     return GetNegatedExpression(N0, DAG, LegalOperations);
7373   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7374   // constant pool values.
7375   if (!TLI.isFNegFree(VT) &&
7376       N0.getOpcode() == ISD::BITCAST &&
7377       N0.getNode()->hasOneUse()) {
7378     SDValue Int = N0.getOperand(0);
7379     EVT IntVT = Int.getValueType();
7380     if (IntVT.isInteger() && !IntVT.isVector()) {
7381       APInt SignMask;
7382       if (N0.getValueType().isVector()) {
7383         // For a vector, get a mask such as 0x80... per scalar element
7384         // and splat it.
7385         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7386         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7387       } else {
7388         // For a scalar, just generate 0x80...
7389         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7390       }
7391       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7392                         DAG.getConstant(SignMask, IntVT));
7393       AddToWorklist(Int.getNode());
7394       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7395     }
7396   }
7398   // (fneg (fmul c, x)) -> (fmul -c, x)
7399   if (N0.getOpcode() == ISD::FMUL) {
7400     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7401     if (CFP1) {
7402       APFloat CVal = CFP1->getValueAPF();
7403       CVal.changeSign();
7404       if (Level >= AfterLegalizeDAG &&
7405           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7406            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7407         return DAG.getNode(
7408             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7409             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7410     }
7411   }
7413   return SDValue();
7416 SDValue DAGCombiner::visitFABS(SDNode *N) {
7417   SDValue N0 = N->getOperand(0);
7418   EVT VT = N->getValueType(0);
7420   if (VT.isVector()) {
7421     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7422     if (FoldedVOp.getNode()) return FoldedVOp;
7423   }
7425   // fold (fabs c1) -> fabs(c1)
7426   if (isa<ConstantFPSDNode>(N0))
7427     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7428   
7429   // fold (fabs (fabs x)) -> (fabs x)
7430   if (N0.getOpcode() == ISD::FABS)
7431     return N->getOperand(0);
7433   // fold (fabs (fneg x)) -> (fabs x)
7434   // fold (fabs (fcopysign x, y)) -> (fabs x)
7435   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7436     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7438   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7439   // constant pool values.
7440   if (!TLI.isFAbsFree(VT) &&
7441       N0.getOpcode() == ISD::BITCAST &&
7442       N0.getNode()->hasOneUse()) {
7443     SDValue Int = N0.getOperand(0);
7444     EVT IntVT = Int.getValueType();
7445     if (IntVT.isInteger() && !IntVT.isVector()) {
7446       APInt SignMask;
7447       if (N0.getValueType().isVector()) {
7448         // For a vector, get a mask such as 0x7f... per scalar element
7449         // and splat it.
7450         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7451         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7452       } else {
7453         // For a scalar, just generate 0x7f...
7454         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7455       }
7456       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7457                         DAG.getConstant(SignMask, IntVT));
7458       AddToWorklist(Int.getNode());
7459       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7460     }
7461   }
7463   return SDValue();
7466 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7467   SDValue Chain = N->getOperand(0);
7468   SDValue N1 = N->getOperand(1);
7469   SDValue N2 = N->getOperand(2);
7471   // If N is a constant we could fold this into a fallthrough or unconditional
7472   // branch. However that doesn't happen very often in normal code, because
7473   // Instcombine/SimplifyCFG should have handled the available opportunities.
7474   // If we did this folding here, it would be necessary to update the
7475   // MachineBasicBlock CFG, which is awkward.
7477   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7478   // on the target.
7479   if (N1.getOpcode() == ISD::SETCC &&
7480       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7481                                    N1.getOperand(0).getValueType())) {
7482     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7483                        Chain, N1.getOperand(2),
7484                        N1.getOperand(0), N1.getOperand(1), N2);
7485   }
7487   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7488       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7489        (N1.getOperand(0).hasOneUse() &&
7490         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7491     SDNode *Trunc = nullptr;
7492     if (N1.getOpcode() == ISD::TRUNCATE) {
7493       // Look pass the truncate.
7494       Trunc = N1.getNode();
7495       N1 = N1.getOperand(0);
7496     }
7498     // Match this pattern so that we can generate simpler code:
7499     //
7500     //   %a = ...
7501     //   %b = and i32 %a, 2
7502     //   %c = srl i32 %b, 1
7503     //   brcond i32 %c ...
7504     //
7505     // into
7506     //
7507     //   %a = ...
7508     //   %b = and i32 %a, 2
7509     //   %c = setcc eq %b, 0
7510     //   brcond %c ...
7511     //
7512     // This applies only when the AND constant value has one bit set and the
7513     // SRL constant is equal to the log2 of the AND constant. The back-end is
7514     // smart enough to convert the result into a TEST/JMP sequence.
7515     SDValue Op0 = N1.getOperand(0);
7516     SDValue Op1 = N1.getOperand(1);
7518     if (Op0.getOpcode() == ISD::AND &&
7519         Op1.getOpcode() == ISD::Constant) {
7520       SDValue AndOp1 = Op0.getOperand(1);
7522       if (AndOp1.getOpcode() == ISD::Constant) {
7523         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7525         if (AndConst.isPowerOf2() &&
7526             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7527           SDValue SetCC =
7528             DAG.getSetCC(SDLoc(N),
7529                          getSetCCResultType(Op0.getValueType()),
7530                          Op0, DAG.getConstant(0, Op0.getValueType()),
7531                          ISD::SETNE);
7533           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7534                                           MVT::Other, Chain, SetCC, N2);
7535           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7536           // will convert it back to (X & C1) >> C2.
7537           CombineTo(N, NewBRCond, false);
7538           // Truncate is dead.
7539           if (Trunc)
7540             deleteAndRecombine(Trunc);
7541           // Replace the uses of SRL with SETCC
7542           WorklistRemover DeadNodes(*this);
7543           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7544           deleteAndRecombine(N1.getNode());
7545           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7546         }
7547       }
7548     }
7550     if (Trunc)
7551       // Restore N1 if the above transformation doesn't match.
7552       N1 = N->getOperand(1);
7553   }
7555   // Transform br(xor(x, y)) -> br(x != y)
7556   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7557   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7558     SDNode *TheXor = N1.getNode();
7559     SDValue Op0 = TheXor->getOperand(0);
7560     SDValue Op1 = TheXor->getOperand(1);
7561     if (Op0.getOpcode() == Op1.getOpcode()) {
7562       // Avoid missing important xor optimizations.
7563       SDValue Tmp = visitXOR(TheXor);
7564       if (Tmp.getNode()) {
7565         if (Tmp.getNode() != TheXor) {
7566           DEBUG(dbgs() << "\nReplacing.8 ";
7567                 TheXor->dump(&DAG);
7568                 dbgs() << "\nWith: ";
7569                 Tmp.getNode()->dump(&DAG);
7570                 dbgs() << '\n');
7571           WorklistRemover DeadNodes(*this);
7572           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7573           deleteAndRecombine(TheXor);
7574           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7575                              MVT::Other, Chain, Tmp, N2);
7576         }
7578         // visitXOR has changed XOR's operands or replaced the XOR completely,
7579         // bail out.
7580         return SDValue(N, 0);
7581       }
7582     }
7584     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7585       bool Equal = false;
7586       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7587         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7588             Op0.getOpcode() == ISD::XOR) {
7589           TheXor = Op0.getNode();
7590           Equal = true;
7591         }
7593       EVT SetCCVT = N1.getValueType();
7594       if (LegalTypes)
7595         SetCCVT = getSetCCResultType(SetCCVT);
7596       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7597                                    SetCCVT,
7598                                    Op0, Op1,
7599                                    Equal ? ISD::SETEQ : ISD::SETNE);
7600       // Replace the uses of XOR with SETCC
7601       WorklistRemover DeadNodes(*this);
7602       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7603       deleteAndRecombine(N1.getNode());
7604       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7605                          MVT::Other, Chain, SetCC, N2);
7606     }
7607   }
7609   return SDValue();
7612 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7613 //
7614 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7615   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7616   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7618   // If N is a constant we could fold this into a fallthrough or unconditional
7619   // branch. However that doesn't happen very often in normal code, because
7620   // Instcombine/SimplifyCFG should have handled the available opportunities.
7621   // If we did this folding here, it would be necessary to update the
7622   // MachineBasicBlock CFG, which is awkward.
7624   // Use SimplifySetCC to simplify SETCC's.
7625   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7626                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7627                                false);
7628   if (Simp.getNode()) AddToWorklist(Simp.getNode());
7630   // fold to a simpler setcc
7631   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7632     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7633                        N->getOperand(0), Simp.getOperand(2),
7634                        Simp.getOperand(0), Simp.getOperand(1),
7635                        N->getOperand(4));
7637   return SDValue();
7640 /// Return true if 'Use' is a load or a store that uses N as its base pointer
7641 /// and that N may be folded in the load / store addressing mode.
7642 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7643                                     SelectionDAG &DAG,
7644                                     const TargetLowering &TLI) {
7645   EVT VT;
7646   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7647     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7648       return false;
7649     VT = Use->getValueType(0);
7650   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7651     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7652       return false;
7653     VT = ST->getValue().getValueType();
7654   } else
7655     return false;
7657   TargetLowering::AddrMode AM;
7658   if (N->getOpcode() == ISD::ADD) {
7659     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7660     if (Offset)
7661       // [reg +/- imm]
7662       AM.BaseOffs = Offset->getSExtValue();
7663     else
7664       // [reg +/- reg]
7665       AM.Scale = 1;
7666   } else if (N->getOpcode() == ISD::SUB) {
7667     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7668     if (Offset)
7669       // [reg +/- imm]
7670       AM.BaseOffs = -Offset->getSExtValue();
7671     else
7672       // [reg +/- reg]
7673       AM.Scale = 1;
7674   } else
7675     return false;
7677   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7680 /// Try turning a load/store into a pre-indexed load/store when the base
7681 /// pointer is an add or subtract and it has other uses besides the load/store.
7682 /// After the transformation, the new indexed load/store has effectively folded
7683 /// the add/subtract in and all of its other uses are redirected to the
7684 /// new load/store.
7685 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7686   if (Level < AfterLegalizeDAG)
7687     return false;
7689   bool isLoad = true;
7690   SDValue Ptr;
7691   EVT VT;
7692   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7693     if (LD->isIndexed())
7694       return false;
7695     VT = LD->getMemoryVT();
7696     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7697         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7698       return false;
7699     Ptr = LD->getBasePtr();
7700   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7701     if (ST->isIndexed())
7702       return false;
7703     VT = ST->getMemoryVT();
7704     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7705         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7706       return false;
7707     Ptr = ST->getBasePtr();
7708     isLoad = false;
7709   } else {
7710     return false;
7711   }
7713   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7714   // out.  There is no reason to make this a preinc/predec.
7715   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7716       Ptr.getNode()->hasOneUse())
7717     return false;
7719   // Ask the target to do addressing mode selection.
7720   SDValue BasePtr;
7721   SDValue Offset;
7722   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7723   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7724     return false;
7726   // Backends without true r+i pre-indexed forms may need to pass a
7727   // constant base with a variable offset so that constant coercion
7728   // will work with the patterns in canonical form.
7729   bool Swapped = false;
7730   if (isa<ConstantSDNode>(BasePtr)) {
7731     std::swap(BasePtr, Offset);
7732     Swapped = true;
7733   }
7735   // Don't create a indexed load / store with zero offset.
7736   if (isa<ConstantSDNode>(Offset) &&
7737       cast<ConstantSDNode>(Offset)->isNullValue())
7738     return false;
7740   // Try turning it into a pre-indexed load / store except when:
7741   // 1) The new base ptr is a frame index.
7742   // 2) If N is a store and the new base ptr is either the same as or is a
7743   //    predecessor of the value being stored.
7744   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7745   //    that would create a cycle.
7746   // 4) All uses are load / store ops that use it as old base ptr.
7748   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7749   // (plus the implicit offset) to a register to preinc anyway.
7750   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7751     return false;
7753   // Check #2.
7754   if (!isLoad) {
7755     SDValue Val = cast<StoreSDNode>(N)->getValue();
7756     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7757       return false;
7758   }
7760   // If the offset is a constant, there may be other adds of constants that
7761   // can be folded with this one. We should do this to avoid having to keep
7762   // a copy of the original base pointer.
7763   SmallVector<SDNode *, 16> OtherUses;
7764   if (isa<ConstantSDNode>(Offset))
7765     for (SDNode *Use : BasePtr.getNode()->uses()) {
7766       if (Use == Ptr.getNode())
7767         continue;
7769       if (Use->isPredecessorOf(N))
7770         continue;
7772       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7773         OtherUses.clear();
7774         break;
7775       }
7777       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7778       if (Op1.getNode() == BasePtr.getNode())
7779         std::swap(Op0, Op1);
7780       assert(Op0.getNode() == BasePtr.getNode() &&
7781              "Use of ADD/SUB but not an operand");
7783       if (!isa<ConstantSDNode>(Op1)) {
7784         OtherUses.clear();
7785         break;
7786       }
7788       // FIXME: In some cases, we can be smarter about this.
7789       if (Op1.getValueType() != Offset.getValueType()) {
7790         OtherUses.clear();
7791         break;
7792       }
7794       OtherUses.push_back(Use);
7795     }
7797   if (Swapped)
7798     std::swap(BasePtr, Offset);
7800   // Now check for #3 and #4.
7801   bool RealUse = false;
7803   // Caches for hasPredecessorHelper
7804   SmallPtrSet<const SDNode *, 32> Visited;
7805   SmallVector<const SDNode *, 16> Worklist;
7807   for (SDNode *Use : Ptr.getNode()->uses()) {
7808     if (Use == N)
7809       continue;
7810     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7811       return false;
7813     // If Ptr may be folded in addressing mode of other use, then it's
7814     // not profitable to do this transformation.
7815     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7816       RealUse = true;
7817   }
7819   if (!RealUse)
7820     return false;
7822   SDValue Result;
7823   if (isLoad)
7824     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7825                                 BasePtr, Offset, AM);
7826   else
7827     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7828                                  BasePtr, Offset, AM);
7829   ++PreIndexedNodes;
7830   ++NodesCombined;
7831   DEBUG(dbgs() << "\nReplacing.4 ";
7832         N->dump(&DAG);
7833         dbgs() << "\nWith: ";
7834         Result.getNode()->dump(&DAG);
7835         dbgs() << '\n');
7836   WorklistRemover DeadNodes(*this);
7837   if (isLoad) {
7838     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7839     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7840   } else {
7841     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7842   }
7844   // Finally, since the node is now dead, remove it from the graph.
7845   deleteAndRecombine(N);
7847   if (Swapped)
7848     std::swap(BasePtr, Offset);
7850   // Replace other uses of BasePtr that can be updated to use Ptr
7851   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7852     unsigned OffsetIdx = 1;
7853     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7854       OffsetIdx = 0;
7855     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7856            BasePtr.getNode() && "Expected BasePtr operand");
7858     // We need to replace ptr0 in the following expression:
7859     //   x0 * offset0 + y0 * ptr0 = t0
7860     // knowing that
7861     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7862     //
7863     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7864     // indexed load/store and the expresion that needs to be re-written.
7865     //
7866     // Therefore, we have:
7867     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7869     ConstantSDNode *CN =
7870       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7871     int X0, X1, Y0, Y1;
7872     APInt Offset0 = CN->getAPIntValue();
7873     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7875     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7876     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7877     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7878     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7880     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7882     APInt CNV = Offset0;
7883     if (X0 < 0) CNV = -CNV;
7884     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7885     else CNV = CNV - Offset1;
7887     // We can now generate the new expression.
7888     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7889     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7891     SDValue NewUse = DAG.getNode(Opcode,
7892                                  SDLoc(OtherUses[i]),
7893                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7894     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7895     deleteAndRecombine(OtherUses[i]);
7896   }
7898   // Replace the uses of Ptr with uses of the updated base value.
7899   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7900   deleteAndRecombine(Ptr.getNode());
7902   return true;
7905 /// Try to combine a load/store with a add/sub of the base pointer node into a
7906 /// post-indexed load/store. The transformation folded the add/subtract into the
7907 /// new indexed load/store effectively and all of its uses are redirected to the
7908 /// new load/store.
7909 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7910   if (Level < AfterLegalizeDAG)
7911     return false;
7913   bool isLoad = true;
7914   SDValue Ptr;
7915   EVT VT;
7916   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7917     if (LD->isIndexed())
7918       return false;
7919     VT = LD->getMemoryVT();
7920     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7921         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7922       return false;
7923     Ptr = LD->getBasePtr();
7924   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7925     if (ST->isIndexed())
7926       return false;
7927     VT = ST->getMemoryVT();
7928     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7929         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7930       return false;
7931     Ptr = ST->getBasePtr();
7932     isLoad = false;
7933   } else {
7934     return false;
7935   }
7937   if (Ptr.getNode()->hasOneUse())
7938     return false;
7940   for (SDNode *Op : Ptr.getNode()->uses()) {
7941     if (Op == N ||
7942         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7943       continue;
7945     SDValue BasePtr;
7946     SDValue Offset;
7947     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7948     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7949       // Don't create a indexed load / store with zero offset.
7950       if (isa<ConstantSDNode>(Offset) &&
7951           cast<ConstantSDNode>(Offset)->isNullValue())
7952         continue;
7954       // Try turning it into a post-indexed load / store except when
7955       // 1) All uses are load / store ops that use it as base ptr (and
7956       //    it may be folded as addressing mmode).
7957       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7958       //    nor a successor of N. Otherwise, if Op is folded that would
7959       //    create a cycle.
7961       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7962         continue;
7964       // Check for #1.
7965       bool TryNext = false;
7966       for (SDNode *Use : BasePtr.getNode()->uses()) {
7967         if (Use == Ptr.getNode())
7968           continue;
7970         // If all the uses are load / store addresses, then don't do the
7971         // transformation.
7972         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7973           bool RealUse = false;
7974           for (SDNode *UseUse : Use->uses()) {
7975             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7976               RealUse = true;
7977           }
7979           if (!RealUse) {
7980             TryNext = true;
7981             break;
7982           }
7983         }
7984       }
7986       if (TryNext)
7987         continue;
7989       // Check for #2
7990       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7991         SDValue Result = isLoad
7992           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7993                                BasePtr, Offset, AM)
7994           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7995                                 BasePtr, Offset, AM);
7996         ++PostIndexedNodes;
7997         ++NodesCombined;
7998         DEBUG(dbgs() << "\nReplacing.5 ";
7999               N->dump(&DAG);
8000               dbgs() << "\nWith: ";
8001               Result.getNode()->dump(&DAG);
8002               dbgs() << '\n');
8003         WorklistRemover DeadNodes(*this);
8004         if (isLoad) {
8005           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8006           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8007         } else {
8008           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8009         }
8011         // Finally, since the node is now dead, remove it from the graph.
8012         deleteAndRecombine(N);
8014         // Replace the uses of Use with uses of the updated base value.
8015         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8016                                       Result.getValue(isLoad ? 1 : 0));
8017         deleteAndRecombine(Op);
8018         return true;
8019       }
8020     }
8021   }
8023   return false;
8026 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8027 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8028   ISD::MemIndexedMode AM = LD->getAddressingMode();
8029   assert(AM != ISD::UNINDEXED);
8030   SDValue BP = LD->getOperand(1);
8031   SDValue Inc = LD->getOperand(2);
8032   assert(Inc.getOpcode() != ISD::TargetConstant &&
8033          "Cannot split out indexing using target constants");
8034   unsigned Opc =
8035       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8036   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8039 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8040   LoadSDNode *LD  = cast<LoadSDNode>(N);
8041   SDValue Chain = LD->getChain();
8042   SDValue Ptr   = LD->getBasePtr();
8044   // If load is not volatile and there are no uses of the loaded value (and
8045   // the updated indexed value in case of indexed loads), change uses of the
8046   // chain value into uses of the chain input (i.e. delete the dead load).
8047   if (!LD->isVolatile()) {
8048     if (N->getValueType(1) == MVT::Other) {
8049       // Unindexed loads.
8050       if (!N->hasAnyUseOfValue(0)) {
8051         // It's not safe to use the two value CombineTo variant here. e.g.
8052         // v1, chain2 = load chain1, loc
8053         // v2, chain3 = load chain2, loc
8054         // v3         = add v2, c
8055         // Now we replace use of chain2 with chain1.  This makes the second load
8056         // isomorphic to the one we are deleting, and thus makes this load live.
8057         DEBUG(dbgs() << "\nReplacing.6 ";
8058               N->dump(&DAG);
8059               dbgs() << "\nWith chain: ";
8060               Chain.getNode()->dump(&DAG);
8061               dbgs() << "\n");
8062         WorklistRemover DeadNodes(*this);
8063         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8065         if (N->use_empty())
8066           deleteAndRecombine(N);
8068         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8069       }
8070     } else {
8071       // Indexed loads.
8072       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8074       // If this load has an TargetConstant offset, then we cannot split the
8075       // indexing into an add/sub directly (that TargetConstant may not be
8076       // valid for a different type of node).
8077       bool HasTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant;
8079       if (!N->hasAnyUseOfValue(0) &&
8080           ((MaySplitLoadIndex && !HasTCInc) || !N->hasAnyUseOfValue(1))) {
8081         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8082         SDValue Index;
8083         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasTCInc) {
8084           Index = SplitIndexingFromLoad(LD);
8085           // Try to fold the base pointer arithmetic into subsequent loads and
8086           // stores.
8087           AddUsersToWorklist(N);
8088         } else
8089           Index = DAG.getUNDEF(N->getValueType(1));
8090         DEBUG(dbgs() << "\nReplacing.7 ";
8091               N->dump(&DAG);
8092               dbgs() << "\nWith: ";
8093               Undef.getNode()->dump(&DAG);
8094               dbgs() << " and 2 other values\n");
8095         WorklistRemover DeadNodes(*this);
8096         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8097         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8098         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8099         deleteAndRecombine(N);
8100         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8101       }
8102     }
8103   }
8105   // If this load is directly stored, replace the load value with the stored
8106   // value.
8107   // TODO: Handle store large -> read small portion.
8108   // TODO: Handle TRUNCSTORE/LOADEXT
8109   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8110     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8111       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8112       if (PrevST->getBasePtr() == Ptr &&
8113           PrevST->getValue().getValueType() == N->getValueType(0))
8114       return CombineTo(N, Chain.getOperand(1), Chain);
8115     }
8116   }
8118   // Try to infer better alignment information than the load already has.
8119   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8120     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8121       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8122         SDValue NewLoad =
8123                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8124                               LD->getValueType(0),
8125                               Chain, Ptr, LD->getPointerInfo(),
8126                               LD->getMemoryVT(),
8127                               LD->isVolatile(), LD->isNonTemporal(),
8128                               LD->isInvariant(), Align, LD->getAAInfo());
8129         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8130       }
8131     }
8132   }
8134   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8135     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8136 #ifndef NDEBUG
8137   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8138       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8139     UseAA = false;
8140 #endif
8141   if (UseAA && LD->isUnindexed()) {
8142     // Walk up chain skipping non-aliasing memory nodes.
8143     SDValue BetterChain = FindBetterChain(N, Chain);
8145     // If there is a better chain.
8146     if (Chain != BetterChain) {
8147       SDValue ReplLoad;
8149       // Replace the chain to void dependency.
8150       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8151         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8152                                BetterChain, Ptr, LD->getMemOperand());
8153       } else {
8154         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8155                                   LD->getValueType(0),
8156                                   BetterChain, Ptr, LD->getMemoryVT(),
8157                                   LD->getMemOperand());
8158       }
8160       // Create token factor to keep old chain connected.
8161       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8162                                   MVT::Other, Chain, ReplLoad.getValue(1));
8164       // Make sure the new and old chains are cleaned up.
8165       AddToWorklist(Token.getNode());
8167       // Replace uses with load result and token factor. Don't add users
8168       // to work list.
8169       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8170     }
8171   }
8173   // Try transforming N to an indexed load.
8174   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8175     return SDValue(N, 0);
8177   // Try to slice up N to more direct loads if the slices are mapped to
8178   // different register banks or pairing can take place.
8179   if (SliceUpLoad(N))
8180     return SDValue(N, 0);
8182   return SDValue();
8185 namespace {
8186 /// \brief Helper structure used to slice a load in smaller loads.
8187 /// Basically a slice is obtained from the following sequence:
8188 /// Origin = load Ty1, Base
8189 /// Shift = srl Ty1 Origin, CstTy Amount
8190 /// Inst = trunc Shift to Ty2
8191 ///
8192 /// Then, it will be rewriten into:
8193 /// Slice = load SliceTy, Base + SliceOffset
8194 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8195 ///
8196 /// SliceTy is deduced from the number of bits that are actually used to
8197 /// build Inst.
8198 struct LoadedSlice {
8199   /// \brief Helper structure used to compute the cost of a slice.
8200   struct Cost {
8201     /// Are we optimizing for code size.
8202     bool ForCodeSize;
8203     /// Various cost.
8204     unsigned Loads;
8205     unsigned Truncates;
8206     unsigned CrossRegisterBanksCopies;
8207     unsigned ZExts;
8208     unsigned Shift;
8210     Cost(bool ForCodeSize = false)
8211         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8212           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8214     /// \brief Get the cost of one isolated slice.
8215     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8216         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8217           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8218       EVT TruncType = LS.Inst->getValueType(0);
8219       EVT LoadedType = LS.getLoadedType();
8220       if (TruncType != LoadedType &&
8221           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8222         ZExts = 1;
8223     }
8225     /// \brief Account for slicing gain in the current cost.
8226     /// Slicing provide a few gains like removing a shift or a
8227     /// truncate. This method allows to grow the cost of the original
8228     /// load with the gain from this slice.
8229     void addSliceGain(const LoadedSlice &LS) {
8230       // Each slice saves a truncate.
8231       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8232       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8233                               LS.Inst->getOperand(0).getValueType()))
8234         ++Truncates;
8235       // If there is a shift amount, this slice gets rid of it.
8236       if (LS.Shift)
8237         ++Shift;
8238       // If this slice can merge a cross register bank copy, account for it.
8239       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8240         ++CrossRegisterBanksCopies;
8241     }
8243     Cost &operator+=(const Cost &RHS) {
8244       Loads += RHS.Loads;
8245       Truncates += RHS.Truncates;
8246       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8247       ZExts += RHS.ZExts;
8248       Shift += RHS.Shift;
8249       return *this;
8250     }
8252     bool operator==(const Cost &RHS) const {
8253       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8254              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8255              ZExts == RHS.ZExts && Shift == RHS.Shift;
8256     }
8258     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8260     bool operator<(const Cost &RHS) const {
8261       // Assume cross register banks copies are as expensive as loads.
8262       // FIXME: Do we want some more target hooks?
8263       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8264       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8265       // Unless we are optimizing for code size, consider the
8266       // expensive operation first.
8267       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8268         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8269       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8270              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8271     }
8273     bool operator>(const Cost &RHS) const { return RHS < *this; }
8275     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8277     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8278   };
8279   // The last instruction that represent the slice. This should be a
8280   // truncate instruction.
8281   SDNode *Inst;
8282   // The original load instruction.
8283   LoadSDNode *Origin;
8284   // The right shift amount in bits from the original load.
8285   unsigned Shift;
8286   // The DAG from which Origin came from.
8287   // This is used to get some contextual information about legal types, etc.
8288   SelectionDAG *DAG;
8290   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8291               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8292       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8294   LoadedSlice(const LoadedSlice &LS)
8295       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8297   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8298   /// \return Result is \p BitWidth and has used bits set to 1 and
8299   ///         not used bits set to 0.
8300   APInt getUsedBits() const {
8301     // Reproduce the trunc(lshr) sequence:
8302     // - Start from the truncated value.
8303     // - Zero extend to the desired bit width.
8304     // - Shift left.
8305     assert(Origin && "No original load to compare against.");
8306     unsigned BitWidth = Origin->getValueSizeInBits(0);
8307     assert(Inst && "This slice is not bound to an instruction");
8308     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8309            "Extracted slice is bigger than the whole type!");
8310     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8311     UsedBits.setAllBits();
8312     UsedBits = UsedBits.zext(BitWidth);
8313     UsedBits <<= Shift;
8314     return UsedBits;
8315   }
8317   /// \brief Get the size of the slice to be loaded in bytes.
8318   unsigned getLoadedSize() const {
8319     unsigned SliceSize = getUsedBits().countPopulation();
8320     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8321     return SliceSize / 8;
8322   }
8324   /// \brief Get the type that will be loaded for this slice.
8325   /// Note: This may not be the final type for the slice.
8326   EVT getLoadedType() const {
8327     assert(DAG && "Missing context");
8328     LLVMContext &Ctxt = *DAG->getContext();
8329     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8330   }
8332   /// \brief Get the alignment of the load used for this slice.
8333   unsigned getAlignment() const {
8334     unsigned Alignment = Origin->getAlignment();
8335     unsigned Offset = getOffsetFromBase();
8336     if (Offset != 0)
8337       Alignment = MinAlign(Alignment, Alignment + Offset);
8338     return Alignment;
8339   }
8341   /// \brief Check if this slice can be rewritten with legal operations.
8342   bool isLegal() const {
8343     // An invalid slice is not legal.
8344     if (!Origin || !Inst || !DAG)
8345       return false;
8347     // Offsets are for indexed load only, we do not handle that.
8348     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8349       return false;
8351     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8353     // Check that the type is legal.
8354     EVT SliceType = getLoadedType();
8355     if (!TLI.isTypeLegal(SliceType))
8356       return false;
8358     // Check that the load is legal for this type.
8359     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8360       return false;
8362     // Check that the offset can be computed.
8363     // 1. Check its type.
8364     EVT PtrType = Origin->getBasePtr().getValueType();
8365     if (PtrType == MVT::Untyped || PtrType.isExtended())
8366       return false;
8368     // 2. Check that it fits in the immediate.
8369     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8370       return false;
8372     // 3. Check that the computation is legal.
8373     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8374       return false;
8376     // Check that the zext is legal if it needs one.
8377     EVT TruncateType = Inst->getValueType(0);
8378     if (TruncateType != SliceType &&
8379         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8380       return false;
8382     return true;
8383   }
8385   /// \brief Get the offset in bytes of this slice in the original chunk of
8386   /// bits.
8387   /// \pre DAG != nullptr.
8388   uint64_t getOffsetFromBase() const {
8389     assert(DAG && "Missing context.");
8390     bool IsBigEndian =
8391         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8392     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8393     uint64_t Offset = Shift / 8;
8394     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8395     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8396            "The size of the original loaded type is not a multiple of a"
8397            " byte.");
8398     // If Offset is bigger than TySizeInBytes, it means we are loading all
8399     // zeros. This should have been optimized before in the process.
8400     assert(TySizeInBytes > Offset &&
8401            "Invalid shift amount for given loaded size");
8402     if (IsBigEndian)
8403       Offset = TySizeInBytes - Offset - getLoadedSize();
8404     return Offset;
8405   }
8407   /// \brief Generate the sequence of instructions to load the slice
8408   /// represented by this object and redirect the uses of this slice to
8409   /// this new sequence of instructions.
8410   /// \pre this->Inst && this->Origin are valid Instructions and this
8411   /// object passed the legal check: LoadedSlice::isLegal returned true.
8412   /// \return The last instruction of the sequence used to load the slice.
8413   SDValue loadSlice() const {
8414     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8415     const SDValue &OldBaseAddr = Origin->getBasePtr();
8416     SDValue BaseAddr = OldBaseAddr;
8417     // Get the offset in that chunk of bytes w.r.t. the endianess.
8418     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8419     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8420     if (Offset) {
8421       // BaseAddr = BaseAddr + Offset.
8422       EVT ArithType = BaseAddr.getValueType();
8423       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8424                               DAG->getConstant(Offset, ArithType));
8425     }
8427     // Create the type of the loaded slice according to its size.
8428     EVT SliceType = getLoadedType();
8430     // Create the load for the slice.
8431     SDValue LastInst = DAG->getLoad(
8432         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8433         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8434         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8435     // If the final type is not the same as the loaded type, this means that
8436     // we have to pad with zero. Create a zero extend for that.
8437     EVT FinalType = Inst->getValueType(0);
8438     if (SliceType != FinalType)
8439       LastInst =
8440           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8441     return LastInst;
8442   }
8444   /// \brief Check if this slice can be merged with an expensive cross register
8445   /// bank copy. E.g.,
8446   /// i = load i32
8447   /// f = bitcast i32 i to float
8448   bool canMergeExpensiveCrossRegisterBankCopy() const {
8449     if (!Inst || !Inst->hasOneUse())
8450       return false;
8451     SDNode *Use = *Inst->use_begin();
8452     if (Use->getOpcode() != ISD::BITCAST)
8453       return false;
8454     assert(DAG && "Missing context");
8455     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8456     EVT ResVT = Use->getValueType(0);
8457     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8458     const TargetRegisterClass *ArgRC =
8459         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8460     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8461       return false;
8463     // At this point, we know that we perform a cross-register-bank copy.
8464     // Check if it is expensive.
8465     const TargetRegisterInfo *TRI =
8466         TLI.getTargetMachine().getSubtargetImpl()->getRegisterInfo();
8467     // Assume bitcasts are cheap, unless both register classes do not
8468     // explicitly share a common sub class.
8469     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8470       return false;
8472     // Check if it will be merged with the load.
8473     // 1. Check the alignment constraint.
8474     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8475         ResVT.getTypeForEVT(*DAG->getContext()));
8477     if (RequiredAlignment > getAlignment())
8478       return false;
8480     // 2. Check that the load is a legal operation for that type.
8481     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8482       return false;
8484     // 3. Check that we do not have a zext in the way.
8485     if (Inst->getValueType(0) != getLoadedType())
8486       return false;
8488     return true;
8489   }
8490 };
8493 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8494 /// \p UsedBits looks like 0..0 1..1 0..0.
8495 static bool areUsedBitsDense(const APInt &UsedBits) {
8496   // If all the bits are one, this is dense!
8497   if (UsedBits.isAllOnesValue())
8498     return true;
8500   // Get rid of the unused bits on the right.
8501   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8502   // Get rid of the unused bits on the left.
8503   if (NarrowedUsedBits.countLeadingZeros())
8504     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8505   // Check that the chunk of bits is completely used.
8506   return NarrowedUsedBits.isAllOnesValue();
8509 /// \brief Check whether or not \p First and \p Second are next to each other
8510 /// in memory. This means that there is no hole between the bits loaded
8511 /// by \p First and the bits loaded by \p Second.
8512 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8513                                      const LoadedSlice &Second) {
8514   assert(First.Origin == Second.Origin && First.Origin &&
8515          "Unable to match different memory origins.");
8516   APInt UsedBits = First.getUsedBits();
8517   assert((UsedBits & Second.getUsedBits()) == 0 &&
8518          "Slices are not supposed to overlap.");
8519   UsedBits |= Second.getUsedBits();
8520   return areUsedBitsDense(UsedBits);
8523 /// \brief Adjust the \p GlobalLSCost according to the target
8524 /// paring capabilities and the layout of the slices.
8525 /// \pre \p GlobalLSCost should account for at least as many loads as
8526 /// there is in the slices in \p LoadedSlices.
8527 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8528                                  LoadedSlice::Cost &GlobalLSCost) {
8529   unsigned NumberOfSlices = LoadedSlices.size();
8530   // If there is less than 2 elements, no pairing is possible.
8531   if (NumberOfSlices < 2)
8532     return;
8534   // Sort the slices so that elements that are likely to be next to each
8535   // other in memory are next to each other in the list.
8536   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8537             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8538     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8539     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8540   });
8541   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8542   // First (resp. Second) is the first (resp. Second) potentially candidate
8543   // to be placed in a paired load.
8544   const LoadedSlice *First = nullptr;
8545   const LoadedSlice *Second = nullptr;
8546   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8547                 // Set the beginning of the pair.
8548                                                            First = Second) {
8550     Second = &LoadedSlices[CurrSlice];
8552     // If First is NULL, it means we start a new pair.
8553     // Get to the next slice.
8554     if (!First)
8555       continue;
8557     EVT LoadedType = First->getLoadedType();
8559     // If the types of the slices are different, we cannot pair them.
8560     if (LoadedType != Second->getLoadedType())
8561       continue;
8563     // Check if the target supplies paired loads for this type.
8564     unsigned RequiredAlignment = 0;
8565     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8566       // move to the next pair, this type is hopeless.
8567       Second = nullptr;
8568       continue;
8569     }
8570     // Check if we meet the alignment requirement.
8571     if (RequiredAlignment > First->getAlignment())
8572       continue;
8574     // Check that both loads are next to each other in memory.
8575     if (!areSlicesNextToEachOther(*First, *Second))
8576       continue;
8578     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8579     --GlobalLSCost.Loads;
8580     // Move to the next pair.
8581     Second = nullptr;
8582   }
8585 /// \brief Check the profitability of all involved LoadedSlice.
8586 /// Currently, it is considered profitable if there is exactly two
8587 /// involved slices (1) which are (2) next to each other in memory, and
8588 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8589 ///
8590 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8591 /// the elements themselves.
8592 ///
8593 /// FIXME: When the cost model will be mature enough, we can relax
8594 /// constraints (1) and (2).
8595 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8596                                 const APInt &UsedBits, bool ForCodeSize) {
8597   unsigned NumberOfSlices = LoadedSlices.size();
8598   if (StressLoadSlicing)
8599     return NumberOfSlices > 1;
8601   // Check (1).
8602   if (NumberOfSlices != 2)
8603     return false;
8605   // Check (2).
8606   if (!areUsedBitsDense(UsedBits))
8607     return false;
8609   // Check (3).
8610   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8611   // The original code has one big load.
8612   OrigCost.Loads = 1;
8613   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8614     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8615     // Accumulate the cost of all the slices.
8616     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8617     GlobalSlicingCost += SliceCost;
8619     // Account as cost in the original configuration the gain obtained
8620     // with the current slices.
8621     OrigCost.addSliceGain(LS);
8622   }
8624   // If the target supports paired load, adjust the cost accordingly.
8625   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8626   return OrigCost > GlobalSlicingCost;
8629 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8630 /// operations, split it in the various pieces being extracted.
8631 ///
8632 /// This sort of thing is introduced by SROA.
8633 /// This slicing takes care not to insert overlapping loads.
8634 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8635 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8636   if (Level < AfterLegalizeDAG)
8637     return false;
8639   LoadSDNode *LD = cast<LoadSDNode>(N);
8640   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8641       !LD->getValueType(0).isInteger())
8642     return false;
8644   // Keep track of already used bits to detect overlapping values.
8645   // In that case, we will just abort the transformation.
8646   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8648   SmallVector<LoadedSlice, 4> LoadedSlices;
8650   // Check if this load is used as several smaller chunks of bits.
8651   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8652   // of computation for each trunc.
8653   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8654        UI != UIEnd; ++UI) {
8655     // Skip the uses of the chain.
8656     if (UI.getUse().getResNo() != 0)
8657       continue;
8659     SDNode *User = *UI;
8660     unsigned Shift = 0;
8662     // Check if this is a trunc(lshr).
8663     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8664         isa<ConstantSDNode>(User->getOperand(1))) {
8665       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8666       User = *User->use_begin();
8667     }
8669     // At this point, User is a Truncate, iff we encountered, trunc or
8670     // trunc(lshr).
8671     if (User->getOpcode() != ISD::TRUNCATE)
8672       return false;
8674     // The width of the type must be a power of 2 and greater than 8-bits.
8675     // Otherwise the load cannot be represented in LLVM IR.
8676     // Moreover, if we shifted with a non-8-bits multiple, the slice
8677     // will be across several bytes. We do not support that.
8678     unsigned Width = User->getValueSizeInBits(0);
8679     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8680       return 0;
8682     // Build the slice for this chain of computations.
8683     LoadedSlice LS(User, LD, Shift, &DAG);
8684     APInt CurrentUsedBits = LS.getUsedBits();
8686     // Check if this slice overlaps with another.
8687     if ((CurrentUsedBits & UsedBits) != 0)
8688       return false;
8689     // Update the bits used globally.
8690     UsedBits |= CurrentUsedBits;
8692     // Check if the new slice would be legal.
8693     if (!LS.isLegal())
8694       return false;
8696     // Record the slice.
8697     LoadedSlices.push_back(LS);
8698   }
8700   // Abort slicing if it does not seem to be profitable.
8701   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8702     return false;
8704   ++SlicedLoads;
8706   // Rewrite each chain to use an independent load.
8707   // By construction, each chain can be represented by a unique load.
8709   // Prepare the argument for the new token factor for all the slices.
8710   SmallVector<SDValue, 8> ArgChains;
8711   for (SmallVectorImpl<LoadedSlice>::const_iterator
8712            LSIt = LoadedSlices.begin(),
8713            LSItEnd = LoadedSlices.end();
8714        LSIt != LSItEnd; ++LSIt) {
8715     SDValue SliceInst = LSIt->loadSlice();
8716     CombineTo(LSIt->Inst, SliceInst, true);
8717     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8718       SliceInst = SliceInst.getOperand(0);
8719     assert(SliceInst->getOpcode() == ISD::LOAD &&
8720            "It takes more than a zext to get to the loaded slice!!");
8721     ArgChains.push_back(SliceInst.getValue(1));
8722   }
8724   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8725                               ArgChains);
8726   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8727   return true;
8730 /// Check to see if V is (and load (ptr), imm), where the load is having
8731 /// specific bytes cleared out.  If so, return the byte size being masked out
8732 /// and the shift amount.
8733 static std::pair<unsigned, unsigned>
8734 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8735   std::pair<unsigned, unsigned> Result(0, 0);
8737   // Check for the structure we're looking for.
8738   if (V->getOpcode() != ISD::AND ||
8739       !isa<ConstantSDNode>(V->getOperand(1)) ||
8740       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8741     return Result;
8743   // Check the chain and pointer.
8744   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8745   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8747   // The store should be chained directly to the load or be an operand of a
8748   // tokenfactor.
8749   if (LD == Chain.getNode())
8750     ; // ok.
8751   else if (Chain->getOpcode() != ISD::TokenFactor)
8752     return Result; // Fail.
8753   else {
8754     bool isOk = false;
8755     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8756       if (Chain->getOperand(i).getNode() == LD) {
8757         isOk = true;
8758         break;
8759       }
8760     if (!isOk) return Result;
8761   }
8763   // This only handles simple types.
8764   if (V.getValueType() != MVT::i16 &&
8765       V.getValueType() != MVT::i32 &&
8766       V.getValueType() != MVT::i64)
8767     return Result;
8769   // Check the constant mask.  Invert it so that the bits being masked out are
8770   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8771   // follow the sign bit for uniformity.
8772   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8773   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8774   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8775   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8776   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8777   if (NotMaskLZ == 64) return Result;  // All zero mask.
8779   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8780   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8781     return Result;
8783   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8784   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8785     NotMaskLZ -= 64-V.getValueSizeInBits();
8787   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8788   switch (MaskedBytes) {
8789   case 1:
8790   case 2:
8791   case 4: break;
8792   default: return Result; // All one mask, or 5-byte mask.
8793   }
8795   // Verify that the first bit starts at a multiple of mask so that the access
8796   // is aligned the same as the access width.
8797   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8799   Result.first = MaskedBytes;
8800   Result.second = NotMaskTZ/8;
8801   return Result;
8805 /// Check to see if IVal is something that provides a value as specified by
8806 /// MaskInfo. If so, replace the specified store with a narrower store of
8807 /// truncated IVal.
8808 static SDNode *
8809 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8810                                 SDValue IVal, StoreSDNode *St,
8811                                 DAGCombiner *DC) {
8812   unsigned NumBytes = MaskInfo.first;
8813   unsigned ByteShift = MaskInfo.second;
8814   SelectionDAG &DAG = DC->getDAG();
8816   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8817   // that uses this.  If not, this is not a replacement.
8818   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8819                                   ByteShift*8, (ByteShift+NumBytes)*8);
8820   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8822   // Check that it is legal on the target to do this.  It is legal if the new
8823   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8824   // legalization.
8825   MVT VT = MVT::getIntegerVT(NumBytes*8);
8826   if (!DC->isTypeLegal(VT))
8827     return nullptr;
8829   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8830   // shifted by ByteShift and truncated down to NumBytes.
8831   if (ByteShift)
8832     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8833                        DAG.getConstant(ByteShift*8,
8834                                     DC->getShiftAmountTy(IVal.getValueType())));
8836   // Figure out the offset for the store and the alignment of the access.
8837   unsigned StOffset;
8838   unsigned NewAlign = St->getAlignment();
8840   if (DAG.getTargetLoweringInfo().isLittleEndian())
8841     StOffset = ByteShift;
8842   else
8843     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8845   SDValue Ptr = St->getBasePtr();
8846   if (StOffset) {
8847     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8848                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8849     NewAlign = MinAlign(NewAlign, StOffset);
8850   }
8852   // Truncate down to the new size.
8853   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8855   ++OpsNarrowed;
8856   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8857                       St->getPointerInfo().getWithOffset(StOffset),
8858                       false, false, NewAlign).getNode();
8862 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
8863 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
8864 /// narrowing the load and store if it would end up being a win for performance
8865 /// or code size.
8866 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8867   StoreSDNode *ST  = cast<StoreSDNode>(N);
8868   if (ST->isVolatile())
8869     return SDValue();
8871   SDValue Chain = ST->getChain();
8872   SDValue Value = ST->getValue();
8873   SDValue Ptr   = ST->getBasePtr();
8874   EVT VT = Value.getValueType();
8876   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8877     return SDValue();
8879   unsigned Opc = Value.getOpcode();
8881   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8882   // is a byte mask indicating a consecutive number of bytes, check to see if
8883   // Y is known to provide just those bytes.  If so, we try to replace the
8884   // load + replace + store sequence with a single (narrower) store, which makes
8885   // the load dead.
8886   if (Opc == ISD::OR) {
8887     std::pair<unsigned, unsigned> MaskedLoad;
8888     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8889     if (MaskedLoad.first)
8890       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8891                                                   Value.getOperand(1), ST,this))
8892         return SDValue(NewST, 0);
8894     // Or is commutative, so try swapping X and Y.
8895     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8896     if (MaskedLoad.first)
8897       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8898                                                   Value.getOperand(0), ST,this))
8899         return SDValue(NewST, 0);
8900   }
8902   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8903       Value.getOperand(1).getOpcode() != ISD::Constant)
8904     return SDValue();
8906   SDValue N0 = Value.getOperand(0);
8907   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8908       Chain == SDValue(N0.getNode(), 1)) {
8909     LoadSDNode *LD = cast<LoadSDNode>(N0);
8910     if (LD->getBasePtr() != Ptr ||
8911         LD->getPointerInfo().getAddrSpace() !=
8912         ST->getPointerInfo().getAddrSpace())
8913       return SDValue();
8915     // Find the type to narrow it the load / op / store to.
8916     SDValue N1 = Value.getOperand(1);
8917     unsigned BitWidth = N1.getValueSizeInBits();
8918     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8919     if (Opc == ISD::AND)
8920       Imm ^= APInt::getAllOnesValue(BitWidth);
8921     if (Imm == 0 || Imm.isAllOnesValue())
8922       return SDValue();
8923     unsigned ShAmt = Imm.countTrailingZeros();
8924     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8925     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8926     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8927     while (NewBW < BitWidth &&
8928            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8929              TLI.isNarrowingProfitable(VT, NewVT))) {
8930       NewBW = NextPowerOf2(NewBW);
8931       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8932     }
8933     if (NewBW >= BitWidth)
8934       return SDValue();
8936     // If the lsb changed does not start at the type bitwidth boundary,
8937     // start at the previous one.
8938     if (ShAmt % NewBW)
8939       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8940     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8941                                    std::min(BitWidth, ShAmt + NewBW));
8942     if ((Imm & Mask) == Imm) {
8943       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8944       if (Opc == ISD::AND)
8945         NewImm ^= APInt::getAllOnesValue(NewBW);
8946       uint64_t PtrOff = ShAmt / 8;
8947       // For big endian targets, we need to adjust the offset to the pointer to
8948       // load the correct bytes.
8949       if (TLI.isBigEndian())
8950         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8952       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8953       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8954       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8955         return SDValue();
8957       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8958                                    Ptr.getValueType(), Ptr,
8959                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8960       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8961                                   LD->getChain(), NewPtr,
8962                                   LD->getPointerInfo().getWithOffset(PtrOff),
8963                                   LD->isVolatile(), LD->isNonTemporal(),
8964                                   LD->isInvariant(), NewAlign,
8965                                   LD->getAAInfo());
8966       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8967                                    DAG.getConstant(NewImm, NewVT));
8968       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8969                                    NewVal, NewPtr,
8970                                    ST->getPointerInfo().getWithOffset(PtrOff),
8971                                    false, false, NewAlign);
8973       AddToWorklist(NewPtr.getNode());
8974       AddToWorklist(NewLD.getNode());
8975       AddToWorklist(NewVal.getNode());
8976       WorklistRemover DeadNodes(*this);
8977       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8978       ++OpsNarrowed;
8979       return NewST;
8980     }
8981   }
8983   return SDValue();
8986 /// For a given floating point load / store pair, if the load value isn't used
8987 /// by any other operations, then consider transforming the pair to integer
8988 /// load / store operations if the target deems the transformation profitable.
8989 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8990   StoreSDNode *ST  = cast<StoreSDNode>(N);
8991   SDValue Chain = ST->getChain();
8992   SDValue Value = ST->getValue();
8993   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8994       Value.hasOneUse() &&
8995       Chain == SDValue(Value.getNode(), 1)) {
8996     LoadSDNode *LD = cast<LoadSDNode>(Value);
8997     EVT VT = LD->getMemoryVT();
8998     if (!VT.isFloatingPoint() ||
8999         VT != ST->getMemoryVT() ||
9000         LD->isNonTemporal() ||
9001         ST->isNonTemporal() ||
9002         LD->getPointerInfo().getAddrSpace() != 0 ||
9003         ST->getPointerInfo().getAddrSpace() != 0)
9004       return SDValue();
9006     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9007     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9008         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9009         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9010         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9011       return SDValue();
9013     unsigned LDAlign = LD->getAlignment();
9014     unsigned STAlign = ST->getAlignment();
9015     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9016     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9017     if (LDAlign < ABIAlign || STAlign < ABIAlign)
9018       return SDValue();
9020     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9021                                 LD->getChain(), LD->getBasePtr(),
9022                                 LD->getPointerInfo(),
9023                                 false, false, false, LDAlign);
9025     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9026                                  NewLD, ST->getBasePtr(),
9027                                  ST->getPointerInfo(),
9028                                  false, false, STAlign);
9030     AddToWorklist(NewLD.getNode());
9031     AddToWorklist(NewST.getNode());
9032     WorklistRemover DeadNodes(*this);
9033     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9034     ++LdStFP2Int;
9035     return NewST;
9036   }
9038   return SDValue();
9041 /// Helper struct to parse and store a memory address as base + index + offset.
9042 /// We ignore sign extensions when it is safe to do so.
9043 /// The following two expressions are not equivalent. To differentiate we need
9044 /// to store whether there was a sign extension involved in the index
9045 /// computation.
9046 ///  (load (i64 add (i64 copyfromreg %c)
9047 ///                 (i64 signextend (add (i8 load %index)
9048 ///                                      (i8 1))))
9049 /// vs
9050 ///
9051 /// (load (i64 add (i64 copyfromreg %c)
9052 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
9053 ///                                         (i32 1)))))
9054 struct BaseIndexOffset {
9055   SDValue Base;
9056   SDValue Index;
9057   int64_t Offset;
9058   bool IsIndexSignExt;
9060   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9062   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9063                   bool IsIndexSignExt) :
9064     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9066   bool equalBaseIndex(const BaseIndexOffset &Other) {
9067     return Other.Base == Base && Other.Index == Index &&
9068       Other.IsIndexSignExt == IsIndexSignExt;
9069   }
9071   /// Parses tree in Ptr for base, index, offset addresses.
9072   static BaseIndexOffset match(SDValue Ptr) {
9073     bool IsIndexSignExt = false;
9075     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9076     // instruction, then it could be just the BASE or everything else we don't
9077     // know how to handle. Just use Ptr as BASE and give up.
9078     if (Ptr->getOpcode() != ISD::ADD)
9079       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9081     // We know that we have at least an ADD instruction. Try to pattern match
9082     // the simple case of BASE + OFFSET.
9083     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9084       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9085       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9086                               IsIndexSignExt);
9087     }
9089     // Inside a loop the current BASE pointer is calculated using an ADD and a
9090     // MUL instruction. In this case Ptr is the actual BASE pointer.
9091     // (i64 add (i64 %array_ptr)
9092     //          (i64 mul (i64 %induction_var)
9093     //                   (i64 %element_size)))
9094     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9095       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9097     // Look at Base + Index + Offset cases.
9098     SDValue Base = Ptr->getOperand(0);
9099     SDValue IndexOffset = Ptr->getOperand(1);
9101     // Skip signextends.
9102     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9103       IndexOffset = IndexOffset->getOperand(0);
9104       IsIndexSignExt = true;
9105     }
9107     // Either the case of Base + Index (no offset) or something else.
9108     if (IndexOffset->getOpcode() != ISD::ADD)
9109       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9111     // Now we have the case of Base + Index + offset.
9112     SDValue Index = IndexOffset->getOperand(0);
9113     SDValue Offset = IndexOffset->getOperand(1);
9115     if (!isa<ConstantSDNode>(Offset))
9116       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9118     // Ignore signextends.
9119     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9120       Index = Index->getOperand(0);
9121       IsIndexSignExt = true;
9122     } else IsIndexSignExt = false;
9124     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9125     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9126   }
9127 };
9129 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9130 /// is located in a sequence of memory operations connected by a chain.
9131 struct MemOpLink {
9132   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9133     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9134   // Ptr to the mem node.
9135   LSBaseSDNode *MemNode;
9136   // Offset from the base ptr.
9137   int64_t OffsetFromBase;
9138   // What is the sequence number of this mem node.
9139   // Lowest mem operand in the DAG starts at zero.
9140   unsigned SequenceNum;
9141 };
9143 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9144   EVT MemVT = St->getMemoryVT();
9145   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9146   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9147     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9149   // Don't merge vectors into wider inputs.
9150   if (MemVT.isVector() || !MemVT.isSimple())
9151     return false;
9153   // Perform an early exit check. Do not bother looking at stored values that
9154   // are not constants or loads.
9155   SDValue StoredVal = St->getValue();
9156   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9157   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9158       !IsLoadSrc)
9159     return false;
9161   // Only look at ends of store sequences.
9162   SDValue Chain = SDValue(St, 0);
9163   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9164     return false;
9166   // This holds the base pointer, index, and the offset in bytes from the base
9167   // pointer.
9168   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9170   // We must have a base and an offset.
9171   if (!BasePtr.Base.getNode())
9172     return false;
9174   // Do not handle stores to undef base pointers.
9175   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9176     return false;
9178   // Save the LoadSDNodes that we find in the chain.
9179   // We need to make sure that these nodes do not interfere with
9180   // any of the store nodes.
9181   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9183   // Save the StoreSDNodes that we find in the chain.
9184   SmallVector<MemOpLink, 8> StoreNodes;
9186   // Walk up the chain and look for nodes with offsets from the same
9187   // base pointer. Stop when reaching an instruction with a different kind
9188   // or instruction which has a different base pointer.
9189   unsigned Seq = 0;
9190   StoreSDNode *Index = St;
9191   while (Index) {
9192     // If the chain has more than one use, then we can't reorder the mem ops.
9193     if (Index != St && !SDValue(Index, 0)->hasOneUse())
9194       break;
9196     // Find the base pointer and offset for this memory node.
9197     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9199     // Check that the base pointer is the same as the original one.
9200     if (!Ptr.equalBaseIndex(BasePtr))
9201       break;
9203     // Check that the alignment is the same.
9204     if (Index->getAlignment() != St->getAlignment())
9205       break;
9207     // The memory operands must not be volatile.
9208     if (Index->isVolatile() || Index->isIndexed())
9209       break;
9211     // No truncation.
9212     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9213       if (St->isTruncatingStore())
9214         break;
9216     // The stored memory type must be the same.
9217     if (Index->getMemoryVT() != MemVT)
9218       break;
9220     // We do not allow unaligned stores because we want to prevent overriding
9221     // stores.
9222     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9223       break;
9225     // We found a potential memory operand to merge.
9226     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9228     // Find the next memory operand in the chain. If the next operand in the
9229     // chain is a store then move up and continue the scan with the next
9230     // memory operand. If the next operand is a load save it and use alias
9231     // information to check if it interferes with anything.
9232     SDNode *NextInChain = Index->getChain().getNode();
9233     while (1) {
9234       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9235         // We found a store node. Use it for the next iteration.
9236         Index = STn;
9237         break;
9238       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9239         if (Ldn->isVolatile()) {
9240           Index = nullptr;
9241           break;
9242         }
9244         // Save the load node for later. Continue the scan.
9245         AliasLoadNodes.push_back(Ldn);
9246         NextInChain = Ldn->getChain().getNode();
9247         continue;
9248       } else {
9249         Index = nullptr;
9250         break;
9251       }
9252     }
9253   }
9255   // Check if there is anything to merge.
9256   if (StoreNodes.size() < 2)
9257     return false;
9259   // Sort the memory operands according to their distance from the base pointer.
9260   std::sort(StoreNodes.begin(), StoreNodes.end(),
9261             [](MemOpLink LHS, MemOpLink RHS) {
9262     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9263            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9264             LHS.SequenceNum > RHS.SequenceNum);
9265   });
9267   // Scan the memory operations on the chain and find the first non-consecutive
9268   // store memory address.
9269   unsigned LastConsecutiveStore = 0;
9270   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9271   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9273     // Check that the addresses are consecutive starting from the second
9274     // element in the list of stores.
9275     if (i > 0) {
9276       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9277       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9278         break;
9279     }
9281     bool Alias = false;
9282     // Check if this store interferes with any of the loads that we found.
9283     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9284       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9285         Alias = true;
9286         break;
9287       }
9288     // We found a load that alias with this store. Stop the sequence.
9289     if (Alias)
9290       break;
9292     // Mark this node as useful.
9293     LastConsecutiveStore = i;
9294   }
9296   // The node with the lowest store address.
9297   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9299   // Store the constants into memory as one consecutive store.
9300   if (!IsLoadSrc) {
9301     unsigned LastLegalType = 0;
9302     unsigned LastLegalVectorType = 0;
9303     bool NonZero = false;
9304     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9305       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9306       SDValue StoredVal = St->getValue();
9308       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9309         NonZero |= !C->isNullValue();
9310       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9311         NonZero |= !C->getConstantFPValue()->isNullValue();
9312       } else {
9313         // Non-constant.
9314         break;
9315       }
9317       // Find a legal type for the constant store.
9318       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9319       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9320       if (TLI.isTypeLegal(StoreTy))
9321         LastLegalType = i+1;
9322       // Or check whether a truncstore is legal.
9323       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9324                TargetLowering::TypePromoteInteger) {
9325         EVT LegalizedStoredValueTy =
9326           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9327         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9328           LastLegalType = i+1;
9329       }
9331       // Find a legal type for the vector store.
9332       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9333       if (TLI.isTypeLegal(Ty))
9334         LastLegalVectorType = i + 1;
9335     }
9337     // We only use vectors if the constant is known to be zero and the
9338     // function is not marked with the noimplicitfloat attribute.
9339     if (NonZero || NoVectors)
9340       LastLegalVectorType = 0;
9342     // Check if we found a legal integer type to store.
9343     if (LastLegalType == 0 && LastLegalVectorType == 0)
9344       return false;
9346     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9347     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9349     // Make sure we have something to merge.
9350     if (NumElem < 2)
9351       return false;
9353     unsigned EarliestNodeUsed = 0;
9354     for (unsigned i=0; i < NumElem; ++i) {
9355       // Find a chain for the new wide-store operand. Notice that some
9356       // of the store nodes that we found may not be selected for inclusion
9357       // in the wide store. The chain we use needs to be the chain of the
9358       // earliest store node which is *used* and replaced by the wide store.
9359       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9360         EarliestNodeUsed = i;
9361     }
9363     // The earliest Node in the DAG.
9364     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9365     SDLoc DL(StoreNodes[0].MemNode);
9367     SDValue StoredVal;
9368     if (UseVector) {
9369       // Find a legal type for the vector store.
9370       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9371       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9372       StoredVal = DAG.getConstant(0, Ty);
9373     } else {
9374       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9375       APInt StoreInt(StoreBW, 0);
9377       // Construct a single integer constant which is made of the smaller
9378       // constant inputs.
9379       bool IsLE = TLI.isLittleEndian();
9380       for (unsigned i = 0; i < NumElem ; ++i) {
9381         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9382         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9383         SDValue Val = St->getValue();
9384         StoreInt<<=ElementSizeBytes*8;
9385         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9386           StoreInt|=C->getAPIntValue().zext(StoreBW);
9387         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9388           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9389         } else {
9390           assert(false && "Invalid constant element type");
9391         }
9392       }
9394       // Create the new Load and Store operations.
9395       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9396       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9397     }
9399     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9400                                     FirstInChain->getBasePtr(),
9401                                     FirstInChain->getPointerInfo(),
9402                                     false, false,
9403                                     FirstInChain->getAlignment());
9405     // Replace the first store with the new store
9406     CombineTo(EarliestOp, NewStore);
9407     // Erase all other stores.
9408     for (unsigned i = 0; i < NumElem ; ++i) {
9409       if (StoreNodes[i].MemNode == EarliestOp)
9410         continue;
9411       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9412       // ReplaceAllUsesWith will replace all uses that existed when it was
9413       // called, but graph optimizations may cause new ones to appear. For
9414       // example, the case in pr14333 looks like
9415       //
9416       //  St's chain -> St -> another store -> X
9417       //
9418       // And the only difference from St to the other store is the chain.
9419       // When we change it's chain to be St's chain they become identical,
9420       // get CSEed and the net result is that X is now a use of St.
9421       // Since we know that St is redundant, just iterate.
9422       while (!St->use_empty())
9423         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9424       deleteAndRecombine(St);
9425     }
9427     return true;
9428   }
9430   // Below we handle the case of multiple consecutive stores that
9431   // come from multiple consecutive loads. We merge them into a single
9432   // wide load and a single wide store.
9434   // Look for load nodes which are used by the stored values.
9435   SmallVector<MemOpLink, 8> LoadNodes;
9437   // Find acceptable loads. Loads need to have the same chain (token factor),
9438   // must not be zext, volatile, indexed, and they must be consecutive.
9439   BaseIndexOffset LdBasePtr;
9440   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9441     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9442     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9443     if (!Ld) break;
9445     // Loads must only have one use.
9446     if (!Ld->hasNUsesOfValue(1, 0))
9447       break;
9449     // Check that the alignment is the same as the stores.
9450     if (Ld->getAlignment() != St->getAlignment())
9451       break;
9453     // The memory operands must not be volatile.
9454     if (Ld->isVolatile() || Ld->isIndexed())
9455       break;
9457     // We do not accept ext loads.
9458     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9459       break;
9461     // The stored memory type must be the same.
9462     if (Ld->getMemoryVT() != MemVT)
9463       break;
9465     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9466     // If this is not the first ptr that we check.
9467     if (LdBasePtr.Base.getNode()) {
9468       // The base ptr must be the same.
9469       if (!LdPtr.equalBaseIndex(LdBasePtr))
9470         break;
9471     } else {
9472       // Check that all other base pointers are the same as this one.
9473       LdBasePtr = LdPtr;
9474     }
9476     // We found a potential memory operand to merge.
9477     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9478   }
9480   if (LoadNodes.size() < 2)
9481     return false;
9483   // If we have load/store pair instructions and we only have two values,
9484   // don't bother.
9485   unsigned RequiredAlignment;
9486   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9487       St->getAlignment() >= RequiredAlignment)
9488     return false;
9490   // Scan the memory operations on the chain and find the first non-consecutive
9491   // load memory address. These variables hold the index in the store node
9492   // array.
9493   unsigned LastConsecutiveLoad = 0;
9494   // This variable refers to the size and not index in the array.
9495   unsigned LastLegalVectorType = 0;
9496   unsigned LastLegalIntegerType = 0;
9497   StartAddress = LoadNodes[0].OffsetFromBase;
9498   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9499   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9500     // All loads much share the same chain.
9501     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9502       break;
9504     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9505     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9506       break;
9507     LastConsecutiveLoad = i;
9509     // Find a legal type for the vector store.
9510     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9511     if (TLI.isTypeLegal(StoreTy))
9512       LastLegalVectorType = i + 1;
9514     // Find a legal type for the integer store.
9515     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9516     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9517     if (TLI.isTypeLegal(StoreTy))
9518       LastLegalIntegerType = i + 1;
9519     // Or check whether a truncstore and extload is legal.
9520     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9521              TargetLowering::TypePromoteInteger) {
9522       EVT LegalizedStoredValueTy =
9523         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9524       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9525           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9526           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9527           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9528         LastLegalIntegerType = i+1;
9529     }
9530   }
9532   // Only use vector types if the vector type is larger than the integer type.
9533   // If they are the same, use integers.
9534   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9535   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9537   // We add +1 here because the LastXXX variables refer to location while
9538   // the NumElem refers to array/index size.
9539   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9540   NumElem = std::min(LastLegalType, NumElem);
9542   if (NumElem < 2)
9543     return false;
9545   // The earliest Node in the DAG.
9546   unsigned EarliestNodeUsed = 0;
9547   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9548   for (unsigned i=1; i<NumElem; ++i) {
9549     // Find a chain for the new wide-store operand. Notice that some
9550     // of the store nodes that we found may not be selected for inclusion
9551     // in the wide store. The chain we use needs to be the chain of the
9552     // earliest store node which is *used* and replaced by the wide store.
9553     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9554       EarliestNodeUsed = i;
9555   }
9557   // Find if it is better to use vectors or integers to load and store
9558   // to memory.
9559   EVT JointMemOpVT;
9560   if (UseVectorTy) {
9561     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9562   } else {
9563     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9564     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9565   }
9567   SDLoc LoadDL(LoadNodes[0].MemNode);
9568   SDLoc StoreDL(StoreNodes[0].MemNode);
9570   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9571   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9572                                 FirstLoad->getChain(),
9573                                 FirstLoad->getBasePtr(),
9574                                 FirstLoad->getPointerInfo(),
9575                                 false, false, false,
9576                                 FirstLoad->getAlignment());
9578   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9579                                   FirstInChain->getBasePtr(),
9580                                   FirstInChain->getPointerInfo(), false, false,
9581                                   FirstInChain->getAlignment());
9583   // Replace one of the loads with the new load.
9584   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9585   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9586                                 SDValue(NewLoad.getNode(), 1));
9588   // Remove the rest of the load chains.
9589   for (unsigned i = 1; i < NumElem ; ++i) {
9590     // Replace all chain users of the old load nodes with the chain of the new
9591     // load node.
9592     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9593     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9594   }
9596   // Replace the first store with the new store.
9597   CombineTo(EarliestOp, NewStore);
9598   // Erase all other stores.
9599   for (unsigned i = 0; i < NumElem ; ++i) {
9600     // Remove all Store nodes.
9601     if (StoreNodes[i].MemNode == EarliestOp)
9602       continue;
9603     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9604     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9605     deleteAndRecombine(St);
9606   }
9608   return true;
9611 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9612   StoreSDNode *ST  = cast<StoreSDNode>(N);
9613   SDValue Chain = ST->getChain();
9614   SDValue Value = ST->getValue();
9615   SDValue Ptr   = ST->getBasePtr();
9617   // If this is a store of a bit convert, store the input value if the
9618   // resultant store does not need a higher alignment than the original.
9619   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9620       ST->isUnindexed()) {
9621     unsigned OrigAlign = ST->getAlignment();
9622     EVT SVT = Value.getOperand(0).getValueType();
9623     unsigned Align = TLI.getDataLayout()->
9624       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9625     if (Align <= OrigAlign &&
9626         ((!LegalOperations && !ST->isVolatile()) ||
9627          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9628       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9629                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9630                           ST->isNonTemporal(), OrigAlign,
9631                           ST->getAAInfo());
9632   }
9634   // Turn 'store undef, Ptr' -> nothing.
9635   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9636     return Chain;
9638   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9639   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9640     // NOTE: If the original store is volatile, this transform must not increase
9641     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9642     // processor operation but an i64 (which is not legal) requires two.  So the
9643     // transform should not be done in this case.
9644     if (Value.getOpcode() != ISD::TargetConstantFP) {
9645       SDValue Tmp;
9646       switch (CFP->getSimpleValueType(0).SimpleTy) {
9647       default: llvm_unreachable("Unknown FP type");
9648       case MVT::f16:    // We don't do this for these yet.
9649       case MVT::f80:
9650       case MVT::f128:
9651       case MVT::ppcf128:
9652         break;
9653       case MVT::f32:
9654         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9655             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9656           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9657                               bitcastToAPInt().getZExtValue(), MVT::i32);
9658           return DAG.getStore(Chain, SDLoc(N), Tmp,
9659                               Ptr, ST->getMemOperand());
9660         }
9661         break;
9662       case MVT::f64:
9663         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9664              !ST->isVolatile()) ||
9665             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9666           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9667                                 getZExtValue(), MVT::i64);
9668           return DAG.getStore(Chain, SDLoc(N), Tmp,
9669                               Ptr, ST->getMemOperand());
9670         }
9672         if (!ST->isVolatile() &&
9673             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9674           // Many FP stores are not made apparent until after legalize, e.g. for
9675           // argument passing.  Since this is so common, custom legalize the
9676           // 64-bit integer store into two 32-bit stores.
9677           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9678           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9679           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9680           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9682           unsigned Alignment = ST->getAlignment();
9683           bool isVolatile = ST->isVolatile();
9684           bool isNonTemporal = ST->isNonTemporal();
9685           AAMDNodes AAInfo = ST->getAAInfo();
9687           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9688                                      Ptr, ST->getPointerInfo(),
9689                                      isVolatile, isNonTemporal,
9690                                      ST->getAlignment(), AAInfo);
9691           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9692                             DAG.getConstant(4, Ptr.getValueType()));
9693           Alignment = MinAlign(Alignment, 4U);
9694           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9695                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9696                                      isVolatile, isNonTemporal,
9697                                      Alignment, AAInfo);
9698           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9699                              St0, St1);
9700         }
9702         break;
9703       }
9704     }
9705   }
9707   // Try to infer better alignment information than the store already has.
9708   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9709     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9710       if (Align > ST->getAlignment())
9711         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9712                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9713                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9714                                  ST->getAAInfo());
9715     }
9716   }
9718   // Try transforming a pair floating point load / store ops to integer
9719   // load / store ops.
9720   SDValue NewST = TransformFPLoadStorePair(N);
9721   if (NewST.getNode())
9722     return NewST;
9724   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9725     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9726 #ifndef NDEBUG
9727   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9728       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9729     UseAA = false;
9730 #endif
9731   if (UseAA && ST->isUnindexed()) {
9732     // Walk up chain skipping non-aliasing memory nodes.
9733     SDValue BetterChain = FindBetterChain(N, Chain);
9735     // If there is a better chain.
9736     if (Chain != BetterChain) {
9737       SDValue ReplStore;
9739       // Replace the chain to avoid dependency.
9740       if (ST->isTruncatingStore()) {
9741         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9742                                       ST->getMemoryVT(), ST->getMemOperand());
9743       } else {
9744         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9745                                  ST->getMemOperand());
9746       }
9748       // Create token to keep both nodes around.
9749       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9750                                   MVT::Other, Chain, ReplStore);
9752       // Make sure the new and old chains are cleaned up.
9753       AddToWorklist(Token.getNode());
9755       // Don't add users to work list.
9756       return CombineTo(N, Token, false);
9757     }
9758   }
9760   // Try transforming N to an indexed store.
9761   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9762     return SDValue(N, 0);
9764   // FIXME: is there such a thing as a truncating indexed store?
9765   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9766       Value.getValueType().isInteger()) {
9767     // See if we can simplify the input to this truncstore with knowledge that
9768     // only the low bits are being used.  For example:
9769     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9770     SDValue Shorter =
9771       GetDemandedBits(Value,
9772                       APInt::getLowBitsSet(
9773                         Value.getValueType().getScalarType().getSizeInBits(),
9774                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9775     AddToWorklist(Value.getNode());
9776     if (Shorter.getNode())
9777       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9778                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9780     // Otherwise, see if we can simplify the operation with
9781     // SimplifyDemandedBits, which only works if the value has a single use.
9782     if (SimplifyDemandedBits(Value,
9783                         APInt::getLowBitsSet(
9784                           Value.getValueType().getScalarType().getSizeInBits(),
9785                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9786       return SDValue(N, 0);
9787   }
9789   // If this is a load followed by a store to the same location, then the store
9790   // is dead/noop.
9791   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9792     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9793         ST->isUnindexed() && !ST->isVolatile() &&
9794         // There can't be any side effects between the load and store, such as
9795         // a call or store.
9796         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9797       // The store is dead, remove it.
9798       return Chain;
9799     }
9800   }
9802   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9803   // truncating store.  We can do this even if this is already a truncstore.
9804   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9805       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9806       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9807                             ST->getMemoryVT())) {
9808     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9809                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9810   }
9812   // Only perform this optimization before the types are legal, because we
9813   // don't want to perform this optimization on every DAGCombine invocation.
9814   if (!LegalTypes) {
9815     bool EverChanged = false;
9817     do {
9818       // There can be multiple store sequences on the same chain.
9819       // Keep trying to merge store sequences until we are unable to do so
9820       // or until we merge the last store on the chain.
9821       bool Changed = MergeConsecutiveStores(ST);
9822       EverChanged |= Changed;
9823       if (!Changed) break;
9824     } while (ST->getOpcode() != ISD::DELETED_NODE);
9826     if (EverChanged)
9827       return SDValue(N, 0);
9828   }
9830   return ReduceLoadOpStoreWidth(N);
9833 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9834   SDValue InVec = N->getOperand(0);
9835   SDValue InVal = N->getOperand(1);
9836   SDValue EltNo = N->getOperand(2);
9837   SDLoc dl(N);
9839   // If the inserted element is an UNDEF, just use the input vector.
9840   if (InVal.getOpcode() == ISD::UNDEF)
9841     return InVec;
9843   EVT VT = InVec.getValueType();
9845   // If we can't generate a legal BUILD_VECTOR, exit
9846   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9847     return SDValue();
9849   // Check that we know which element is being inserted
9850   if (!isa<ConstantSDNode>(EltNo))
9851     return SDValue();
9852   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9854   // Canonicalize insert_vector_elt dag nodes.
9855   // Example:
9856   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9857   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9858   //
9859   // Do this only if the child insert_vector node has one use; also
9860   // do this only if indices are both constants and Idx1 < Idx0.
9861   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9862       && isa<ConstantSDNode>(InVec.getOperand(2))) {
9863     unsigned OtherElt =
9864       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9865     if (Elt < OtherElt) {
9866       // Swap nodes.
9867       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9868                                   InVec.getOperand(0), InVal, EltNo);
9869       AddToWorklist(NewOp.getNode());
9870       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9871                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9872     }
9873   }
9875   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9876   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9877   // vector elements.
9878   SmallVector<SDValue, 8> Ops;
9879   // Do not combine these two vectors if the output vector will not replace
9880   // the input vector.
9881   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9882     Ops.append(InVec.getNode()->op_begin(),
9883                InVec.getNode()->op_end());
9884   } else if (InVec.getOpcode() == ISD::UNDEF) {
9885     unsigned NElts = VT.getVectorNumElements();
9886     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9887   } else {
9888     return SDValue();
9889   }
9891   // Insert the element
9892   if (Elt < Ops.size()) {
9893     // All the operands of BUILD_VECTOR must have the same type;
9894     // we enforce that here.
9895     EVT OpVT = Ops[0].getValueType();
9896     if (InVal.getValueType() != OpVT)
9897       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9898                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9899                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9900     Ops[Elt] = InVal;
9901   }
9903   // Return the new vector
9904   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9907 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
9908     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
9909   EVT ResultVT = EVE->getValueType(0);
9910   EVT VecEltVT = InVecVT.getVectorElementType();
9911   unsigned Align = OriginalLoad->getAlignment();
9912   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
9913       VecEltVT.getTypeForEVT(*DAG.getContext()));
9915   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
9916     return SDValue();
9918   Align = NewAlign;
9920   SDValue NewPtr = OriginalLoad->getBasePtr();
9921   SDValue Offset;
9922   EVT PtrType = NewPtr.getValueType();
9923   MachinePointerInfo MPI;
9924   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
9925     int Elt = ConstEltNo->getZExtValue();
9926     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
9927     if (TLI.isBigEndian())
9928       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
9929     Offset = DAG.getConstant(PtrOff, PtrType);
9930     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
9931   } else {
9932     Offset = DAG.getNode(
9933         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
9934         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
9935     if (TLI.isBigEndian())
9936       Offset = DAG.getNode(
9937           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
9938           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
9939     MPI = OriginalLoad->getPointerInfo();
9940   }
9941   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
9943   // The replacement we need to do here is a little tricky: we need to
9944   // replace an extractelement of a load with a load.
9945   // Use ReplaceAllUsesOfValuesWith to do the replacement.
9946   // Note that this replacement assumes that the extractvalue is the only
9947   // use of the load; that's okay because we don't want to perform this
9948   // transformation in other cases anyway.
9949   SDValue Load;
9950   SDValue Chain;
9951   if (ResultVT.bitsGT(VecEltVT)) {
9952     // If the result type of vextract is wider than the load, then issue an
9953     // extending load instead.
9954     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
9955                                    ? ISD::ZEXTLOAD
9956                                    : ISD::EXTLOAD;
9957     Load = DAG.getExtLoad(
9958         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
9959         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9960         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9961     Chain = Load.getValue(1);
9962   } else {
9963     Load = DAG.getLoad(
9964         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
9965         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9966         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9967     Chain = Load.getValue(1);
9968     if (ResultVT.bitsLT(VecEltVT))
9969       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
9970     else
9971       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
9972   }
9973   WorklistRemover DeadNodes(*this);
9974   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
9975   SDValue To[] = { Load, Chain };
9976   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9977   // Since we're explicitly calling ReplaceAllUses, add the new node to the
9978   // worklist explicitly as well.
9979   AddToWorklist(Load.getNode());
9980   AddUsersToWorklist(Load.getNode()); // Add users too
9981   // Make sure to revisit this node to clean it up; it will usually be dead.
9982   AddToWorklist(EVE);
9983   ++OpsNarrowed;
9984   return SDValue(EVE, 0);
9987 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9988   // (vextract (scalar_to_vector val, 0) -> val
9989   SDValue InVec = N->getOperand(0);
9990   EVT VT = InVec.getValueType();
9991   EVT NVT = N->getValueType(0);
9993   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9994     // Check if the result type doesn't match the inserted element type. A
9995     // SCALAR_TO_VECTOR may truncate the inserted element and the
9996     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9997     SDValue InOp = InVec.getOperand(0);
9998     if (InOp.getValueType() != NVT) {
9999       assert(InOp.getValueType().isInteger() && NVT.isInteger());
10000       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10001     }
10002     return InOp;
10003   }
10005   SDValue EltNo = N->getOperand(1);
10006   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10008   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10009   // We only perform this optimization before the op legalization phase because
10010   // we may introduce new vector instructions which are not backed by TD
10011   // patterns. For example on AVX, extracting elements from a wide vector
10012   // without using extract_subvector. However, if we can find an underlying
10013   // scalar value, then we can always use that.
10014   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10015       && ConstEltNo) {
10016     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10017     int NumElem = VT.getVectorNumElements();
10018     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10019     // Find the new index to extract from.
10020     int OrigElt = SVOp->getMaskElt(Elt);
10022     // Extracting an undef index is undef.
10023     if (OrigElt == -1)
10024       return DAG.getUNDEF(NVT);
10026     // Select the right vector half to extract from.
10027     SDValue SVInVec;
10028     if (OrigElt < NumElem) {
10029       SVInVec = InVec->getOperand(0);
10030     } else {
10031       SVInVec = InVec->getOperand(1);
10032       OrigElt -= NumElem;
10033     }
10035     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10036       SDValue InOp = SVInVec.getOperand(OrigElt);
10037       if (InOp.getValueType() != NVT) {
10038         assert(InOp.getValueType().isInteger() && NVT.isInteger());
10039         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10040       }
10042       return InOp;
10043     }
10045     // FIXME: We should handle recursing on other vector shuffles and
10046     // scalar_to_vector here as well.
10048     if (!LegalOperations) {
10049       EVT IndexTy = TLI.getVectorIdxTy();
10050       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10051                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
10052     }
10053   }
10055   bool BCNumEltsChanged = false;
10056   EVT ExtVT = VT.getVectorElementType();
10057   EVT LVT = ExtVT;
10059   // If the result of load has to be truncated, then it's not necessarily
10060   // profitable.
10061   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10062     return SDValue();
10064   if (InVec.getOpcode() == ISD::BITCAST) {
10065     // Don't duplicate a load with other uses.
10066     if (!InVec.hasOneUse())
10067       return SDValue();
10069     EVT BCVT = InVec.getOperand(0).getValueType();
10070     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10071       return SDValue();
10072     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10073       BCNumEltsChanged = true;
10074     InVec = InVec.getOperand(0);
10075     ExtVT = BCVT.getVectorElementType();
10076   }
10078   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10079   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10080       ISD::isNormalLoad(InVec.getNode()) &&
10081       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10082     SDValue Index = N->getOperand(1);
10083     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10084       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10085                                                            OrigLoad);
10086   }
10088   // Perform only after legalization to ensure build_vector / vector_shuffle
10089   // optimizations have already been done.
10090   if (!LegalOperations) return SDValue();
10092   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10093   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10094   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10096   if (ConstEltNo) {
10097     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10099     LoadSDNode *LN0 = nullptr;
10100     const ShuffleVectorSDNode *SVN = nullptr;
10101     if (ISD::isNormalLoad(InVec.getNode())) {
10102       LN0 = cast<LoadSDNode>(InVec);
10103     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10104                InVec.getOperand(0).getValueType() == ExtVT &&
10105                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10106       // Don't duplicate a load with other uses.
10107       if (!InVec.hasOneUse())
10108         return SDValue();
10110       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10111     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10112       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10113       // =>
10114       // (load $addr+1*size)
10116       // Don't duplicate a load with other uses.
10117       if (!InVec.hasOneUse())
10118         return SDValue();
10120       // If the bit convert changed the number of elements, it is unsafe
10121       // to examine the mask.
10122       if (BCNumEltsChanged)
10123         return SDValue();
10125       // Select the input vector, guarding against out of range extract vector.
10126       unsigned NumElems = VT.getVectorNumElements();
10127       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10128       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10130       if (InVec.getOpcode() == ISD::BITCAST) {
10131         // Don't duplicate a load with other uses.
10132         if (!InVec.hasOneUse())
10133           return SDValue();
10135         InVec = InVec.getOperand(0);
10136       }
10137       if (ISD::isNormalLoad(InVec.getNode())) {
10138         LN0 = cast<LoadSDNode>(InVec);
10139         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10140         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10141       }
10142     }
10144     // Make sure we found a non-volatile load and the extractelement is
10145     // the only use.
10146     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10147       return SDValue();
10149     // If Idx was -1 above, Elt is going to be -1, so just return undef.
10150     if (Elt == -1)
10151       return DAG.getUNDEF(LVT);
10153     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10154   }
10156   return SDValue();
10159 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10160 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10161   // We perform this optimization post type-legalization because
10162   // the type-legalizer often scalarizes integer-promoted vectors.
10163   // Performing this optimization before may create bit-casts which
10164   // will be type-legalized to complex code sequences.
10165   // We perform this optimization only before the operation legalizer because we
10166   // may introduce illegal operations.
10167   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10168     return SDValue();
10170   unsigned NumInScalars = N->getNumOperands();
10171   SDLoc dl(N);
10172   EVT VT = N->getValueType(0);
10174   // Check to see if this is a BUILD_VECTOR of a bunch of values
10175   // which come from any_extend or zero_extend nodes. If so, we can create
10176   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10177   // optimizations. We do not handle sign-extend because we can't fill the sign
10178   // using shuffles.
10179   EVT SourceType = MVT::Other;
10180   bool AllAnyExt = true;
10182   for (unsigned i = 0; i != NumInScalars; ++i) {
10183     SDValue In = N->getOperand(i);
10184     // Ignore undef inputs.
10185     if (In.getOpcode() == ISD::UNDEF) continue;
10187     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10188     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10190     // Abort if the element is not an extension.
10191     if (!ZeroExt && !AnyExt) {
10192       SourceType = MVT::Other;
10193       break;
10194     }
10196     // The input is a ZeroExt or AnyExt. Check the original type.
10197     EVT InTy = In.getOperand(0).getValueType();
10199     // Check that all of the widened source types are the same.
10200     if (SourceType == MVT::Other)
10201       // First time.
10202       SourceType = InTy;
10203     else if (InTy != SourceType) {
10204       // Multiple income types. Abort.
10205       SourceType = MVT::Other;
10206       break;
10207     }
10209     // Check if all of the extends are ANY_EXTENDs.
10210     AllAnyExt &= AnyExt;
10211   }
10213   // In order to have valid types, all of the inputs must be extended from the
10214   // same source type and all of the inputs must be any or zero extend.
10215   // Scalar sizes must be a power of two.
10216   EVT OutScalarTy = VT.getScalarType();
10217   bool ValidTypes = SourceType != MVT::Other &&
10218                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10219                  isPowerOf2_32(SourceType.getSizeInBits());
10221   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10222   // turn into a single shuffle instruction.
10223   if (!ValidTypes)
10224     return SDValue();
10226   bool isLE = TLI.isLittleEndian();
10227   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10228   assert(ElemRatio > 1 && "Invalid element size ratio");
10229   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10230                                DAG.getConstant(0, SourceType);
10232   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10233   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10235   // Populate the new build_vector
10236   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10237     SDValue Cast = N->getOperand(i);
10238     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10239             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10240             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10241     SDValue In;
10242     if (Cast.getOpcode() == ISD::UNDEF)
10243       In = DAG.getUNDEF(SourceType);
10244     else
10245       In = Cast->getOperand(0);
10246     unsigned Index = isLE ? (i * ElemRatio) :
10247                             (i * ElemRatio + (ElemRatio - 1));
10249     assert(Index < Ops.size() && "Invalid index");
10250     Ops[Index] = In;
10251   }
10253   // The type of the new BUILD_VECTOR node.
10254   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10255   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10256          "Invalid vector size");
10257   // Check if the new vector type is legal.
10258   if (!isTypeLegal(VecVT)) return SDValue();
10260   // Make the new BUILD_VECTOR.
10261   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10263   // The new BUILD_VECTOR node has the potential to be further optimized.
10264   AddToWorklist(BV.getNode());
10265   // Bitcast to the desired type.
10266   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10269 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10270   EVT VT = N->getValueType(0);
10272   unsigned NumInScalars = N->getNumOperands();
10273   SDLoc dl(N);
10275   EVT SrcVT = MVT::Other;
10276   unsigned Opcode = ISD::DELETED_NODE;
10277   unsigned NumDefs = 0;
10279   for (unsigned i = 0; i != NumInScalars; ++i) {
10280     SDValue In = N->getOperand(i);
10281     unsigned Opc = In.getOpcode();
10283     if (Opc == ISD::UNDEF)
10284       continue;
10286     // If all scalar values are floats and converted from integers.
10287     if (Opcode == ISD::DELETED_NODE &&
10288         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10289       Opcode = Opc;
10290     }
10292     if (Opc != Opcode)
10293       return SDValue();
10295     EVT InVT = In.getOperand(0).getValueType();
10297     // If all scalar values are typed differently, bail out. It's chosen to
10298     // simplify BUILD_VECTOR of integer types.
10299     if (SrcVT == MVT::Other)
10300       SrcVT = InVT;
10301     if (SrcVT != InVT)
10302       return SDValue();
10303     NumDefs++;
10304   }
10306   // If the vector has just one element defined, it's not worth to fold it into
10307   // a vectorized one.
10308   if (NumDefs < 2)
10309     return SDValue();
10311   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10312          && "Should only handle conversion from integer to float.");
10313   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10315   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10317   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10318     return SDValue();
10320   SmallVector<SDValue, 8> Opnds;
10321   for (unsigned i = 0; i != NumInScalars; ++i) {
10322     SDValue In = N->getOperand(i);
10324     if (In.getOpcode() == ISD::UNDEF)
10325       Opnds.push_back(DAG.getUNDEF(SrcVT));
10326     else
10327       Opnds.push_back(In.getOperand(0));
10328   }
10329   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10330   AddToWorklist(BV.getNode());
10332   return DAG.getNode(Opcode, dl, VT, BV);
10335 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10336   unsigned NumInScalars = N->getNumOperands();
10337   SDLoc dl(N);
10338   EVT VT = N->getValueType(0);
10340   // A vector built entirely of undefs is undef.
10341   if (ISD::allOperandsUndef(N))
10342     return DAG.getUNDEF(VT);
10344   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10345   if (V.getNode())
10346     return V;
10348   V = reduceBuildVecConvertToConvertBuildVec(N);
10349   if (V.getNode())
10350     return V;
10352   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10353   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10354   // at most two distinct vectors, turn this into a shuffle node.
10356   // May only combine to shuffle after legalize if shuffle is legal.
10357   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
10358     return SDValue();
10360   SDValue VecIn1, VecIn2;
10361   for (unsigned i = 0; i != NumInScalars; ++i) {
10362     // Ignore undef inputs.
10363     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10365     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10366     // constant index, bail out.
10367     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10368         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10369       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10370       break;
10371     }
10373     // We allow up to two distinct input vectors.
10374     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10375     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10376       continue;
10378     if (!VecIn1.getNode()) {
10379       VecIn1 = ExtractedFromVec;
10380     } else if (!VecIn2.getNode()) {
10381       VecIn2 = ExtractedFromVec;
10382     } else {
10383       // Too many inputs.
10384       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10385       break;
10386     }
10387   }
10389   // If everything is good, we can make a shuffle operation.
10390   if (VecIn1.getNode()) {
10391     SmallVector<int, 8> Mask;
10392     for (unsigned i = 0; i != NumInScalars; ++i) {
10393       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10394         Mask.push_back(-1);
10395         continue;
10396       }
10398       // If extracting from the first vector, just use the index directly.
10399       SDValue Extract = N->getOperand(i);
10400       SDValue ExtVal = Extract.getOperand(1);
10401       if (Extract.getOperand(0) == VecIn1) {
10402         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10403         if (ExtIndex > VT.getVectorNumElements())
10404           return SDValue();
10406         Mask.push_back(ExtIndex);
10407         continue;
10408       }
10410       // Otherwise, use InIdx + VecSize
10411       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10412       Mask.push_back(Idx+NumInScalars);
10413     }
10415     // We can't generate a shuffle node with mismatched input and output types.
10416     // Attempt to transform a single input vector to the correct type.
10417     if ((VT != VecIn1.getValueType())) {
10418       // We don't support shuffeling between TWO values of different types.
10419       if (VecIn2.getNode())
10420         return SDValue();
10422       // We only support widening of vectors which are half the size of the
10423       // output registers. For example XMM->YMM widening on X86 with AVX.
10424       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10425         return SDValue();
10427       // If the input vector type has a different base type to the output
10428       // vector type, bail out.
10429       if (VecIn1.getValueType().getVectorElementType() !=
10430           VT.getVectorElementType())
10431         return SDValue();
10433       // Widen the input vector by adding undef values.
10434       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10435                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10436     }
10438     // If VecIn2 is unused then change it to undef.
10439     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10441     // Check that we were able to transform all incoming values to the same
10442     // type.
10443     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10444         VecIn1.getValueType() != VT)
10445           return SDValue();
10447     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10448     if (!isTypeLegal(VT))
10449       return SDValue();
10451     // Return the new VECTOR_SHUFFLE node.
10452     SDValue Ops[2];
10453     Ops[0] = VecIn1;
10454     Ops[1] = VecIn2;
10455     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10456   }
10458   return SDValue();
10461 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10462   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10463   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10464   // inputs come from at most two distinct vectors, turn this into a shuffle
10465   // node.
10467   // If we only have one input vector, we don't need to do any concatenation.
10468   if (N->getNumOperands() == 1)
10469     return N->getOperand(0);
10471   // Check if all of the operands are undefs.
10472   EVT VT = N->getValueType(0);
10473   if (ISD::allOperandsUndef(N))
10474     return DAG.getUNDEF(VT);
10476   // Optimize concat_vectors where one of the vectors is undef.
10477   if (N->getNumOperands() == 2 &&
10478       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10479     SDValue In = N->getOperand(0);
10480     assert(In.getValueType().isVector() && "Must concat vectors");
10482     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10483     if (In->getOpcode() == ISD::BITCAST &&
10484         !In->getOperand(0)->getValueType(0).isVector()) {
10485       SDValue Scalar = In->getOperand(0);
10486       EVT SclTy = Scalar->getValueType(0);
10488       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10489         return SDValue();
10491       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10492                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10493       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10494         return SDValue();
10496       SDLoc dl = SDLoc(N);
10497       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10498       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10499     }
10500   }
10502   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10503   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10504   if (N->getNumOperands() == 2 &&
10505       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10506       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10507     EVT VT = N->getValueType(0);
10508     SDValue N0 = N->getOperand(0);
10509     SDValue N1 = N->getOperand(1);
10510     SmallVector<SDValue, 8> Opnds;
10511     unsigned BuildVecNumElts =  N0.getNumOperands();
10513     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10514     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10515     if (SclTy0.isFloatingPoint()) {
10516       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10517         Opnds.push_back(N0.getOperand(i));
10518       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10519         Opnds.push_back(N1.getOperand(i));
10520     } else {
10521       // If BUILD_VECTOR are from built from integer, they may have different
10522       // operand types. Get the smaller type and truncate all operands to it.
10523       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10524       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10525         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10526                         N0.getOperand(i)));
10527       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10528         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10529                         N1.getOperand(i)));
10530     }
10532     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10533   }
10535   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10536   // nodes often generate nop CONCAT_VECTOR nodes.
10537   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10538   // place the incoming vectors at the exact same location.
10539   SDValue SingleSource = SDValue();
10540   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10542   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10543     SDValue Op = N->getOperand(i);
10545     if (Op.getOpcode() == ISD::UNDEF)
10546       continue;
10548     // Check if this is the identity extract:
10549     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10550       return SDValue();
10552     // Find the single incoming vector for the extract_subvector.
10553     if (SingleSource.getNode()) {
10554       if (Op.getOperand(0) != SingleSource)
10555         return SDValue();
10556     } else {
10557       SingleSource = Op.getOperand(0);
10559       // Check the source type is the same as the type of the result.
10560       // If not, this concat may extend the vector, so we can not
10561       // optimize it away.
10562       if (SingleSource.getValueType() != N->getValueType(0))
10563         return SDValue();
10564     }
10566     unsigned IdentityIndex = i * PartNumElem;
10567     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10568     // The extract index must be constant.
10569     if (!CS)
10570       return SDValue();
10572     // Check that we are reading from the identity index.
10573     if (CS->getZExtValue() != IdentityIndex)
10574       return SDValue();
10575   }
10577   if (SingleSource.getNode())
10578     return SingleSource;
10580   return SDValue();
10583 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10584   EVT NVT = N->getValueType(0);
10585   SDValue V = N->getOperand(0);
10587   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10588     // Combine:
10589     //    (extract_subvec (concat V1, V2, ...), i)
10590     // Into:
10591     //    Vi if possible
10592     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10593     // type.
10594     if (V->getOperand(0).getValueType() != NVT)
10595       return SDValue();
10596     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10597     unsigned NumElems = NVT.getVectorNumElements();
10598     assert((Idx % NumElems) == 0 &&
10599            "IDX in concat is not a multiple of the result vector length.");
10600     return V->getOperand(Idx / NumElems);
10601   }
10603   // Skip bitcasting
10604   if (V->getOpcode() == ISD::BITCAST)
10605     V = V.getOperand(0);
10607   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10608     SDLoc dl(N);
10609     // Handle only simple case where vector being inserted and vector
10610     // being extracted are of same type, and are half size of larger vectors.
10611     EVT BigVT = V->getOperand(0).getValueType();
10612     EVT SmallVT = V->getOperand(1).getValueType();
10613     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10614       return SDValue();
10616     // Only handle cases where both indexes are constants with the same type.
10617     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10618     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10620     if (InsIdx && ExtIdx &&
10621         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10622         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10623       // Combine:
10624       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10625       // Into:
10626       //    indices are equal or bit offsets are equal => V1
10627       //    otherwise => (extract_subvec V1, ExtIdx)
10628       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10629           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10630         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10631       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10632                          DAG.getNode(ISD::BITCAST, dl,
10633                                      N->getOperand(0).getValueType(),
10634                                      V->getOperand(0)), N->getOperand(1));
10635     }
10636   }
10638   return SDValue();
10641 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10642 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10643   EVT VT = N->getValueType(0);
10644   unsigned NumElts = VT.getVectorNumElements();
10646   SDValue N0 = N->getOperand(0);
10647   SDValue N1 = N->getOperand(1);
10648   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10650   SmallVector<SDValue, 4> Ops;
10651   EVT ConcatVT = N0.getOperand(0).getValueType();
10652   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10653   unsigned NumConcats = NumElts / NumElemsPerConcat;
10655   // Look at every vector that's inserted. We're looking for exact
10656   // subvector-sized copies from a concatenated vector
10657   for (unsigned I = 0; I != NumConcats; ++I) {
10658     // Make sure we're dealing with a copy.
10659     unsigned Begin = I * NumElemsPerConcat;
10660     bool AllUndef = true, NoUndef = true;
10661     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10662       if (SVN->getMaskElt(J) >= 0)
10663         AllUndef = false;
10664       else
10665         NoUndef = false;
10666     }
10668     if (NoUndef) {
10669       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10670         return SDValue();
10672       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10673         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10674           return SDValue();
10676       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10677       if (FirstElt < N0.getNumOperands())
10678         Ops.push_back(N0.getOperand(FirstElt));
10679       else
10680         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10682     } else if (AllUndef) {
10683       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10684     } else { // Mixed with general masks and undefs, can't do optimization.
10685       return SDValue();
10686     }
10687   }
10689   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10692 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10693   EVT VT = N->getValueType(0);
10694   unsigned NumElts = VT.getVectorNumElements();
10696   SDValue N0 = N->getOperand(0);
10697   SDValue N1 = N->getOperand(1);
10699   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10701   // Canonicalize shuffle undef, undef -> undef
10702   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10703     return DAG.getUNDEF(VT);
10705   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10707   // Canonicalize shuffle v, v -> v, undef
10708   if (N0 == N1) {
10709     SmallVector<int, 8> NewMask;
10710     for (unsigned i = 0; i != NumElts; ++i) {
10711       int Idx = SVN->getMaskElt(i);
10712       if (Idx >= (int)NumElts) Idx -= NumElts;
10713       NewMask.push_back(Idx);
10714     }
10715     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10716                                 &NewMask[0]);
10717   }
10719   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10720   if (N0.getOpcode() == ISD::UNDEF) {
10721     SmallVector<int, 8> NewMask;
10722     for (unsigned i = 0; i != NumElts; ++i) {
10723       int Idx = SVN->getMaskElt(i);
10724       if (Idx >= 0) {
10725         if (Idx >= (int)NumElts)
10726           Idx -= NumElts;
10727         else
10728           Idx = -1; // remove reference to lhs
10729       }
10730       NewMask.push_back(Idx);
10731     }
10732     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10733                                 &NewMask[0]);
10734   }
10736   // Remove references to rhs if it is undef
10737   if (N1.getOpcode() == ISD::UNDEF) {
10738     bool Changed = false;
10739     SmallVector<int, 8> NewMask;
10740     for (unsigned i = 0; i != NumElts; ++i) {
10741       int Idx = SVN->getMaskElt(i);
10742       if (Idx >= (int)NumElts) {
10743         Idx = -1;
10744         Changed = true;
10745       }
10746       NewMask.push_back(Idx);
10747     }
10748     if (Changed)
10749       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10750   }
10752   // If it is a splat, check if the argument vector is another splat or a
10753   // build_vector with all scalar elements the same.
10754   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10755     SDNode *V = N0.getNode();
10757     // If this is a bit convert that changes the element type of the vector but
10758     // not the number of vector elements, look through it.  Be careful not to
10759     // look though conversions that change things like v4f32 to v2f64.
10760     if (V->getOpcode() == ISD::BITCAST) {
10761       SDValue ConvInput = V->getOperand(0);
10762       if (ConvInput.getValueType().isVector() &&
10763           ConvInput.getValueType().getVectorNumElements() == NumElts)
10764         V = ConvInput.getNode();
10765     }
10767     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10768       assert(V->getNumOperands() == NumElts &&
10769              "BUILD_VECTOR has wrong number of operands");
10770       SDValue Base;
10771       bool AllSame = true;
10772       for (unsigned i = 0; i != NumElts; ++i) {
10773         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10774           Base = V->getOperand(i);
10775           break;
10776         }
10777       }
10778       // Splat of <u, u, u, u>, return <u, u, u, u>
10779       if (!Base.getNode())
10780         return N0;
10781       for (unsigned i = 0; i != NumElts; ++i) {
10782         if (V->getOperand(i) != Base) {
10783           AllSame = false;
10784           break;
10785         }
10786       }
10787       // Splat of <x, x, x, x>, return <x, x, x, x>
10788       if (AllSame)
10789         return N0;
10790     }
10791   }
10793   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10794       Level < AfterLegalizeVectorOps &&
10795       (N1.getOpcode() == ISD::UNDEF ||
10796       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10797        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10798     SDValue V = partitionShuffleOfConcats(N, DAG);
10800     if (V.getNode())
10801       return V;
10802   }
10804   // If this shuffle node is simply a swizzle of another shuffle node,
10805   // then try to simplify it.
10806   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10807       N1.getOpcode() == ISD::UNDEF) {
10809     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10811     // The incoming shuffle must be of the same type as the result of the
10812     // current shuffle.
10813     assert(OtherSV->getOperand(0).getValueType() == VT &&
10814            "Shuffle types don't match");
10816     SmallVector<int, 4> Mask;
10817     // Compute the combined shuffle mask.
10818     for (unsigned i = 0; i != NumElts; ++i) {
10819       int Idx = SVN->getMaskElt(i);
10820       assert(Idx < (int)NumElts && "Index references undef operand");
10821       // Next, this index comes from the first value, which is the incoming
10822       // shuffle. Adopt the incoming index.
10823       if (Idx >= 0)
10824         Idx = OtherSV->getMaskElt(Idx);
10825       Mask.push_back(Idx);
10826     }
10828     // Check if all indices in Mask are Undef. In case, propagate Undef.
10829     bool isUndefMask = true;
10830     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10831       isUndefMask &= Mask[i] < 0;
10833     if (isUndefMask)
10834       return DAG.getUNDEF(VT);
10835     
10836     bool CommuteOperands = false;
10837     if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10838       // To be valid, the combine shuffle mask should only reference elements
10839       // from one of the two vectors in input to the inner shufflevector.
10840       bool IsValidMask = true;
10841       for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10842         // See if the combined mask only reference undefs or elements coming
10843         // from the first shufflevector operand.
10844         IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
10846       if (!IsValidMask) {
10847         IsValidMask = true;
10848         for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10849           // Check that all the elements come from the second shuffle operand.
10850           IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10851         CommuteOperands = IsValidMask;
10852       }
10854       // Early exit if the combined shuffle mask is not valid.
10855       if (!IsValidMask)
10856         return SDValue();
10857     }
10859     // See if this pair of shuffles can be safely folded according to either
10860     // of the following rules:
10861     //   shuffle(shuffle(x, y), undef) -> x
10862     //   shuffle(shuffle(x, undef), undef) -> x
10863     //   shuffle(shuffle(x, y), undef) -> y
10864     bool IsIdentityMask = true;
10865     unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
10866     for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10867       // Skip Undefs.
10868       if (Mask[i] < 0)
10869         continue;
10871       // The combined shuffle must map each index to itself.
10872       IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
10873     }
10874     
10875     if (IsIdentityMask) {
10876       if (CommuteOperands)
10877         // optimize shuffle(shuffle(x, y), undef) -> y.
10878         return OtherSV->getOperand(1);
10879       
10880       // optimize shuffle(shuffle(x, undef), undef) -> x
10881       // optimize shuffle(shuffle(x, y), undef) -> x
10882       return OtherSV->getOperand(0);
10883     }
10885     // It may still be beneficial to combine the two shuffles if the
10886     // resulting shuffle is legal.
10887     if (TLI.isTypeLegal(VT)) {
10888       if (!CommuteOperands) {
10889         if (TLI.isShuffleMaskLegal(Mask, VT))
10890           // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10891           // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10892           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10893                                       &Mask[0]);
10894       } else {
10895         // Compute the commuted shuffle mask.
10896         for (unsigned i = 0; i != NumElts; ++i) {
10897           int idx = Mask[i];
10898           if (idx < 0)
10899             continue;
10900           else if (idx < (int)NumElts)
10901             Mask[i] = idx + NumElts;
10902           else
10903             Mask[i] = idx - NumElts;
10904         }
10906         if (TLI.isShuffleMaskLegal(Mask, VT))
10907           //   shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(y, undef, M3)
10908           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(1), N1,
10909                                       &Mask[0]);
10910       }
10911     }
10912   }
10914   // Canonicalize shuffles according to rules:
10915   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10916   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10917   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10918   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10919       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10920       TLI.isTypeLegal(VT)) {
10921     // The incoming shuffle must be of the same type as the result of the
10922     // current shuffle.
10923     assert(N1->getOperand(0).getValueType() == VT &&
10924            "Shuffle types don't match");
10926     SDValue SV0 = N1->getOperand(0);
10927     SDValue SV1 = N1->getOperand(1);
10928     bool HasSameOp0 = N0 == SV0;
10929     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10930     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10931       // Commute the operands of this shuffle so that next rule
10932       // will trigger.
10933       return DAG.getCommutedVectorShuffle(*SVN);
10934   }
10936   // Try to fold according to rules:
10937   //   shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10938   //   shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10939   //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10940   //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10941   // Don't try to fold shuffles with illegal type.
10942   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10943       N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
10944     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10946     // The incoming shuffle must be of the same type as the result of the
10947     // current shuffle.
10948     assert(OtherSV->getOperand(0).getValueType() == VT &&
10949            "Shuffle types don't match");
10951     SDValue SV0 = OtherSV->getOperand(0);
10952     SDValue SV1 = OtherSV->getOperand(1);
10953     bool HasSameOp0 = N1 == SV0;
10954     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10955     if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
10956       // Early exit.
10957       return SDValue();
10959     SmallVector<int, 4> Mask;
10960     // Compute the combined shuffle mask for a shuffle with SV0 as the first
10961     // operand, and SV1 as the second operand.
10962     for (unsigned i = 0; i != NumElts; ++i) {
10963       int Idx = SVN->getMaskElt(i);
10964       if (Idx < 0) {
10965         // Propagate Undef.
10966         Mask.push_back(Idx);
10967         continue;
10968       }
10970       if (Idx < (int)NumElts) {
10971         Idx = OtherSV->getMaskElt(Idx);
10972         if (IsSV1Undef && Idx >= (int) NumElts)
10973           Idx = -1;  // Propagate Undef.
10974       } else
10975         Idx = HasSameOp0 ? Idx - NumElts : Idx;
10977       Mask.push_back(Idx);
10978     }
10980     // Check if all indices in Mask are Undef. In case, propagate Undef.
10981     bool isUndefMask = true;
10982     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10983       isUndefMask &= Mask[i] < 0;
10985     if (isUndefMask)
10986       return DAG.getUNDEF(VT);
10988     // Avoid introducing shuffles with illegal mask.
10989     if (TLI.isShuffleMaskLegal(Mask, VT)) {
10990       if (IsSV1Undef)
10991         //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10992         //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10993         return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
10994       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
10995     }
10996   }
10998   return SDValue();
11001 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11002   SDValue N0 = N->getOperand(0);
11003   SDValue N2 = N->getOperand(2);
11005   // If the input vector is a concatenation, and the insert replaces
11006   // one of the halves, we can optimize into a single concat_vectors.
11007   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11008       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11009     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11010     EVT VT = N->getValueType(0);
11012     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11013     // (concat_vectors Z, Y)
11014     if (InsIdx == 0)
11015       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11016                          N->getOperand(1), N0.getOperand(1));
11018     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11019     // (concat_vectors X, Z)
11020     if (InsIdx == VT.getVectorNumElements()/2)
11021       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11022                          N0.getOperand(0), N->getOperand(1));
11023   }
11025   return SDValue();
11028 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11029 /// with the destination vector and a zero vector.
11030 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11031 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
11032 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11033   EVT VT = N->getValueType(0);
11034   SDLoc dl(N);
11035   SDValue LHS = N->getOperand(0);
11036   SDValue RHS = N->getOperand(1);
11037   if (N->getOpcode() == ISD::AND) {
11038     if (RHS.getOpcode() == ISD::BITCAST)
11039       RHS = RHS.getOperand(0);
11040     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11041       SmallVector<int, 8> Indices;
11042       unsigned NumElts = RHS.getNumOperands();
11043       for (unsigned i = 0; i != NumElts; ++i) {
11044         SDValue Elt = RHS.getOperand(i);
11045         if (!isa<ConstantSDNode>(Elt))
11046           return SDValue();
11048         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11049           Indices.push_back(i);
11050         else if (cast<ConstantSDNode>(Elt)->isNullValue())
11051           Indices.push_back(NumElts);
11052         else
11053           return SDValue();
11054       }
11056       // Let's see if the target supports this vector_shuffle.
11057       EVT RVT = RHS.getValueType();
11058       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11059         return SDValue();
11061       // Return the new VECTOR_SHUFFLE node.
11062       EVT EltVT = RVT.getVectorElementType();
11063       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11064                                      DAG.getConstant(0, EltVT));
11065       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11066       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11067       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11068       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11069     }
11070   }
11072   return SDValue();
11075 /// Visit a binary vector operation, like ADD.
11076 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11077   assert(N->getValueType(0).isVector() &&
11078          "SimplifyVBinOp only works on vectors!");
11080   SDValue LHS = N->getOperand(0);
11081   SDValue RHS = N->getOperand(1);
11082   SDValue Shuffle = XformToShuffleWithZero(N);
11083   if (Shuffle.getNode()) return Shuffle;
11085   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11086   // this operation.
11087   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11088       RHS.getOpcode() == ISD::BUILD_VECTOR) {
11089     // Check if both vectors are constants. If not bail out.
11090     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11091           cast<BuildVectorSDNode>(RHS)->isConstant()))
11092       return SDValue();
11094     SmallVector<SDValue, 8> Ops;
11095     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11096       SDValue LHSOp = LHS.getOperand(i);
11097       SDValue RHSOp = RHS.getOperand(i);
11099       // Can't fold divide by zero.
11100       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11101           N->getOpcode() == ISD::FDIV) {
11102         if ((RHSOp.getOpcode() == ISD::Constant &&
11103              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11104             (RHSOp.getOpcode() == ISD::ConstantFP &&
11105              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11106           break;
11107       }
11109       EVT VT = LHSOp.getValueType();
11110       EVT RVT = RHSOp.getValueType();
11111       if (RVT != VT) {
11112         // Integer BUILD_VECTOR operands may have types larger than the element
11113         // size (e.g., when the element type is not legal).  Prior to type
11114         // legalization, the types may not match between the two BUILD_VECTORS.
11115         // Truncate one of the operands to make them match.
11116         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11117           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11118         } else {
11119           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11120           VT = RVT;
11121         }
11122       }
11123       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11124                                    LHSOp, RHSOp);
11125       if (FoldOp.getOpcode() != ISD::UNDEF &&
11126           FoldOp.getOpcode() != ISD::Constant &&
11127           FoldOp.getOpcode() != ISD::ConstantFP)
11128         break;
11129       Ops.push_back(FoldOp);
11130       AddToWorklist(FoldOp.getNode());
11131     }
11133     if (Ops.size() == LHS.getNumOperands())
11134       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11135   }
11137   // Type legalization might introduce new shuffles in the DAG.
11138   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11139   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
11140   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11141       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11142       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11143       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11144     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11145     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11147     if (SVN0->getMask().equals(SVN1->getMask())) {
11148       EVT VT = N->getValueType(0);
11149       SDValue UndefVector = LHS.getOperand(1);
11150       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11151                                      LHS.getOperand(0), RHS.getOperand(0));
11152       AddUsersToWorklist(N);
11153       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11154                                   &SVN0->getMask()[0]);
11155     }
11156   }
11158   return SDValue();
11161 /// Visit a binary vector operation, like FABS/FNEG.
11162 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11163   assert(N->getValueType(0).isVector() &&
11164          "SimplifyVUnaryOp only works on vectors!");
11166   SDValue N0 = N->getOperand(0);
11168   if (N0.getOpcode() != ISD::BUILD_VECTOR)
11169     return SDValue();
11171   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11172   SmallVector<SDValue, 8> Ops;
11173   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11174     SDValue Op = N0.getOperand(i);
11175     if (Op.getOpcode() != ISD::UNDEF &&
11176         Op.getOpcode() != ISD::ConstantFP)
11177       break;
11178     EVT EltVT = Op.getValueType();
11179     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11180     if (FoldOp.getOpcode() != ISD::UNDEF &&
11181         FoldOp.getOpcode() != ISD::ConstantFP)
11182       break;
11183     Ops.push_back(FoldOp);
11184     AddToWorklist(FoldOp.getNode());
11185   }
11187   if (Ops.size() != N0.getNumOperands())
11188     return SDValue();
11190   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11193 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11194                                     SDValue N1, SDValue N2){
11195   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11197   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11198                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11200   // If we got a simplified select_cc node back from SimplifySelectCC, then
11201   // break it down into a new SETCC node, and a new SELECT node, and then return
11202   // the SELECT node, since we were called with a SELECT node.
11203   if (SCC.getNode()) {
11204     // Check to see if we got a select_cc back (to turn into setcc/select).
11205     // Otherwise, just return whatever node we got back, like fabs.
11206     if (SCC.getOpcode() == ISD::SELECT_CC) {
11207       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11208                                   N0.getValueType(),
11209                                   SCC.getOperand(0), SCC.getOperand(1),
11210                                   SCC.getOperand(4));
11211       AddToWorklist(SETCC.getNode());
11212       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11213                            SCC.getOperand(2), SCC.getOperand(3));
11214     }
11216     return SCC;
11217   }
11218   return SDValue();
11221 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11222 /// being selected between, see if we can simplify the select.  Callers of this
11223 /// should assume that TheSelect is deleted if this returns true.  As such, they
11224 /// should return the appropriate thing (e.g. the node) back to the top-level of
11225 /// the DAG combiner loop to avoid it being looked at.
11226 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11227                                     SDValue RHS) {
11229   // Cannot simplify select with vector condition
11230   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11232   // If this is a select from two identical things, try to pull the operation
11233   // through the select.
11234   if (LHS.getOpcode() != RHS.getOpcode() ||
11235       !LHS.hasOneUse() || !RHS.hasOneUse())
11236     return false;
11238   // If this is a load and the token chain is identical, replace the select
11239   // of two loads with a load through a select of the address to load from.
11240   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11241   // constants have been dropped into the constant pool.
11242   if (LHS.getOpcode() == ISD::LOAD) {
11243     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11244     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11246     // Token chains must be identical.
11247     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11248         // Do not let this transformation reduce the number of volatile loads.
11249         LLD->isVolatile() || RLD->isVolatile() ||
11250         // If this is an EXTLOAD, the VT's must match.
11251         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11252         // If this is an EXTLOAD, the kind of extension must match.
11253         (LLD->getExtensionType() != RLD->getExtensionType() &&
11254          // The only exception is if one of the extensions is anyext.
11255          LLD->getExtensionType() != ISD::EXTLOAD &&
11256          RLD->getExtensionType() != ISD::EXTLOAD) ||
11257         // FIXME: this discards src value information.  This is
11258         // over-conservative. It would be beneficial to be able to remember
11259         // both potential memory locations.  Since we are discarding
11260         // src value info, don't do the transformation if the memory
11261         // locations are not in the default address space.
11262         LLD->getPointerInfo().getAddrSpace() != 0 ||
11263         RLD->getPointerInfo().getAddrSpace() != 0 ||
11264         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11265                                       LLD->getBasePtr().getValueType()))
11266       return false;
11268     // Check that the select condition doesn't reach either load.  If so,
11269     // folding this will induce a cycle into the DAG.  If not, this is safe to
11270     // xform, so create a select of the addresses.
11271     SDValue Addr;
11272     if (TheSelect->getOpcode() == ISD::SELECT) {
11273       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11274       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11275           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11276         return false;
11277       // The loads must not depend on one another.
11278       if (LLD->isPredecessorOf(RLD) ||
11279           RLD->isPredecessorOf(LLD))
11280         return false;
11281       Addr = DAG.getSelect(SDLoc(TheSelect),
11282                            LLD->getBasePtr().getValueType(),
11283                            TheSelect->getOperand(0), LLD->getBasePtr(),
11284                            RLD->getBasePtr());
11285     } else {  // Otherwise SELECT_CC
11286       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11287       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11289       if ((LLD->hasAnyUseOfValue(1) &&
11290            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11291           (RLD->hasAnyUseOfValue(1) &&
11292            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11293         return false;
11295       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11296                          LLD->getBasePtr().getValueType(),
11297                          TheSelect->getOperand(0),
11298                          TheSelect->getOperand(1),
11299                          LLD->getBasePtr(), RLD->getBasePtr(),
11300                          TheSelect->getOperand(4));
11301     }
11303     SDValue Load;
11304     // It is safe to replace the two loads if they have different alignments,
11305     // but the new load must be the minimum (most restrictive) alignment of the
11306     // inputs.
11307     bool isInvariant = LLD->getAlignment() & RLD->getAlignment();
11308     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11309     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11310       Load = DAG.getLoad(TheSelect->getValueType(0),
11311                          SDLoc(TheSelect),
11312                          // FIXME: Discards pointer and AA info.
11313                          LLD->getChain(), Addr, MachinePointerInfo(),
11314                          LLD->isVolatile(), LLD->isNonTemporal(),
11315                          isInvariant, Alignment);
11316     } else {
11317       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11318                             RLD->getExtensionType() : LLD->getExtensionType(),
11319                             SDLoc(TheSelect),
11320                             TheSelect->getValueType(0),
11321                             // FIXME: Discards pointer and AA info.
11322                             LLD->getChain(), Addr, MachinePointerInfo(),
11323                             LLD->getMemoryVT(), LLD->isVolatile(),
11324                             LLD->isNonTemporal(), isInvariant, Alignment);
11325     }
11327     // Users of the select now use the result of the load.
11328     CombineTo(TheSelect, Load);
11330     // Users of the old loads now use the new load's chain.  We know the
11331     // old-load value is dead now.
11332     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11333     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11334     return true;
11335   }
11337   return false;
11340 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
11341 /// where 'cond' is the comparison specified by CC.
11342 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11343                                       SDValue N2, SDValue N3,
11344                                       ISD::CondCode CC, bool NotExtCompare) {
11345   // (x ? y : y) -> y.
11346   if (N2 == N3) return N2;
11348   EVT VT = N2.getValueType();
11349   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11350   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11351   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11353   // Determine if the condition we're dealing with is constant
11354   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11355                               N0, N1, CC, DL, false);
11356   if (SCC.getNode()) AddToWorklist(SCC.getNode());
11357   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11359   // fold select_cc true, x, y -> x
11360   if (SCCC && !SCCC->isNullValue())
11361     return N2;
11362   // fold select_cc false, x, y -> y
11363   if (SCCC && SCCC->isNullValue())
11364     return N3;
11366   // Check to see if we can simplify the select into an fabs node
11367   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11368     // Allow either -0.0 or 0.0
11369     if (CFP->getValueAPF().isZero()) {
11370       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11371       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11372           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11373           N2 == N3.getOperand(0))
11374         return DAG.getNode(ISD::FABS, DL, VT, N0);
11376       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11377       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11378           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11379           N2.getOperand(0) == N3)
11380         return DAG.getNode(ISD::FABS, DL, VT, N3);
11381     }
11382   }
11384   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11385   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11386   // in it.  This is a win when the constant is not otherwise available because
11387   // it replaces two constant pool loads with one.  We only do this if the FP
11388   // type is known to be legal, because if it isn't, then we are before legalize
11389   // types an we want the other legalization to happen first (e.g. to avoid
11390   // messing with soft float) and if the ConstantFP is not legal, because if
11391   // it is legal, we may not need to store the FP constant in a constant pool.
11392   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11393     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11394       if (TLI.isTypeLegal(N2.getValueType()) &&
11395           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11396                TargetLowering::Legal &&
11397            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11398            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11399           // If both constants have multiple uses, then we won't need to do an
11400           // extra load, they are likely around in registers for other users.
11401           (TV->hasOneUse() || FV->hasOneUse())) {
11402         Constant *Elts[] = {
11403           const_cast<ConstantFP*>(FV->getConstantFPValue()),
11404           const_cast<ConstantFP*>(TV->getConstantFPValue())
11405         };
11406         Type *FPTy = Elts[0]->getType();
11407         const DataLayout &TD = *TLI.getDataLayout();
11409         // Create a ConstantArray of the two constants.
11410         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11411         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11412                                             TD.getPrefTypeAlignment(FPTy));
11413         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11415         // Get the offsets to the 0 and 1 element of the array so that we can
11416         // select between them.
11417         SDValue Zero = DAG.getIntPtrConstant(0);
11418         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11419         SDValue One = DAG.getIntPtrConstant(EltSize);
11421         SDValue Cond = DAG.getSetCC(DL,
11422                                     getSetCCResultType(N0.getValueType()),
11423                                     N0, N1, CC);
11424         AddToWorklist(Cond.getNode());
11425         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11426                                           Cond, One, Zero);
11427         AddToWorklist(CstOffset.getNode());
11428         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11429                             CstOffset);
11430         AddToWorklist(CPIdx.getNode());
11431         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11432                            MachinePointerInfo::getConstantPool(), false,
11433                            false, false, Alignment);
11435       }
11436     }
11438   // Check to see if we can perform the "gzip trick", transforming
11439   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11440   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11441       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11442        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11443     EVT XType = N0.getValueType();
11444     EVT AType = N2.getValueType();
11445     if (XType.bitsGE(AType)) {
11446       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11447       // single-bit constant.
11448       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11449         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11450         ShCtV = XType.getSizeInBits()-ShCtV-1;
11451         SDValue ShCt = DAG.getConstant(ShCtV,
11452                                        getShiftAmountTy(N0.getValueType()));
11453         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11454                                     XType, N0, ShCt);
11455         AddToWorklist(Shift.getNode());
11457         if (XType.bitsGT(AType)) {
11458           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11459           AddToWorklist(Shift.getNode());
11460         }
11462         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11463       }
11465       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11466                                   XType, N0,
11467                                   DAG.getConstant(XType.getSizeInBits()-1,
11468                                          getShiftAmountTy(N0.getValueType())));
11469       AddToWorklist(Shift.getNode());
11471       if (XType.bitsGT(AType)) {
11472         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11473         AddToWorklist(Shift.getNode());
11474       }
11476       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11477     }
11478   }
11480   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11481   // where y is has a single bit set.
11482   // A plaintext description would be, we can turn the SELECT_CC into an AND
11483   // when the condition can be materialized as an all-ones register.  Any
11484   // single bit-test can be materialized as an all-ones register with
11485   // shift-left and shift-right-arith.
11486   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11487       N0->getValueType(0) == VT &&
11488       N1C && N1C->isNullValue() &&
11489       N2C && N2C->isNullValue()) {
11490     SDValue AndLHS = N0->getOperand(0);
11491     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11492     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11493       // Shift the tested bit over the sign bit.
11494       APInt AndMask = ConstAndRHS->getAPIntValue();
11495       SDValue ShlAmt =
11496         DAG.getConstant(AndMask.countLeadingZeros(),
11497                         getShiftAmountTy(AndLHS.getValueType()));
11498       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11500       // Now arithmetic right shift it all the way over, so the result is either
11501       // all-ones, or zero.
11502       SDValue ShrAmt =
11503         DAG.getConstant(AndMask.getBitWidth()-1,
11504                         getShiftAmountTy(Shl.getValueType()));
11505       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11507       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11508     }
11509   }
11511   // fold select C, 16, 0 -> shl C, 4
11512   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11513       TLI.getBooleanContents(N0.getValueType()) ==
11514           TargetLowering::ZeroOrOneBooleanContent) {
11516     // If the caller doesn't want us to simplify this into a zext of a compare,
11517     // don't do it.
11518     if (NotExtCompare && N2C->getAPIntValue() == 1)
11519       return SDValue();
11521     // Get a SetCC of the condition
11522     // NOTE: Don't create a SETCC if it's not legal on this target.
11523     if (!LegalOperations ||
11524         TLI.isOperationLegal(ISD::SETCC,
11525           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11526       SDValue Temp, SCC;
11527       // cast from setcc result type to select result type
11528       if (LegalTypes) {
11529         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11530                             N0, N1, CC);
11531         if (N2.getValueType().bitsLT(SCC.getValueType()))
11532           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11533                                         N2.getValueType());
11534         else
11535           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11536                              N2.getValueType(), SCC);
11537       } else {
11538         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11539         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11540                            N2.getValueType(), SCC);
11541       }
11543       AddToWorklist(SCC.getNode());
11544       AddToWorklist(Temp.getNode());
11546       if (N2C->getAPIntValue() == 1)
11547         return Temp;
11549       // shl setcc result by log2 n2c
11550       return DAG.getNode(
11551           ISD::SHL, DL, N2.getValueType(), Temp,
11552           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11553                           getShiftAmountTy(Temp.getValueType())));
11554     }
11555   }
11557   // Check to see if this is the equivalent of setcc
11558   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11559   // otherwise, go ahead with the folds.
11560   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11561     EVT XType = N0.getValueType();
11562     if (!LegalOperations ||
11563         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11564       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11565       if (Res.getValueType() != VT)
11566         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11567       return Res;
11568     }
11570     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11571     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11572         (!LegalOperations ||
11573          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11574       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11575       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11576                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11577                                        getShiftAmountTy(Ctlz.getValueType())));
11578     }
11579     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11580     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11581       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11582                                   XType, DAG.getConstant(0, XType), N0);
11583       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11584       return DAG.getNode(ISD::SRL, DL, XType,
11585                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11586                          DAG.getConstant(XType.getSizeInBits()-1,
11587                                          getShiftAmountTy(XType)));
11588     }
11589     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11590     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11591       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11592                                  DAG.getConstant(XType.getSizeInBits()-1,
11593                                          getShiftAmountTy(N0.getValueType())));
11594       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11595     }
11596   }
11598   // Check to see if this is an integer abs.
11599   // select_cc setg[te] X,  0,  X, -X ->
11600   // select_cc setgt    X, -1,  X, -X ->
11601   // select_cc setl[te] X,  0, -X,  X ->
11602   // select_cc setlt    X,  1, -X,  X ->
11603   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11604   if (N1C) {
11605     ConstantSDNode *SubC = nullptr;
11606     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11607          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11608         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11609       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11610     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11611               (N1C->isOne() && CC == ISD::SETLT)) &&
11612              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11613       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11615     EVT XType = N0.getValueType();
11616     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11617       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11618                                   N0,
11619                                   DAG.getConstant(XType.getSizeInBits()-1,
11620                                          getShiftAmountTy(N0.getValueType())));
11621       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11622                                 XType, N0, Shift);
11623       AddToWorklist(Shift.getNode());
11624       AddToWorklist(Add.getNode());
11625       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11626     }
11627   }
11629   return SDValue();
11632 /// This is a stub for TargetLowering::SimplifySetCC.
11633 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11634                                    SDValue N1, ISD::CondCode Cond,
11635                                    SDLoc DL, bool foldBooleans) {
11636   TargetLowering::DAGCombinerInfo
11637     DagCombineInfo(DAG, Level, false, this);
11638   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11641 /// Given an ISD::SDIV node expressing a divide by constant, return
11642 /// a DAG expression to select that will generate the same value by multiplying
11643 /// by a magic number.  See:
11644 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11645 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11646   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11647   if (!C)
11648     return SDValue();
11650   // Avoid division by zero.
11651   if (!C->getAPIntValue())
11652     return SDValue();
11654   std::vector<SDNode*> Built;
11655   SDValue S =
11656       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11658   for (SDNode *N : Built)
11659     AddToWorklist(N);
11660   return S;
11663 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
11664 /// DAG expression that will generate the same value by right shifting.
11665 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11666   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11667   if (!C)
11668     return SDValue();
11670   // Avoid division by zero.
11671   if (!C->getAPIntValue())
11672     return SDValue();
11674   std::vector<SDNode *> Built;
11675   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11677   for (SDNode *N : Built)
11678     AddToWorklist(N);
11679   return S;
11682 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
11683 /// expression that will generate the same value by multiplying by a magic
11684 /// number. See:
11685 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11686 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11687   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11688   if (!C)
11689     return SDValue();
11691   // Avoid division by zero.
11692   if (!C->getAPIntValue())
11693     return SDValue();
11695   std::vector<SDNode*> Built;
11696   SDValue S =
11697       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11699   for (SDNode *N : Built)
11700     AddToWorklist(N);
11701   return S;
11704 /// Return true if base is a frame index, which is known not to alias with
11705 /// anything but itself.  Provides base object and offset as results.
11706 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11707                            const GlobalValue *&GV, const void *&CV) {
11708   // Assume it is a primitive operation.
11709   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11711   // If it's an adding a simple constant then integrate the offset.
11712   if (Base.getOpcode() == ISD::ADD) {
11713     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11714       Base = Base.getOperand(0);
11715       Offset += C->getZExtValue();
11716     }
11717   }
11719   // Return the underlying GlobalValue, and update the Offset.  Return false
11720   // for GlobalAddressSDNode since the same GlobalAddress may be represented
11721   // by multiple nodes with different offsets.
11722   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11723     GV = G->getGlobal();
11724     Offset += G->getOffset();
11725     return false;
11726   }
11728   // Return the underlying Constant value, and update the Offset.  Return false
11729   // for ConstantSDNodes since the same constant pool entry may be represented
11730   // by multiple nodes with different offsets.
11731   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11732     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11733                                          : (const void *)C->getConstVal();
11734     Offset += C->getOffset();
11735     return false;
11736   }
11737   // If it's any of the following then it can't alias with anything but itself.
11738   return isa<FrameIndexSDNode>(Base);
11741 /// Return true if there is any possibility that the two addresses overlap.
11742 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11743   // If they are the same then they must be aliases.
11744   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11746   // If they are both volatile then they cannot be reordered.
11747   if (Op0->isVolatile() && Op1->isVolatile()) return true;
11749   // Gather base node and offset information.
11750   SDValue Base1, Base2;
11751   int64_t Offset1, Offset2;
11752   const GlobalValue *GV1, *GV2;
11753   const void *CV1, *CV2;
11754   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11755                                       Base1, Offset1, GV1, CV1);
11756   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11757                                       Base2, Offset2, GV2, CV2);
11759   // If they have a same base address then check to see if they overlap.
11760   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11761     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11762              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11764   // It is possible for different frame indices to alias each other, mostly
11765   // when tail call optimization reuses return address slots for arguments.
11766   // To catch this case, look up the actual index of frame indices to compute
11767   // the real alias relationship.
11768   if (isFrameIndex1 && isFrameIndex2) {
11769     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11770     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11771     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11772     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11773              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11774   }
11776   // Otherwise, if we know what the bases are, and they aren't identical, then
11777   // we know they cannot alias.
11778   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11779     return false;
11781   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11782   // compared to the size and offset of the access, we may be able to prove they
11783   // do not alias.  This check is conservative for now to catch cases created by
11784   // splitting vector types.
11785   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11786       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11787       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11788        Op1->getMemoryVT().getSizeInBits() >> 3) &&
11789       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11790     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11791     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11793     // There is no overlap between these relatively aligned accesses of similar
11794     // size, return no alias.
11795     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11796         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11797       return false;
11798   }
11800   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11801     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11802 #ifndef NDEBUG
11803   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11804       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11805     UseAA = false;
11806 #endif
11807   if (UseAA &&
11808       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11809     // Use alias analysis information.
11810     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11811                                  Op1->getSrcValueOffset());
11812     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11813         Op0->getSrcValueOffset() - MinOffset;
11814     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11815         Op1->getSrcValueOffset() - MinOffset;
11816     AliasAnalysis::AliasResult AAResult =
11817         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11818                                          Overlap1,
11819                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
11820                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11821                                          Overlap2,
11822                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
11823     if (AAResult == AliasAnalysis::NoAlias)
11824       return false;
11825   }
11827   // Otherwise we have to assume they alias.
11828   return true;
11831 /// Walk up chain skipping non-aliasing memory nodes,
11832 /// looking for aliasing nodes and adding them to the Aliases vector.
11833 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11834                                    SmallVectorImpl<SDValue> &Aliases) {
11835   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11836   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11838   // Get alias information for node.
11839   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11841   // Starting off.
11842   Chains.push_back(OriginalChain);
11843   unsigned Depth = 0;
11845   // Look at each chain and determine if it is an alias.  If so, add it to the
11846   // aliases list.  If not, then continue up the chain looking for the next
11847   // candidate.
11848   while (!Chains.empty()) {
11849     SDValue Chain = Chains.back();
11850     Chains.pop_back();
11852     // For TokenFactor nodes, look at each operand and only continue up the
11853     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11854     // find more and revert to original chain since the xform is unlikely to be
11855     // profitable.
11856     //
11857     // FIXME: The depth check could be made to return the last non-aliasing
11858     // chain we found before we hit a tokenfactor rather than the original
11859     // chain.
11860     if (Depth > 6 || Aliases.size() == 2) {
11861       Aliases.clear();
11862       Aliases.push_back(OriginalChain);
11863       return;
11864     }
11866     // Don't bother if we've been before.
11867     if (!Visited.insert(Chain.getNode()))
11868       continue;
11870     switch (Chain.getOpcode()) {
11871     case ISD::EntryToken:
11872       // Entry token is ideal chain operand, but handled in FindBetterChain.
11873       break;
11875     case ISD::LOAD:
11876     case ISD::STORE: {
11877       // Get alias information for Chain.
11878       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11879           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11881       // If chain is alias then stop here.
11882       if (!(IsLoad && IsOpLoad) &&
11883           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11884         Aliases.push_back(Chain);
11885       } else {
11886         // Look further up the chain.
11887         Chains.push_back(Chain.getOperand(0));
11888         ++Depth;
11889       }
11890       break;
11891     }
11893     case ISD::TokenFactor:
11894       // We have to check each of the operands of the token factor for "small"
11895       // token factors, so we queue them up.  Adding the operands to the queue
11896       // (stack) in reverse order maintains the original order and increases the
11897       // likelihood that getNode will find a matching token factor (CSE.)
11898       if (Chain.getNumOperands() > 16) {
11899         Aliases.push_back(Chain);
11900         break;
11901       }
11902       for (unsigned n = Chain.getNumOperands(); n;)
11903         Chains.push_back(Chain.getOperand(--n));
11904       ++Depth;
11905       break;
11907     default:
11908       // For all other instructions we will just have to take what we can get.
11909       Aliases.push_back(Chain);
11910       break;
11911     }
11912   }
11914   // We need to be careful here to also search for aliases through the
11915   // value operand of a store, etc. Consider the following situation:
11916   //   Token1 = ...
11917   //   L1 = load Token1, %52
11918   //   S1 = store Token1, L1, %51
11919   //   L2 = load Token1, %52+8
11920   //   S2 = store Token1, L2, %51+8
11921   //   Token2 = Token(S1, S2)
11922   //   L3 = load Token2, %53
11923   //   S3 = store Token2, L3, %52
11924   //   L4 = load Token2, %53+8
11925   //   S4 = store Token2, L4, %52+8
11926   // If we search for aliases of S3 (which loads address %52), and we look
11927   // only through the chain, then we'll miss the trivial dependence on L1
11928   // (which also loads from %52). We then might change all loads and
11929   // stores to use Token1 as their chain operand, which could result in
11930   // copying %53 into %52 before copying %52 into %51 (which should
11931   // happen first).
11932   //
11933   // The problem is, however, that searching for such data dependencies
11934   // can become expensive, and the cost is not directly related to the
11935   // chain depth. Instead, we'll rule out such configurations here by
11936   // insisting that we've visited all chain users (except for users
11937   // of the original chain, which is not necessary). When doing this,
11938   // we need to look through nodes we don't care about (otherwise, things
11939   // like register copies will interfere with trivial cases).
11941   SmallVector<const SDNode *, 16> Worklist;
11942   for (const SDNode *N : Visited)
11943     if (N != OriginalChain.getNode())
11944       Worklist.push_back(N);
11946   while (!Worklist.empty()) {
11947     const SDNode *M = Worklist.pop_back_val();
11949     // We have already visited M, and want to make sure we've visited any uses
11950     // of M that we care about. For uses that we've not visisted, and don't
11951     // care about, queue them to the worklist.
11953     for (SDNode::use_iterator UI = M->use_begin(),
11954          UIE = M->use_end(); UI != UIE; ++UI)
11955       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11956         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11957           // We've not visited this use, and we care about it (it could have an
11958           // ordering dependency with the original node).
11959           Aliases.clear();
11960           Aliases.push_back(OriginalChain);
11961           return;
11962         }
11964         // We've not visited this use, but we don't care about it. Mark it as
11965         // visited and enqueue it to the worklist.
11966         Worklist.push_back(*UI);
11967       }
11968   }
11971 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
11972 /// (aliasing node.)
11973 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11974   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11976   // Accumulate all the aliases to this node.
11977   GatherAllAliases(N, OldChain, Aliases);
11979   // If no operands then chain to entry token.
11980   if (Aliases.size() == 0)
11981     return DAG.getEntryNode();
11983   // If a single operand then chain to it.  We don't need to revisit it.
11984   if (Aliases.size() == 1)
11985     return Aliases[0];
11987   // Construct a custom tailored token factor.
11988   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11991 /// This is the entry point for the file.
11992 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11993                            CodeGenOpt::Level OptLevel) {
11994   /// This is the main entry point to this class.
11995   DAGCombiner(*this, AA, OptLevel).Run(Level);