1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
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");
54 CombinerAA("combiner-alias-analysis", cl::Hidden,
55 cl::desc("Enable DAG combiner alias-analysis heuristics"));
58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59 cl::desc("Enable DAG combiner's use of IR alias analysis"));
62 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63 cl::desc("Enable DAG combiner's use of TBAA"));
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"
72 /// Hidden option to stress test load slicing, i.e., when this option
73 /// is enabled, load slicing bypasses most of its profitability guards.
75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76 cl::desc("Bypass the profitability model of load "
81 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82 cl::desc("DAG combiner may split indexing from loads"));
84 //------------------------------ DAGCombiner ---------------------------------//
88 const TargetLowering &TLI;
90 CodeGenOpt::Level OptLevel;
95 /// \brief Worklist of all of the nodes that need to be simplified.
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.
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.
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).
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.
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())
127 /// Call the node-specific routine that folds each particular type of node.
128 SDValue visit(SDNode *N);
131 /// Add to the worklist making sure its instance is at the back (next to be
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)
139 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140 Worklist.push_back(N);
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);
156 void deleteAndRecombine(SDNode *N);
157 bool recursivelyDeleteUnusedNodes(SDNode *N);
159 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
162 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163 return CombineTo(N, &Res, 1, AddTo);
166 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
168 SDValue To[] = { Res0, Res1 };
169 return CombineTo(N, To, 2, AddTo);
172 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
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);
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
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:
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.
227 SDValue visitTokenFactor(SDNode *N);
228 SDValue visitMERGE_VALUES(SDNode *N);
229 SDValue visitADD(SDNode *N);
230 SDValue visitSUB(SDNode *N);
231 SDValue visitADDC(SDNode *N);
232 SDValue visitSUBC(SDNode *N);
233 SDValue visitADDE(SDNode *N);
234 SDValue visitSUBE(SDNode *N);
235 SDValue visitMUL(SDNode *N);
236 SDValue visitSDIV(SDNode *N);
237 SDValue visitUDIV(SDNode *N);
238 SDValue visitSREM(SDNode *N);
239 SDValue visitUREM(SDNode *N);
240 SDValue visitMULHU(SDNode *N);
241 SDValue visitMULHS(SDNode *N);
242 SDValue visitSMUL_LOHI(SDNode *N);
243 SDValue visitUMUL_LOHI(SDNode *N);
244 SDValue visitSMULO(SDNode *N);
245 SDValue visitUMULO(SDNode *N);
246 SDValue visitSDIVREM(SDNode *N);
247 SDValue visitUDIVREM(SDNode *N);
248 SDValue visitAND(SDNode *N);
249 SDValue visitOR(SDNode *N);
250 SDValue visitXOR(SDNode *N);
251 SDValue SimplifyVBinOp(SDNode *N);
252 SDValue SimplifyVUnaryOp(SDNode *N);
253 SDValue visitSHL(SDNode *N);
254 SDValue visitSRA(SDNode *N);
255 SDValue visitSRL(SDNode *N);
256 SDValue visitRotate(SDNode *N);
257 SDValue visitCTLZ(SDNode *N);
258 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
259 SDValue visitCTTZ(SDNode *N);
260 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
261 SDValue visitCTPOP(SDNode *N);
262 SDValue visitSELECT(SDNode *N);
263 SDValue visitVSELECT(SDNode *N);
264 SDValue visitSELECT_CC(SDNode *N);
265 SDValue visitSETCC(SDNode *N);
266 SDValue visitSIGN_EXTEND(SDNode *N);
267 SDValue visitZERO_EXTEND(SDNode *N);
268 SDValue visitANY_EXTEND(SDNode *N);
269 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
270 SDValue visitTRUNCATE(SDNode *N);
271 SDValue visitBITCAST(SDNode *N);
272 SDValue visitBUILD_PAIR(SDNode *N);
273 SDValue visitFADD(SDNode *N);
274 SDValue visitFSUB(SDNode *N);
275 SDValue visitFMUL(SDNode *N);
276 SDValue visitFMA(SDNode *N);
277 SDValue visitFDIV(SDNode *N);
278 SDValue visitFREM(SDNode *N);
279 SDValue visitFSQRT(SDNode *N);
280 SDValue visitFCOPYSIGN(SDNode *N);
281 SDValue visitSINT_TO_FP(SDNode *N);
282 SDValue visitUINT_TO_FP(SDNode *N);
283 SDValue visitFP_TO_SINT(SDNode *N);
284 SDValue visitFP_TO_UINT(SDNode *N);
285 SDValue visitFP_ROUND(SDNode *N);
286 SDValue visitFP_ROUND_INREG(SDNode *N);
287 SDValue visitFP_EXTEND(SDNode *N);
288 SDValue visitFNEG(SDNode *N);
289 SDValue visitFABS(SDNode *N);
290 SDValue visitFCEIL(SDNode *N);
291 SDValue visitFTRUNC(SDNode *N);
292 SDValue visitFFLOOR(SDNode *N);
293 SDValue visitFMINNUM(SDNode *N);
294 SDValue visitFMAXNUM(SDNode *N);
295 SDValue visitBRCOND(SDNode *N);
296 SDValue visitBR_CC(SDNode *N);
297 SDValue visitLOAD(SDNode *N);
298 SDValue visitSTORE(SDNode *N);
299 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
300 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
301 SDValue visitBUILD_VECTOR(SDNode *N);
302 SDValue visitCONCAT_VECTORS(SDNode *N);
303 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
304 SDValue visitVECTOR_SHUFFLE(SDNode *N);
305 SDValue visitINSERT_SUBVECTOR(SDNode *N);
306 SDValue visitMLOAD(SDNode *N);
307 SDValue visitMSTORE(SDNode *N);
309 SDValue XformToShuffleWithZero(SDNode *N);
310 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
312 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
314 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
315 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
316 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
317 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
318 SDValue N3, ISD::CondCode CC,
319 bool NotExtCompare = false);
320 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
321 SDLoc DL, bool foldBooleans = true);
323 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
325 bool isOneUseSetCC(SDValue N) const;
327 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
329 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
330 SDValue CombineExtLoad(SDNode *N);
331 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
332 SDValue BuildSDIV(SDNode *N);
333 SDValue BuildSDIVPow2(SDNode *N);
334 SDValue BuildUDIV(SDNode *N);
335 SDValue BuildReciprocalEstimate(SDValue Op);
336 SDValue BuildRsqrtEstimate(SDValue Op);
337 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
338 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
339 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
340 bool DemandHighBits = true);
341 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
342 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
343 SDValue InnerPos, SDValue InnerNeg,
344 unsigned PosOpcode, unsigned NegOpcode,
346 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
347 SDValue ReduceLoadWidth(SDNode *N);
348 SDValue ReduceLoadOpStoreWidth(SDNode *N);
349 SDValue TransformFPLoadStorePair(SDNode *N);
350 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
351 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
353 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
355 /// Walk up chain skipping non-aliasing memory nodes,
356 /// looking for aliasing nodes and adding them to the Aliases vector.
357 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
358 SmallVectorImpl<SDValue> &Aliases);
360 /// Return true if there is any possibility that the two addresses overlap.
361 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
363 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
364 /// chain (aliasing node.)
365 SDValue FindBetterChain(SDNode *N, SDValue Chain);
367 /// Holds a pointer to an LSBaseSDNode as well as information on where it
368 /// is located in a sequence of memory operations connected by a chain.
370 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
371 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
372 // Ptr to the mem node.
373 LSBaseSDNode *MemNode;
374 // Offset from the base ptr.
375 int64_t OffsetFromBase;
376 // What is the sequence number of this mem node.
377 // Lowest mem operand in the DAG starts at zero.
378 unsigned SequenceNum;
381 /// This is a helper function for MergeConsecutiveStores. When the source
382 /// elements of the consecutive stores are all constants or all extracted
383 /// vector elements, try to merge them into one larger store.
384 /// \return True if a merged store was created.
385 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
386 EVT MemVT, unsigned NumElem,
387 bool IsConstantSrc, bool UseVector);
389 /// Merge consecutive store operations into a wide store.
390 /// This optimization uses wide integers or vectors when possible.
391 /// \return True if some memory operations were changed.
392 bool MergeConsecutiveStores(StoreSDNode *N);
394 /// \brief Try to transform a truncation where C is a constant:
395 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
397 /// \p N needs to be a truncation and its first operand an AND. Other
398 /// requirements are checked by the function (e.g. that trunc is
399 /// single-use) and if missed an empty SDValue is returned.
400 SDValue distributeTruncateThroughAnd(SDNode *N);
403 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
404 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
405 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
406 auto *F = DAG.getMachineFunction().getFunction();
407 ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
408 F->hasFnAttribute(Attribute::MinSize);
411 /// Runs the dag combiner on all nodes in the work list
412 void Run(CombineLevel AtLevel);
414 SelectionDAG &getDAG() const { return DAG; }
416 /// Returns a type large enough to hold any valid shift amount - before type
417 /// legalization these can be huge.
418 EVT getShiftAmountTy(EVT LHSTy) {
419 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
420 if (LHSTy.isVector())
422 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
423 : TLI.getPointerTy();
426 /// This method returns true if we are running before type legalization or
427 /// if the specified VT is legal.
428 bool isTypeLegal(const EVT &VT) {
429 if (!LegalTypes) return true;
430 return TLI.isTypeLegal(VT);
433 /// Convenience wrapper around TargetLowering::getSetCCResultType
434 EVT getSetCCResultType(EVT VT) const {
435 return TLI.getSetCCResultType(*DAG.getContext(), VT);
442 /// This class is a DAGUpdateListener that removes any deleted
443 /// nodes from the worklist.
444 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
447 explicit WorklistRemover(DAGCombiner &dc)
448 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
450 void NodeDeleted(SDNode *N, SDNode *E) override {
451 DC.removeFromWorklist(N);
456 //===----------------------------------------------------------------------===//
457 // TargetLowering::DAGCombinerInfo implementation
458 //===----------------------------------------------------------------------===//
460 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
461 ((DAGCombiner*)DC)->AddToWorklist(N);
464 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
465 ((DAGCombiner*)DC)->removeFromWorklist(N);
468 SDValue TargetLowering::DAGCombinerInfo::
469 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
470 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
473 SDValue TargetLowering::DAGCombinerInfo::
474 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
475 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
479 SDValue TargetLowering::DAGCombinerInfo::
480 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
481 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
484 void TargetLowering::DAGCombinerInfo::
485 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
486 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
489 //===----------------------------------------------------------------------===//
491 //===----------------------------------------------------------------------===//
493 void DAGCombiner::deleteAndRecombine(SDNode *N) {
494 removeFromWorklist(N);
496 // If the operands of this node are only used by the node, they will now be
497 // dead. Make sure to re-visit them and recursively delete dead nodes.
498 for (const SDValue &Op : N->ops())
499 // For an operand generating multiple values, one of the values may
500 // become dead allowing further simplification (e.g. split index
501 // arithmetic from an indexed load).
502 if (Op->hasOneUse() || Op->getNumValues() > 1)
503 AddToWorklist(Op.getNode());
508 /// Return 1 if we can compute the negated form of the specified expression for
509 /// the same cost as the expression itself, or 2 if we can compute the negated
510 /// form more cheaply than the expression itself.
511 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
512 const TargetLowering &TLI,
513 const TargetOptions *Options,
514 unsigned Depth = 0) {
515 // fneg is removable even if it has multiple uses.
516 if (Op.getOpcode() == ISD::FNEG) return 2;
518 // Don't allow anything with multiple uses.
519 if (!Op.hasOneUse()) return 0;
521 // Don't recurse exponentially.
522 if (Depth > 6) return 0;
524 switch (Op.getOpcode()) {
525 default: return false;
526 case ISD::ConstantFP:
527 // Don't invert constant FP values after legalize. The negated constant
528 // isn't necessarily legal.
529 return LegalOperations ? 0 : 1;
531 // FIXME: determine better conditions for this xform.
532 if (!Options->UnsafeFPMath) return 0;
534 // After operation legalization, it might not be legal to create new FSUBs.
535 if (LegalOperations &&
536 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
539 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
540 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
543 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
544 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
547 // We can't turn -(A-B) into B-A when we honor signed zeros.
548 if (!Options->UnsafeFPMath) return 0;
550 // fold (fneg (fsub A, B)) -> (fsub B, A)
555 if (Options->HonorSignDependentRoundingFPMath()) return 0;
557 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
558 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
562 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
568 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
573 /// If isNegatibleForFree returns true, return the newly negated expression.
574 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
575 bool LegalOperations, unsigned Depth = 0) {
576 const TargetOptions &Options = DAG.getTarget().Options;
577 // fneg is removable even if it has multiple uses.
578 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
580 // Don't allow anything with multiple uses.
581 assert(Op.hasOneUse() && "Unknown reuse!");
583 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
584 switch (Op.getOpcode()) {
585 default: llvm_unreachable("Unknown code");
586 case ISD::ConstantFP: {
587 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
589 return DAG.getConstantFP(V, Op.getValueType());
592 // FIXME: determine better conditions for this xform.
593 assert(Options.UnsafeFPMath);
595 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
596 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
597 DAG.getTargetLoweringInfo(), &Options, Depth+1))
598 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
599 GetNegatedExpression(Op.getOperand(0), DAG,
600 LegalOperations, Depth+1),
602 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
603 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
604 GetNegatedExpression(Op.getOperand(1), DAG,
605 LegalOperations, Depth+1),
608 // We can't turn -(A-B) into B-A when we honor signed zeros.
609 assert(Options.UnsafeFPMath);
611 // fold (fneg (fsub 0, B)) -> B
612 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
613 if (N0CFP->getValueAPF().isZero())
614 return Op.getOperand(1);
616 // fold (fneg (fsub A, B)) -> (fsub B, A)
617 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
618 Op.getOperand(1), Op.getOperand(0));
622 assert(!Options.HonorSignDependentRoundingFPMath());
624 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
625 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
626 DAG.getTargetLoweringInfo(), &Options, Depth+1))
627 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
628 GetNegatedExpression(Op.getOperand(0), DAG,
629 LegalOperations, Depth+1),
632 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
633 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
635 GetNegatedExpression(Op.getOperand(1), DAG,
636 LegalOperations, Depth+1));
640 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
641 GetNegatedExpression(Op.getOperand(0), DAG,
642 LegalOperations, Depth+1));
644 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
645 GetNegatedExpression(Op.getOperand(0), DAG,
646 LegalOperations, Depth+1),
651 // Return true if this node is a setcc, or is a select_cc
652 // that selects between the target values used for true and false, making it
653 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
654 // the appropriate nodes based on the type of node we are checking. This
655 // simplifies life a bit for the callers.
656 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
658 if (N.getOpcode() == ISD::SETCC) {
659 LHS = N.getOperand(0);
660 RHS = N.getOperand(1);
661 CC = N.getOperand(2);
665 if (N.getOpcode() != ISD::SELECT_CC ||
666 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
667 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
670 if (TLI.getBooleanContents(N.getValueType()) ==
671 TargetLowering::UndefinedBooleanContent)
674 LHS = N.getOperand(0);
675 RHS = N.getOperand(1);
676 CC = N.getOperand(4);
680 /// Return true if this is a SetCC-equivalent operation with only one use.
681 /// If this is true, it allows the users to invert the operation for free when
682 /// it is profitable to do so.
683 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
685 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
690 /// Returns true if N is a BUILD_VECTOR node whose
691 /// elements are all the same constant or undefined.
692 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
693 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
698 unsigned SplatBitSize;
700 EVT EltVT = N->getValueType(0).getVectorElementType();
701 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
703 EltVT.getSizeInBits() >= SplatBitSize);
706 // \brief Returns the SDNode if it is a constant BuildVector or constant.
707 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
708 if (isa<ConstantSDNode>(N))
710 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
711 if (BV && BV->isConstant())
716 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
718 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
719 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
722 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
723 BitVector UndefElements;
724 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
726 // BuildVectors can truncate their operands. Ignore that case here.
727 // FIXME: We blindly ignore splats which include undef which is overly
729 if (CN && UndefElements.none() &&
730 CN->getValueType(0) == N.getValueType().getScalarType())
737 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
739 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
740 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
743 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
744 BitVector UndefElements;
745 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
747 if (CN && UndefElements.none())
754 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
755 SDValue N0, SDValue N1) {
756 EVT VT = N0.getValueType();
757 if (N0.getOpcode() == Opc) {
758 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
759 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
760 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
761 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R))
762 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
765 if (N0.hasOneUse()) {
766 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
768 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
769 if (!OpNode.getNode())
771 AddToWorklist(OpNode.getNode());
772 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
777 if (N1.getOpcode() == Opc) {
778 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
779 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
780 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
781 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L))
782 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
785 if (N1.hasOneUse()) {
786 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
788 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
789 if (!OpNode.getNode())
791 AddToWorklist(OpNode.getNode());
792 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
800 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
802 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
804 DEBUG(dbgs() << "\nReplacing.1 ";
806 dbgs() << "\nWith: ";
807 To[0].getNode()->dump(&DAG);
808 dbgs() << " and " << NumTo-1 << " other values\n");
809 for (unsigned i = 0, e = NumTo; i != e; ++i)
810 assert((!To[i].getNode() ||
811 N->getValueType(i) == To[i].getValueType()) &&
812 "Cannot combine value to value of different type!");
814 WorklistRemover DeadNodes(*this);
815 DAG.ReplaceAllUsesWith(N, To);
817 // Push the new nodes and any users onto the worklist
818 for (unsigned i = 0, e = NumTo; i != e; ++i) {
819 if (To[i].getNode()) {
820 AddToWorklist(To[i].getNode());
821 AddUsersToWorklist(To[i].getNode());
826 // Finally, if the node is now dead, remove it from the graph. The node
827 // may not be dead if the replacement process recursively simplified to
828 // something else needing this node.
830 deleteAndRecombine(N);
831 return SDValue(N, 0);
835 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
836 // Replace all uses. If any nodes become isomorphic to other nodes and
837 // are deleted, make sure to remove them from our worklist.
838 WorklistRemover DeadNodes(*this);
839 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
841 // Push the new node and any (possibly new) users onto the worklist.
842 AddToWorklist(TLO.New.getNode());
843 AddUsersToWorklist(TLO.New.getNode());
845 // Finally, if the node is now dead, remove it from the graph. The node
846 // may not be dead if the replacement process recursively simplified to
847 // something else needing this node.
848 if (TLO.Old.getNode()->use_empty())
849 deleteAndRecombine(TLO.Old.getNode());
852 /// Check the specified integer node value to see if it can be simplified or if
853 /// things it uses can be simplified by bit propagation. If so, return true.
854 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
855 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
856 APInt KnownZero, KnownOne;
857 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
861 AddToWorklist(Op.getNode());
863 // Replace the old value with the new one.
865 DEBUG(dbgs() << "\nReplacing.2 ";
866 TLO.Old.getNode()->dump(&DAG);
867 dbgs() << "\nWith: ";
868 TLO.New.getNode()->dump(&DAG);
871 CommitTargetLoweringOpt(TLO);
875 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
877 EVT VT = Load->getValueType(0);
878 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
880 DEBUG(dbgs() << "\nReplacing.9 ";
882 dbgs() << "\nWith: ";
883 Trunc.getNode()->dump(&DAG);
885 WorklistRemover DeadNodes(*this);
886 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
887 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
888 deleteAndRecombine(Load);
889 AddToWorklist(Trunc.getNode());
892 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
895 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
896 EVT MemVT = LD->getMemoryVT();
897 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
898 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
900 : LD->getExtensionType();
902 return DAG.getExtLoad(ExtType, dl, PVT,
903 LD->getChain(), LD->getBasePtr(),
904 MemVT, LD->getMemOperand());
907 unsigned Opc = Op.getOpcode();
910 case ISD::AssertSext:
911 return DAG.getNode(ISD::AssertSext, dl, PVT,
912 SExtPromoteOperand(Op.getOperand(0), PVT),
914 case ISD::AssertZext:
915 return DAG.getNode(ISD::AssertZext, dl, PVT,
916 ZExtPromoteOperand(Op.getOperand(0), PVT),
918 case ISD::Constant: {
920 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
921 return DAG.getNode(ExtOpc, dl, PVT, Op);
925 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
927 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
930 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
931 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
933 EVT OldVT = Op.getValueType();
935 bool Replace = false;
936 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
937 if (!NewOp.getNode())
939 AddToWorklist(NewOp.getNode());
942 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
943 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
944 DAG.getValueType(OldVT));
947 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
948 EVT OldVT = Op.getValueType();
950 bool Replace = false;
951 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
952 if (!NewOp.getNode())
954 AddToWorklist(NewOp.getNode());
957 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
958 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
961 /// Promote the specified integer binary operation if the target indicates it is
962 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
963 /// i32 since i16 instructions are longer.
964 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
965 if (!LegalOperations)
968 EVT VT = Op.getValueType();
969 if (VT.isVector() || !VT.isInteger())
972 // If operation type is 'undesirable', e.g. i16 on x86, consider
974 unsigned Opc = Op.getOpcode();
975 if (TLI.isTypeDesirableForOp(Opc, VT))
979 // Consult target whether it is a good idea to promote this operation and
980 // what's the right type to promote it to.
981 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
982 assert(PVT != VT && "Don't know what type to promote to!");
984 bool Replace0 = false;
985 SDValue N0 = Op.getOperand(0);
986 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
990 bool Replace1 = false;
991 SDValue N1 = Op.getOperand(1);
996 NN1 = PromoteOperand(N1, PVT, Replace1);
1001 AddToWorklist(NN0.getNode());
1003 AddToWorklist(NN1.getNode());
1006 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1008 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1010 DEBUG(dbgs() << "\nPromoting ";
1011 Op.getNode()->dump(&DAG));
1013 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1014 DAG.getNode(Opc, dl, PVT, NN0, NN1));
1019 /// Promote the specified integer shift operation if the target indicates it is
1020 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1021 /// i32 since i16 instructions are longer.
1022 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1023 if (!LegalOperations)
1026 EVT VT = Op.getValueType();
1027 if (VT.isVector() || !VT.isInteger())
1030 // If operation type is 'undesirable', e.g. i16 on x86, consider
1032 unsigned Opc = Op.getOpcode();
1033 if (TLI.isTypeDesirableForOp(Opc, VT))
1037 // Consult target whether it is a good idea to promote this operation and
1038 // what's the right type to promote it to.
1039 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1040 assert(PVT != VT && "Don't know what type to promote to!");
1042 bool Replace = false;
1043 SDValue N0 = Op.getOperand(0);
1044 if (Opc == ISD::SRA)
1045 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1046 else if (Opc == ISD::SRL)
1047 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1049 N0 = PromoteOperand(N0, PVT, Replace);
1053 AddToWorklist(N0.getNode());
1055 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1057 DEBUG(dbgs() << "\nPromoting ";
1058 Op.getNode()->dump(&DAG));
1060 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1061 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1066 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1067 if (!LegalOperations)
1070 EVT VT = Op.getValueType();
1071 if (VT.isVector() || !VT.isInteger())
1074 // If operation type is 'undesirable', e.g. i16 on x86, consider
1076 unsigned Opc = Op.getOpcode();
1077 if (TLI.isTypeDesirableForOp(Opc, VT))
1081 // Consult target whether it is a good idea to promote this operation and
1082 // what's the right type to promote it to.
1083 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1084 assert(PVT != VT && "Don't know what type to promote to!");
1085 // fold (aext (aext x)) -> (aext x)
1086 // fold (aext (zext x)) -> (zext x)
1087 // fold (aext (sext x)) -> (sext x)
1088 DEBUG(dbgs() << "\nPromoting ";
1089 Op.getNode()->dump(&DAG));
1090 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1095 bool DAGCombiner::PromoteLoad(SDValue Op) {
1096 if (!LegalOperations)
1099 EVT VT = Op.getValueType();
1100 if (VT.isVector() || !VT.isInteger())
1103 // If operation type is 'undesirable', e.g. i16 on x86, consider
1105 unsigned Opc = Op.getOpcode();
1106 if (TLI.isTypeDesirableForOp(Opc, VT))
1110 // Consult target whether it is a good idea to promote this operation and
1111 // what's the right type to promote it to.
1112 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1113 assert(PVT != VT && "Don't know what type to promote to!");
1116 SDNode *N = Op.getNode();
1117 LoadSDNode *LD = cast<LoadSDNode>(N);
1118 EVT MemVT = LD->getMemoryVT();
1119 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1120 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1122 : LD->getExtensionType();
1123 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1124 LD->getChain(), LD->getBasePtr(),
1125 MemVT, LD->getMemOperand());
1126 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1128 DEBUG(dbgs() << "\nPromoting ";
1131 Result.getNode()->dump(&DAG);
1133 WorklistRemover DeadNodes(*this);
1134 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1135 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1136 deleteAndRecombine(N);
1137 AddToWorklist(Result.getNode());
1143 /// \brief Recursively delete a node which has no uses and any operands for
1144 /// which it is the only use.
1146 /// Note that this both deletes the nodes and removes them from the worklist.
1147 /// It also adds any nodes who have had a user deleted to the worklist as they
1148 /// may now have only one use and subject to other combines.
1149 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1150 if (!N->use_empty())
1153 SmallSetVector<SDNode *, 16> Nodes;
1156 N = Nodes.pop_back_val();
1160 if (N->use_empty()) {
1161 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1162 Nodes.insert(N->getOperand(i).getNode());
1164 removeFromWorklist(N);
1169 } while (!Nodes.empty());
1173 //===----------------------------------------------------------------------===//
1174 // Main DAG Combiner implementation
1175 //===----------------------------------------------------------------------===//
1177 void DAGCombiner::Run(CombineLevel AtLevel) {
1178 // set the instance variables, so that the various visit routines may use it.
1180 LegalOperations = Level >= AfterLegalizeVectorOps;
1181 LegalTypes = Level >= AfterLegalizeTypes;
1183 // Early exit if this basic block is in an optnone function.
1184 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
1185 Attribute::OptimizeNone))
1188 // Add all the dag nodes to the worklist.
1189 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1190 E = DAG.allnodes_end(); I != E; ++I)
1193 // Create a dummy node (which is not added to allnodes), that adds a reference
1194 // to the root node, preventing it from being deleted, and tracking any
1195 // changes of the root.
1196 HandleSDNode Dummy(DAG.getRoot());
1198 // while the worklist isn't empty, find a node and
1199 // try and combine it.
1200 while (!WorklistMap.empty()) {
1202 // The Worklist holds the SDNodes in order, but it may contain null entries.
1204 N = Worklist.pop_back_val();
1207 bool GoodWorklistEntry = WorklistMap.erase(N);
1208 (void)GoodWorklistEntry;
1209 assert(GoodWorklistEntry &&
1210 "Found a worklist entry without a corresponding map entry!");
1212 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1213 // N is deleted from the DAG, since they too may now be dead or may have a
1214 // reduced number of uses, allowing other xforms.
1215 if (recursivelyDeleteUnusedNodes(N))
1218 WorklistRemover DeadNodes(*this);
1220 // If this combine is running after legalizing the DAG, re-legalize any
1221 // nodes pulled off the worklist.
1222 if (Level == AfterLegalizeDAG) {
1223 SmallSetVector<SDNode *, 16> UpdatedNodes;
1224 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1226 for (SDNode *LN : UpdatedNodes) {
1228 AddUsersToWorklist(LN);
1234 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1236 // Add any operands of the new node which have not yet been combined to the
1237 // worklist as well. Because the worklist uniques things already, this
1238 // won't repeatedly process the same operand.
1239 CombinedNodes.insert(N);
1240 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1241 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1242 AddToWorklist(N->getOperand(i).getNode());
1244 SDValue RV = combine(N);
1251 // If we get back the same node we passed in, rather than a new node or
1252 // zero, we know that the node must have defined multiple values and
1253 // CombineTo was used. Since CombineTo takes care of the worklist
1254 // mechanics for us, we have no work to do in this case.
1255 if (RV.getNode() == N)
1258 assert(N->getOpcode() != ISD::DELETED_NODE &&
1259 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1260 "Node was deleted but visit returned new node!");
1262 DEBUG(dbgs() << " ... into: ";
1263 RV.getNode()->dump(&DAG));
1265 // Transfer debug value.
1266 DAG.TransferDbgValues(SDValue(N, 0), RV);
1267 if (N->getNumValues() == RV.getNode()->getNumValues())
1268 DAG.ReplaceAllUsesWith(N, RV.getNode());
1270 assert(N->getValueType(0) == RV.getValueType() &&
1271 N->getNumValues() == 1 && "Type mismatch");
1273 DAG.ReplaceAllUsesWith(N, &OpV);
1276 // Push the new node and any users onto the worklist
1277 AddToWorklist(RV.getNode());
1278 AddUsersToWorklist(RV.getNode());
1280 // Finally, if the node is now dead, remove it from the graph. The node
1281 // may not be dead if the replacement process recursively simplified to
1282 // something else needing this node. This will also take care of adding any
1283 // operands which have lost a user to the worklist.
1284 recursivelyDeleteUnusedNodes(N);
1287 // If the root changed (e.g. it was a dead load, update the root).
1288 DAG.setRoot(Dummy.getValue());
1289 DAG.RemoveDeadNodes();
1292 SDValue DAGCombiner::visit(SDNode *N) {
1293 switch (N->getOpcode()) {
1295 case ISD::TokenFactor: return visitTokenFactor(N);
1296 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1297 case ISD::ADD: return visitADD(N);
1298 case ISD::SUB: return visitSUB(N);
1299 case ISD::ADDC: return visitADDC(N);
1300 case ISD::SUBC: return visitSUBC(N);
1301 case ISD::ADDE: return visitADDE(N);
1302 case ISD::SUBE: return visitSUBE(N);
1303 case ISD::MUL: return visitMUL(N);
1304 case ISD::SDIV: return visitSDIV(N);
1305 case ISD::UDIV: return visitUDIV(N);
1306 case ISD::SREM: return visitSREM(N);
1307 case ISD::UREM: return visitUREM(N);
1308 case ISD::MULHU: return visitMULHU(N);
1309 case ISD::MULHS: return visitMULHS(N);
1310 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1311 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1312 case ISD::SMULO: return visitSMULO(N);
1313 case ISD::UMULO: return visitUMULO(N);
1314 case ISD::SDIVREM: return visitSDIVREM(N);
1315 case ISD::UDIVREM: return visitUDIVREM(N);
1316 case ISD::AND: return visitAND(N);
1317 case ISD::OR: return visitOR(N);
1318 case ISD::XOR: return visitXOR(N);
1319 case ISD::SHL: return visitSHL(N);
1320 case ISD::SRA: return visitSRA(N);
1321 case ISD::SRL: return visitSRL(N);
1323 case ISD::ROTL: return visitRotate(N);
1324 case ISD::CTLZ: return visitCTLZ(N);
1325 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1326 case ISD::CTTZ: return visitCTTZ(N);
1327 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1328 case ISD::CTPOP: return visitCTPOP(N);
1329 case ISD::SELECT: return visitSELECT(N);
1330 case ISD::VSELECT: return visitVSELECT(N);
1331 case ISD::SELECT_CC: return visitSELECT_CC(N);
1332 case ISD::SETCC: return visitSETCC(N);
1333 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1334 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1335 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1336 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1337 case ISD::TRUNCATE: return visitTRUNCATE(N);
1338 case ISD::BITCAST: return visitBITCAST(N);
1339 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1340 case ISD::FADD: return visitFADD(N);
1341 case ISD::FSUB: return visitFSUB(N);
1342 case ISD::FMUL: return visitFMUL(N);
1343 case ISD::FMA: return visitFMA(N);
1344 case ISD::FDIV: return visitFDIV(N);
1345 case ISD::FREM: return visitFREM(N);
1346 case ISD::FSQRT: return visitFSQRT(N);
1347 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1348 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1349 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1350 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1351 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1352 case ISD::FP_ROUND: return visitFP_ROUND(N);
1353 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1354 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1355 case ISD::FNEG: return visitFNEG(N);
1356 case ISD::FABS: return visitFABS(N);
1357 case ISD::FFLOOR: return visitFFLOOR(N);
1358 case ISD::FMINNUM: return visitFMINNUM(N);
1359 case ISD::FMAXNUM: return visitFMAXNUM(N);
1360 case ISD::FCEIL: return visitFCEIL(N);
1361 case ISD::FTRUNC: return visitFTRUNC(N);
1362 case ISD::BRCOND: return visitBRCOND(N);
1363 case ISD::BR_CC: return visitBR_CC(N);
1364 case ISD::LOAD: return visitLOAD(N);
1365 case ISD::STORE: return visitSTORE(N);
1366 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1367 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1368 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1369 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1370 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1371 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1372 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1373 case ISD::MLOAD: return visitMLOAD(N);
1374 case ISD::MSTORE: return visitMSTORE(N);
1379 SDValue DAGCombiner::combine(SDNode *N) {
1380 SDValue RV = visit(N);
1382 // If nothing happened, try a target-specific DAG combine.
1383 if (!RV.getNode()) {
1384 assert(N->getOpcode() != ISD::DELETED_NODE &&
1385 "Node was deleted but visit returned NULL!");
1387 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1388 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1390 // Expose the DAG combiner to the target combiner impls.
1391 TargetLowering::DAGCombinerInfo
1392 DagCombineInfo(DAG, Level, false, this);
1394 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1398 // If nothing happened still, try promoting the operation.
1399 if (!RV.getNode()) {
1400 switch (N->getOpcode()) {
1408 RV = PromoteIntBinOp(SDValue(N, 0));
1413 RV = PromoteIntShiftOp(SDValue(N, 0));
1415 case ISD::SIGN_EXTEND:
1416 case ISD::ZERO_EXTEND:
1417 case ISD::ANY_EXTEND:
1418 RV = PromoteExtend(SDValue(N, 0));
1421 if (PromoteLoad(SDValue(N, 0)))
1427 // If N is a commutative binary node, try commuting it to enable more
1429 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1430 N->getNumValues() == 1) {
1431 SDValue N0 = N->getOperand(0);
1432 SDValue N1 = N->getOperand(1);
1434 // Constant operands are canonicalized to RHS.
1435 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1436 SDValue Ops[] = {N1, N0};
1438 if (const BinaryWithFlagsSDNode *BinNode =
1439 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1440 CSENode = DAG.getNodeIfExists(
1441 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1442 BinNode->hasNoSignedWrap(), BinNode->isExact());
1444 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1447 return SDValue(CSENode, 0);
1454 /// Given a node, return its input chain if it has one, otherwise return a null
1456 static SDValue getInputChainForNode(SDNode *N) {
1457 if (unsigned NumOps = N->getNumOperands()) {
1458 if (N->getOperand(0).getValueType() == MVT::Other)
1459 return N->getOperand(0);
1460 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1461 return N->getOperand(NumOps-1);
1462 for (unsigned i = 1; i < NumOps-1; ++i)
1463 if (N->getOperand(i).getValueType() == MVT::Other)
1464 return N->getOperand(i);
1469 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1470 // If N has two operands, where one has an input chain equal to the other,
1471 // the 'other' chain is redundant.
1472 if (N->getNumOperands() == 2) {
1473 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1474 return N->getOperand(0);
1475 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1476 return N->getOperand(1);
1479 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1480 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1481 SmallPtrSet<SDNode*, 16> SeenOps;
1482 bool Changed = false; // If we should replace this token factor.
1484 // Start out with this token factor.
1487 // Iterate through token factors. The TFs grows when new token factors are
1489 for (unsigned i = 0; i < TFs.size(); ++i) {
1490 SDNode *TF = TFs[i];
1492 // Check each of the operands.
1493 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1494 SDValue Op = TF->getOperand(i);
1496 switch (Op.getOpcode()) {
1497 case ISD::EntryToken:
1498 // Entry tokens don't need to be added to the list. They are
1503 case ISD::TokenFactor:
1504 if (Op.hasOneUse() &&
1505 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1506 // Queue up for processing.
1507 TFs.push_back(Op.getNode());
1508 // Clean up in case the token factor is removed.
1509 AddToWorklist(Op.getNode());
1516 // Only add if it isn't already in the list.
1517 if (SeenOps.insert(Op.getNode()).second)
1528 // If we've changed things around then replace token factor.
1531 // The entry token is the only possible outcome.
1532 Result = DAG.getEntryNode();
1534 // New and improved token factor.
1535 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1538 // Add users to worklist if AA is enabled, since it may introduce
1539 // a lot of new chained token factors while removing memory deps.
1540 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1541 : DAG.getSubtarget().useAA();
1542 return CombineTo(N, Result, UseAA /*add to worklist*/);
1548 /// MERGE_VALUES can always be eliminated.
1549 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1550 WorklistRemover DeadNodes(*this);
1551 // Replacing results may cause a different MERGE_VALUES to suddenly
1552 // be CSE'd with N, and carry its uses with it. Iterate until no
1553 // uses remain, to ensure that the node can be safely deleted.
1554 // First add the users of this node to the work list so that they
1555 // can be tried again once they have new operands.
1556 AddUsersToWorklist(N);
1558 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1559 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1560 } while (!N->use_empty());
1561 deleteAndRecombine(N);
1562 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1565 SDValue DAGCombiner::visitADD(SDNode *N) {
1566 SDValue N0 = N->getOperand(0);
1567 SDValue N1 = N->getOperand(1);
1568 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1569 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1570 EVT VT = N0.getValueType();
1573 if (VT.isVector()) {
1574 SDValue FoldedVOp = SimplifyVBinOp(N);
1575 if (FoldedVOp.getNode()) return FoldedVOp;
1577 // fold (add x, 0) -> x, vector edition
1578 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1580 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1584 // fold (add x, undef) -> undef
1585 if (N0.getOpcode() == ISD::UNDEF)
1587 if (N1.getOpcode() == ISD::UNDEF)
1589 // fold (add c1, c2) -> c1+c2
1591 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1592 // canonicalize constant to RHS
1594 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1595 // fold (add x, 0) -> x
1596 if (N1C && N1C->isNullValue())
1598 // fold (add Sym, c) -> Sym+c
1599 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1600 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1601 GA->getOpcode() == ISD::GlobalAddress)
1602 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1604 (uint64_t)N1C->getSExtValue());
1605 // fold ((c1-A)+c2) -> (c1+c2)-A
1606 if (N1C && N0.getOpcode() == ISD::SUB)
1607 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1608 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1609 DAG.getConstant(N1C->getAPIntValue()+
1610 N0C->getAPIntValue(), VT),
1613 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1616 // fold ((0-A) + B) -> B-A
1617 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1618 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1619 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1620 // fold (A + (0-B)) -> A-B
1621 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1622 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1623 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1624 // fold (A+(B-A)) -> B
1625 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1626 return N1.getOperand(0);
1627 // fold ((B-A)+A) -> B
1628 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1629 return N0.getOperand(0);
1630 // fold (A+(B-(A+C))) to (B-C)
1631 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1632 N0 == N1.getOperand(1).getOperand(0))
1633 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1634 N1.getOperand(1).getOperand(1));
1635 // fold (A+(B-(C+A))) to (B-C)
1636 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1637 N0 == N1.getOperand(1).getOperand(1))
1638 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1639 N1.getOperand(1).getOperand(0));
1640 // fold (A+((B-A)+or-C)) to (B+or-C)
1641 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1642 N1.getOperand(0).getOpcode() == ISD::SUB &&
1643 N0 == N1.getOperand(0).getOperand(1))
1644 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1645 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1647 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1648 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1649 SDValue N00 = N0.getOperand(0);
1650 SDValue N01 = N0.getOperand(1);
1651 SDValue N10 = N1.getOperand(0);
1652 SDValue N11 = N1.getOperand(1);
1654 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1655 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1656 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1657 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1660 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1661 return SDValue(N, 0);
1663 // fold (a+b) -> (a|b) iff a and b share no bits.
1664 if (VT.isInteger() && !VT.isVector()) {
1665 APInt LHSZero, LHSOne;
1666 APInt RHSZero, RHSOne;
1667 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1669 if (LHSZero.getBoolValue()) {
1670 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1672 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1673 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1674 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1675 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1676 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1681 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1682 if (N1.getOpcode() == ISD::SHL &&
1683 N1.getOperand(0).getOpcode() == ISD::SUB)
1684 if (ConstantSDNode *C =
1685 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1686 if (C->getAPIntValue() == 0)
1687 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1688 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1689 N1.getOperand(0).getOperand(1),
1691 if (N0.getOpcode() == ISD::SHL &&
1692 N0.getOperand(0).getOpcode() == ISD::SUB)
1693 if (ConstantSDNode *C =
1694 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1695 if (C->getAPIntValue() == 0)
1696 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1697 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1698 N0.getOperand(0).getOperand(1),
1701 if (N1.getOpcode() == ISD::AND) {
1702 SDValue AndOp0 = N1.getOperand(0);
1703 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1704 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1705 unsigned DestBits = VT.getScalarType().getSizeInBits();
1707 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1708 // and similar xforms where the inner op is either ~0 or 0.
1709 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1711 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1715 // add (sext i1), X -> sub X, (zext i1)
1716 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1717 N0.getOperand(0).getValueType() == MVT::i1 &&
1718 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1720 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1721 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1724 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1725 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1726 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1727 if (TN->getVT() == MVT::i1) {
1729 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1730 DAG.getConstant(1, VT));
1731 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1738 SDValue DAGCombiner::visitADDC(SDNode *N) {
1739 SDValue N0 = N->getOperand(0);
1740 SDValue N1 = N->getOperand(1);
1741 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1742 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1743 EVT VT = N0.getValueType();
1745 // If the flag result is dead, turn this into an ADD.
1746 if (!N->hasAnyUseOfValue(1))
1747 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1748 DAG.getNode(ISD::CARRY_FALSE,
1749 SDLoc(N), MVT::Glue));
1751 // canonicalize constant to RHS.
1753 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1755 // fold (addc x, 0) -> x + no carry out
1756 if (N1C && N1C->isNullValue())
1757 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1758 SDLoc(N), MVT::Glue));
1760 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1761 APInt LHSZero, LHSOne;
1762 APInt RHSZero, RHSOne;
1763 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1765 if (LHSZero.getBoolValue()) {
1766 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1768 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1769 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1770 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1771 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1772 DAG.getNode(ISD::CARRY_FALSE,
1773 SDLoc(N), MVT::Glue));
1779 SDValue DAGCombiner::visitADDE(SDNode *N) {
1780 SDValue N0 = N->getOperand(0);
1781 SDValue N1 = N->getOperand(1);
1782 SDValue CarryIn = N->getOperand(2);
1783 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1784 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1786 // canonicalize constant to RHS
1788 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1791 // fold (adde x, y, false) -> (addc x, y)
1792 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1793 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1798 // Since it may not be valid to emit a fold to zero for vector initializers
1799 // check if we can before folding.
1800 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1802 bool LegalOperations, bool LegalTypes) {
1804 return DAG.getConstant(0, VT);
1805 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1806 return DAG.getConstant(0, VT);
1810 SDValue DAGCombiner::visitSUB(SDNode *N) {
1811 SDValue N0 = N->getOperand(0);
1812 SDValue N1 = N->getOperand(1);
1813 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1814 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1815 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1816 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1817 EVT VT = N0.getValueType();
1820 if (VT.isVector()) {
1821 SDValue FoldedVOp = SimplifyVBinOp(N);
1822 if (FoldedVOp.getNode()) return FoldedVOp;
1824 // fold (sub x, 0) -> x, vector edition
1825 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1829 // fold (sub x, x) -> 0
1830 // FIXME: Refactor this and xor and other similar operations together.
1832 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1833 // fold (sub c1, c2) -> c1-c2
1835 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1836 // fold (sub x, c) -> (add x, -c)
1838 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1839 DAG.getConstant(-N1C->getAPIntValue(), VT));
1840 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1841 if (N0C && N0C->isAllOnesValue())
1842 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1843 // fold A-(A-B) -> B
1844 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1845 return N1.getOperand(1);
1846 // fold (A+B)-A -> B
1847 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1848 return N0.getOperand(1);
1849 // fold (A+B)-B -> A
1850 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1851 return N0.getOperand(0);
1852 // fold C2-(A+C1) -> (C2-C1)-A
1853 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1854 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1856 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1859 // fold ((A+(B+or-C))-B) -> A+or-C
1860 if (N0.getOpcode() == ISD::ADD &&
1861 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1862 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1863 N0.getOperand(1).getOperand(0) == N1)
1864 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1865 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1866 // fold ((A+(C+B))-B) -> A+C
1867 if (N0.getOpcode() == ISD::ADD &&
1868 N0.getOperand(1).getOpcode() == ISD::ADD &&
1869 N0.getOperand(1).getOperand(1) == N1)
1870 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1871 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1872 // fold ((A-(B-C))-C) -> A-B
1873 if (N0.getOpcode() == ISD::SUB &&
1874 N0.getOperand(1).getOpcode() == ISD::SUB &&
1875 N0.getOperand(1).getOperand(1) == N1)
1876 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1877 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1879 // If either operand of a sub is undef, the result is undef
1880 if (N0.getOpcode() == ISD::UNDEF)
1882 if (N1.getOpcode() == ISD::UNDEF)
1885 // If the relocation model supports it, consider symbol offsets.
1886 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1887 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1888 // fold (sub Sym, c) -> Sym-c
1889 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1890 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1892 (uint64_t)N1C->getSExtValue());
1893 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1894 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1895 if (GA->getGlobal() == GB->getGlobal())
1896 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1900 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1901 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1902 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1903 if (TN->getVT() == MVT::i1) {
1905 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1906 DAG.getConstant(1, VT));
1907 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1914 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1915 SDValue N0 = N->getOperand(0);
1916 SDValue N1 = N->getOperand(1);
1917 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1918 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1919 EVT VT = N0.getValueType();
1921 // If the flag result is dead, turn this into an SUB.
1922 if (!N->hasAnyUseOfValue(1))
1923 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1924 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1927 // fold (subc x, x) -> 0 + no borrow
1929 return CombineTo(N, DAG.getConstant(0, VT),
1930 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1933 // fold (subc x, 0) -> x + no borrow
1934 if (N1C && N1C->isNullValue())
1935 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1938 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1939 if (N0C && N0C->isAllOnesValue())
1940 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1941 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1947 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1948 SDValue N0 = N->getOperand(0);
1949 SDValue N1 = N->getOperand(1);
1950 SDValue CarryIn = N->getOperand(2);
1952 // fold (sube x, y, false) -> (subc x, y)
1953 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1954 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1959 SDValue DAGCombiner::visitMUL(SDNode *N) {
1960 SDValue N0 = N->getOperand(0);
1961 SDValue N1 = N->getOperand(1);
1962 EVT VT = N0.getValueType();
1964 // fold (mul x, undef) -> 0
1965 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1966 return DAG.getConstant(0, VT);
1968 bool N0IsConst = false;
1969 bool N1IsConst = false;
1970 APInt ConstValue0, ConstValue1;
1972 if (VT.isVector()) {
1973 SDValue FoldedVOp = SimplifyVBinOp(N);
1974 if (FoldedVOp.getNode()) return FoldedVOp;
1976 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1977 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1979 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1980 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1982 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1983 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1987 // fold (mul c1, c2) -> c1*c2
1988 if (N0IsConst && N1IsConst)
1989 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1991 // canonicalize constant to RHS
1992 if (N0IsConst && !N1IsConst)
1993 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1994 // fold (mul x, 0) -> 0
1995 if (N1IsConst && ConstValue1 == 0)
1997 // We require a splat of the entire scalar bit width for non-contiguous
2000 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2001 // fold (mul x, 1) -> x
2002 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2004 // fold (mul x, -1) -> 0-x
2005 if (N1IsConst && ConstValue1.isAllOnesValue())
2006 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2007 DAG.getConstant(0, VT), N0);
2008 // fold (mul x, (1 << c)) -> x << c
2009 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
2010 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2011 DAG.getConstant(ConstValue1.logBase2(),
2012 getShiftAmountTy(N0.getValueType())));
2013 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2014 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
2015 unsigned Log2Val = (-ConstValue1).logBase2();
2016 // FIXME: If the input is something that is easily negated (e.g. a
2017 // single-use add), we should put the negate there.
2018 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2019 DAG.getConstant(0, VT),
2020 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2021 DAG.getConstant(Log2Val,
2022 getShiftAmountTy(N0.getValueType()))));
2026 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2027 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2028 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2029 isa<ConstantSDNode>(N0.getOperand(1)))) {
2030 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2031 N1, N0.getOperand(1));
2032 AddToWorklist(C3.getNode());
2033 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2034 N0.getOperand(0), C3);
2037 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2040 SDValue Sh(nullptr,0), Y(nullptr,0);
2041 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2042 if (N0.getOpcode() == ISD::SHL &&
2043 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2044 isa<ConstantSDNode>(N0.getOperand(1))) &&
2045 N0.getNode()->hasOneUse()) {
2047 } else if (N1.getOpcode() == ISD::SHL &&
2048 isa<ConstantSDNode>(N1.getOperand(1)) &&
2049 N1.getNode()->hasOneUse()) {
2054 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2055 Sh.getOperand(0), Y);
2056 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2057 Mul, Sh.getOperand(1));
2061 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2062 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2063 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2064 isa<ConstantSDNode>(N0.getOperand(1))))
2065 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2066 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2067 N0.getOperand(0), N1),
2068 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2069 N0.getOperand(1), N1));
2072 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2079 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2080 SDValue N0 = N->getOperand(0);
2081 SDValue N1 = N->getOperand(1);
2082 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2083 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2084 EVT VT = N->getValueType(0);
2087 if (VT.isVector()) {
2088 SDValue FoldedVOp = SimplifyVBinOp(N);
2089 if (FoldedVOp.getNode()) return FoldedVOp;
2092 // fold (sdiv c1, c2) -> c1/c2
2093 if (N0C && N1C && !N1C->isNullValue())
2094 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2095 // fold (sdiv X, 1) -> X
2096 if (N1C && N1C->getAPIntValue() == 1LL)
2098 // fold (sdiv X, -1) -> 0-X
2099 if (N1C && N1C->isAllOnesValue())
2100 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2101 DAG.getConstant(0, VT), N0);
2102 // If we know the sign bits of both operands are zero, strength reduce to a
2103 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2104 if (!VT.isVector()) {
2105 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2106 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2110 // fold (sdiv X, pow2) -> simple ops after legalize
2111 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2112 (-N1C->getAPIntValue()).isPowerOf2())) {
2113 // If dividing by powers of two is cheap, then don't perform the following
2115 if (TLI.isPow2SDivCheap())
2118 // Target-specific implementation of sdiv x, pow2.
2119 SDValue Res = BuildSDIVPow2(N);
2123 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2125 // Splat the sign bit into the register
2127 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2128 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2129 getShiftAmountTy(N0.getValueType())));
2130 AddToWorklist(SGN.getNode());
2132 // Add (N0 < 0) ? abs2 - 1 : 0;
2134 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2135 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2136 getShiftAmountTy(SGN.getValueType())));
2137 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2138 AddToWorklist(SRL.getNode());
2139 AddToWorklist(ADD.getNode()); // Divide by pow2
2140 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2141 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2143 // If we're dividing by a positive value, we're done. Otherwise, we must
2144 // negate the result.
2145 if (N1C->getAPIntValue().isNonNegative())
2148 AddToWorklist(SRA.getNode());
2149 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2152 // if integer divide is expensive and we satisfy the requirements, emit an
2153 // alternate sequence.
2154 if (N1C && !TLI.isIntDivCheap()) {
2155 SDValue Op = BuildSDIV(N);
2156 if (Op.getNode()) return Op;
2160 if (N0.getOpcode() == ISD::UNDEF)
2161 return DAG.getConstant(0, VT);
2162 // X / undef -> undef
2163 if (N1.getOpcode() == ISD::UNDEF)
2169 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2170 SDValue N0 = N->getOperand(0);
2171 SDValue N1 = N->getOperand(1);
2172 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2173 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2174 EVT VT = N->getValueType(0);
2177 if (VT.isVector()) {
2178 SDValue FoldedVOp = SimplifyVBinOp(N);
2179 if (FoldedVOp.getNode()) return FoldedVOp;
2182 // fold (udiv c1, c2) -> c1/c2
2183 if (N0C && N1C && !N1C->isNullValue())
2184 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2185 // fold (udiv x, (1 << c)) -> x >>u c
2186 if (N1C && N1C->getAPIntValue().isPowerOf2())
2187 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2188 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2189 getShiftAmountTy(N0.getValueType())));
2190 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2191 if (N1.getOpcode() == ISD::SHL) {
2192 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2193 if (SHC->getAPIntValue().isPowerOf2()) {
2194 EVT ADDVT = N1.getOperand(1).getValueType();
2195 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2197 DAG.getConstant(SHC->getAPIntValue()
2200 AddToWorklist(Add.getNode());
2201 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2205 // fold (udiv x, c) -> alternate
2206 if (N1C && !TLI.isIntDivCheap()) {
2207 SDValue Op = BuildUDIV(N);
2208 if (Op.getNode()) return Op;
2212 if (N0.getOpcode() == ISD::UNDEF)
2213 return DAG.getConstant(0, VT);
2214 // X / undef -> undef
2215 if (N1.getOpcode() == ISD::UNDEF)
2221 SDValue DAGCombiner::visitSREM(SDNode *N) {
2222 SDValue N0 = N->getOperand(0);
2223 SDValue N1 = N->getOperand(1);
2224 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2225 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2226 EVT VT = N->getValueType(0);
2228 // fold (srem c1, c2) -> c1%c2
2229 if (N0C && N1C && !N1C->isNullValue())
2230 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2231 // If we know the sign bits of both operands are zero, strength reduce to a
2232 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2233 if (!VT.isVector()) {
2234 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2235 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2238 // If X/C can be simplified by the division-by-constant logic, lower
2239 // X%C to the equivalent of X-X/C*C.
2240 if (N1C && !N1C->isNullValue()) {
2241 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2242 AddToWorklist(Div.getNode());
2243 SDValue OptimizedDiv = combine(Div.getNode());
2244 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2245 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2247 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2248 AddToWorklist(Mul.getNode());
2254 if (N0.getOpcode() == ISD::UNDEF)
2255 return DAG.getConstant(0, VT);
2256 // X % undef -> undef
2257 if (N1.getOpcode() == ISD::UNDEF)
2263 SDValue DAGCombiner::visitUREM(SDNode *N) {
2264 SDValue N0 = N->getOperand(0);
2265 SDValue N1 = N->getOperand(1);
2266 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2267 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2268 EVT VT = N->getValueType(0);
2270 // fold (urem c1, c2) -> c1%c2
2271 if (N0C && N1C && !N1C->isNullValue())
2272 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2273 // fold (urem x, pow2) -> (and x, pow2-1)
2274 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2275 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2276 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2277 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2278 if (N1.getOpcode() == ISD::SHL) {
2279 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2280 if (SHC->getAPIntValue().isPowerOf2()) {
2282 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2283 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2285 AddToWorklist(Add.getNode());
2286 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2291 // If X/C can be simplified by the division-by-constant logic, lower
2292 // X%C to the equivalent of X-X/C*C.
2293 if (N1C && !N1C->isNullValue()) {
2294 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2295 AddToWorklist(Div.getNode());
2296 SDValue OptimizedDiv = combine(Div.getNode());
2297 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2298 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2300 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2301 AddToWorklist(Mul.getNode());
2307 if (N0.getOpcode() == ISD::UNDEF)
2308 return DAG.getConstant(0, VT);
2309 // X % undef -> undef
2310 if (N1.getOpcode() == ISD::UNDEF)
2316 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2317 SDValue N0 = N->getOperand(0);
2318 SDValue N1 = N->getOperand(1);
2319 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2320 EVT VT = N->getValueType(0);
2323 // fold (mulhs x, 0) -> 0
2324 if (N1C && N1C->isNullValue())
2326 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2327 if (N1C && N1C->getAPIntValue() == 1)
2328 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2329 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2330 getShiftAmountTy(N0.getValueType())));
2331 // fold (mulhs x, undef) -> 0
2332 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2333 return DAG.getConstant(0, VT);
2335 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2337 if (VT.isSimple() && !VT.isVector()) {
2338 MVT Simple = VT.getSimpleVT();
2339 unsigned SimpleSize = Simple.getSizeInBits();
2340 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2341 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2342 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2343 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2344 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2345 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2346 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2347 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2354 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2355 SDValue N0 = N->getOperand(0);
2356 SDValue N1 = N->getOperand(1);
2357 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2358 EVT VT = N->getValueType(0);
2361 // fold (mulhu x, 0) -> 0
2362 if (N1C && N1C->isNullValue())
2364 // fold (mulhu x, 1) -> 0
2365 if (N1C && N1C->getAPIntValue() == 1)
2366 return DAG.getConstant(0, N0.getValueType());
2367 // fold (mulhu x, undef) -> 0
2368 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2369 return DAG.getConstant(0, VT);
2371 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2373 if (VT.isSimple() && !VT.isVector()) {
2374 MVT Simple = VT.getSimpleVT();
2375 unsigned SimpleSize = Simple.getSizeInBits();
2376 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2377 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2378 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2379 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2380 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2381 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2382 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2383 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2390 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2391 /// give the opcodes for the two computations that are being performed. Return
2392 /// true if a simplification was made.
2393 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2395 // If the high half is not needed, just compute the low half.
2396 bool HiExists = N->hasAnyUseOfValue(1);
2398 (!LegalOperations ||
2399 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2400 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2401 return CombineTo(N, Res, Res);
2404 // If the low half is not needed, just compute the high half.
2405 bool LoExists = N->hasAnyUseOfValue(0);
2407 (!LegalOperations ||
2408 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2409 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2410 return CombineTo(N, Res, Res);
2413 // If both halves are used, return as it is.
2414 if (LoExists && HiExists)
2417 // If the two computed results can be simplified separately, separate them.
2419 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2420 AddToWorklist(Lo.getNode());
2421 SDValue LoOpt = combine(Lo.getNode());
2422 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2423 (!LegalOperations ||
2424 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2425 return CombineTo(N, LoOpt, LoOpt);
2429 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2430 AddToWorklist(Hi.getNode());
2431 SDValue HiOpt = combine(Hi.getNode());
2432 if (HiOpt.getNode() && HiOpt != Hi &&
2433 (!LegalOperations ||
2434 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2435 return CombineTo(N, HiOpt, HiOpt);
2441 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2442 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2443 if (Res.getNode()) return Res;
2445 EVT VT = N->getValueType(0);
2448 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2450 if (VT.isSimple() && !VT.isVector()) {
2451 MVT Simple = VT.getSimpleVT();
2452 unsigned SimpleSize = Simple.getSizeInBits();
2453 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2454 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2455 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2456 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2457 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2458 // Compute the high part as N1.
2459 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2460 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2461 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2462 // Compute the low part as N0.
2463 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2464 return CombineTo(N, Lo, Hi);
2471 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2472 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2473 if (Res.getNode()) return Res;
2475 EVT VT = N->getValueType(0);
2478 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2480 if (VT.isSimple() && !VT.isVector()) {
2481 MVT Simple = VT.getSimpleVT();
2482 unsigned SimpleSize = Simple.getSizeInBits();
2483 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2484 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2485 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2486 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2487 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2488 // Compute the high part as N1.
2489 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2490 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2491 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2492 // Compute the low part as N0.
2493 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2494 return CombineTo(N, Lo, Hi);
2501 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2502 // (smulo x, 2) -> (saddo x, x)
2503 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2504 if (C2->getAPIntValue() == 2)
2505 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2506 N->getOperand(0), N->getOperand(0));
2511 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2512 // (umulo x, 2) -> (uaddo x, x)
2513 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2514 if (C2->getAPIntValue() == 2)
2515 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2516 N->getOperand(0), N->getOperand(0));
2521 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2522 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2523 if (Res.getNode()) return Res;
2528 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2529 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2530 if (Res.getNode()) return Res;
2535 /// If this is a binary operator with two operands of the same opcode, try to
2537 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2538 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2539 EVT VT = N0.getValueType();
2540 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2542 // Bail early if none of these transforms apply.
2543 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2545 // For each of OP in AND/OR/XOR:
2546 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2547 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2548 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2549 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2550 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2552 // do not sink logical op inside of a vector extend, since it may combine
2554 EVT Op0VT = N0.getOperand(0).getValueType();
2555 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2556 N0.getOpcode() == ISD::SIGN_EXTEND ||
2557 N0.getOpcode() == ISD::BSWAP ||
2558 // Avoid infinite looping with PromoteIntBinOp.
2559 (N0.getOpcode() == ISD::ANY_EXTEND &&
2560 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2561 (N0.getOpcode() == ISD::TRUNCATE &&
2562 (!TLI.isZExtFree(VT, Op0VT) ||
2563 !TLI.isTruncateFree(Op0VT, VT)) &&
2564 TLI.isTypeLegal(Op0VT))) &&
2566 Op0VT == N1.getOperand(0).getValueType() &&
2567 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2568 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2569 N0.getOperand(0).getValueType(),
2570 N0.getOperand(0), N1.getOperand(0));
2571 AddToWorklist(ORNode.getNode());
2572 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2575 // For each of OP in SHL/SRL/SRA/AND...
2576 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2577 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2578 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2579 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2580 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2581 N0.getOperand(1) == N1.getOperand(1)) {
2582 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2583 N0.getOperand(0).getValueType(),
2584 N0.getOperand(0), N1.getOperand(0));
2585 AddToWorklist(ORNode.getNode());
2586 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2587 ORNode, N0.getOperand(1));
2590 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2591 // Only perform this optimization after type legalization and before
2592 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2593 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2594 // we don't want to undo this promotion.
2595 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2597 if ((N0.getOpcode() == ISD::BITCAST ||
2598 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2599 Level == AfterLegalizeTypes) {
2600 SDValue In0 = N0.getOperand(0);
2601 SDValue In1 = N1.getOperand(0);
2602 EVT In0Ty = In0.getValueType();
2603 EVT In1Ty = In1.getValueType();
2605 // If both incoming values are integers, and the original types are the
2607 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2608 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2609 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2610 AddToWorklist(Op.getNode());
2615 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2616 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2617 // If both shuffles use the same mask, and both shuffle within a single
2618 // vector, then it is worthwhile to move the swizzle after the operation.
2619 // The type-legalizer generates this pattern when loading illegal
2620 // vector types from memory. In many cases this allows additional shuffle
2622 // There are other cases where moving the shuffle after the xor/and/or
2623 // is profitable even if shuffles don't perform a swizzle.
2624 // If both shuffles use the same mask, and both shuffles have the same first
2625 // or second operand, then it might still be profitable to move the shuffle
2626 // after the xor/and/or operation.
2627 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2628 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2629 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2631 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2632 "Inputs to shuffles are not the same type");
2634 // Check that both shuffles use the same mask. The masks are known to be of
2635 // the same length because the result vector type is the same.
2636 // Check also that shuffles have only one use to avoid introducing extra
2638 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2639 SVN0->getMask().equals(SVN1->getMask())) {
2640 SDValue ShOp = N0->getOperand(1);
2642 // Don't try to fold this node if it requires introducing a
2643 // build vector of all zeros that might be illegal at this stage.
2644 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2646 ShOp = DAG.getConstant(0, VT);
2651 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2652 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2653 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2654 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2655 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2656 N0->getOperand(0), N1->getOperand(0));
2657 AddToWorklist(NewNode.getNode());
2658 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2659 &SVN0->getMask()[0]);
2662 // Don't try to fold this node if it requires introducing a
2663 // build vector of all zeros that might be illegal at this stage.
2664 ShOp = N0->getOperand(0);
2665 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2667 ShOp = DAG.getConstant(0, VT);
2672 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2673 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2674 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2675 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2676 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2677 N0->getOperand(1), N1->getOperand(1));
2678 AddToWorklist(NewNode.getNode());
2679 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2680 &SVN0->getMask()[0]);
2688 SDValue DAGCombiner::visitAND(SDNode *N) {
2689 SDValue N0 = N->getOperand(0);
2690 SDValue N1 = N->getOperand(1);
2691 SDValue LL, LR, RL, RR, CC0, CC1;
2692 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2693 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2694 EVT VT = N1.getValueType();
2695 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2698 if (VT.isVector()) {
2699 SDValue FoldedVOp = SimplifyVBinOp(N);
2700 if (FoldedVOp.getNode()) return FoldedVOp;
2702 // fold (and x, 0) -> 0, vector edition
2703 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2704 // do not return N0, because undef node may exist in N0
2705 return DAG.getConstant(
2706 APInt::getNullValue(
2707 N0.getValueType().getScalarType().getSizeInBits()),
2709 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2710 // do not return N1, because undef node may exist in N1
2711 return DAG.getConstant(
2712 APInt::getNullValue(
2713 N1.getValueType().getScalarType().getSizeInBits()),
2716 // fold (and x, -1) -> x, vector edition
2717 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2719 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2723 // fold (and x, undef) -> 0
2724 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2725 return DAG.getConstant(0, VT);
2726 // fold (and c1, c2) -> c1&c2
2728 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2729 // canonicalize constant to RHS
2731 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2732 // fold (and x, -1) -> x
2733 if (N1C && N1C->isAllOnesValue())
2735 // if (and x, c) is known to be zero, return 0
2736 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2737 APInt::getAllOnesValue(BitWidth)))
2738 return DAG.getConstant(0, VT);
2740 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2743 // fold (and (or x, C), D) -> D if (C & D) == D
2744 if (N1C && N0.getOpcode() == ISD::OR)
2745 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2746 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2748 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2749 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2750 SDValue N0Op0 = N0.getOperand(0);
2751 APInt Mask = ~N1C->getAPIntValue();
2752 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2753 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2754 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2755 N0.getValueType(), N0Op0);
2757 // Replace uses of the AND with uses of the Zero extend node.
2760 // We actually want to replace all uses of the any_extend with the
2761 // zero_extend, to avoid duplicating things. This will later cause this
2762 // AND to be folded.
2763 CombineTo(N0.getNode(), Zext);
2764 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2767 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2768 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2769 // already be zero by virtue of the width of the base type of the load.
2771 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2773 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2774 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2775 N0.getOpcode() == ISD::LOAD) {
2776 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2777 N0 : N0.getOperand(0) );
2779 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2780 // This can be a pure constant or a vector splat, in which case we treat the
2781 // vector as a scalar and use the splat value.
2782 APInt Constant = APInt::getNullValue(1);
2783 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2784 Constant = C->getAPIntValue();
2785 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2786 APInt SplatValue, SplatUndef;
2787 unsigned SplatBitSize;
2789 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2790 SplatBitSize, HasAnyUndefs);
2792 // Undef bits can contribute to a possible optimisation if set, so
2794 SplatValue |= SplatUndef;
2796 // The splat value may be something like "0x00FFFFFF", which means 0 for
2797 // the first vector value and FF for the rest, repeating. We need a mask
2798 // that will apply equally to all members of the vector, so AND all the
2799 // lanes of the constant together.
2800 EVT VT = Vector->getValueType(0);
2801 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2803 // If the splat value has been compressed to a bitlength lower
2804 // than the size of the vector lane, we need to re-expand it to
2806 if (BitWidth > SplatBitSize)
2807 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2808 SplatBitSize < BitWidth;
2809 SplatBitSize = SplatBitSize * 2)
2810 SplatValue |= SplatValue.shl(SplatBitSize);
2812 Constant = APInt::getAllOnesValue(BitWidth);
2813 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2814 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2818 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2819 // actually legal and isn't going to get expanded, else this is a false
2821 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2822 Load->getValueType(0),
2823 Load->getMemoryVT());
2825 // Resize the constant to the same size as the original memory access before
2826 // extension. If it is still the AllOnesValue then this AND is completely
2829 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2832 switch (Load->getExtensionType()) {
2833 default: B = false; break;
2834 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2836 case ISD::NON_EXTLOAD: B = true; break;
2839 if (B && Constant.isAllOnesValue()) {
2840 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2841 // preserve semantics once we get rid of the AND.
2842 SDValue NewLoad(Load, 0);
2843 if (Load->getExtensionType() == ISD::EXTLOAD) {
2844 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2845 Load->getValueType(0), SDLoc(Load),
2846 Load->getChain(), Load->getBasePtr(),
2847 Load->getOffset(), Load->getMemoryVT(),
2848 Load->getMemOperand());
2849 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2850 if (Load->getNumValues() == 3) {
2851 // PRE/POST_INC loads have 3 values.
2852 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2853 NewLoad.getValue(2) };
2854 CombineTo(Load, To, 3, true);
2856 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2860 // Fold the AND away, taking care not to fold to the old load node if we
2862 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2864 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2867 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2868 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2869 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2870 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2872 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2873 LL.getValueType().isInteger()) {
2874 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2875 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2876 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2877 LR.getValueType(), LL, RL);
2878 AddToWorklist(ORNode.getNode());
2879 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2881 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2882 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2883 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2884 LR.getValueType(), LL, RL);
2885 AddToWorklist(ANDNode.getNode());
2886 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2888 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2889 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2890 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2891 LR.getValueType(), LL, RL);
2892 AddToWorklist(ORNode.getNode());
2893 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2896 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2897 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2898 Op0 == Op1 && LL.getValueType().isInteger() &&
2899 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2900 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2901 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2902 cast<ConstantSDNode>(RR)->isNullValue()))) {
2903 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2904 LL, DAG.getConstant(1, LL.getValueType()));
2905 AddToWorklist(ADDNode.getNode());
2906 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2907 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2909 // canonicalize equivalent to ll == rl
2910 if (LL == RR && LR == RL) {
2911 Op1 = ISD::getSetCCSwappedOperands(Op1);
2914 if (LL == RL && LR == RR) {
2915 bool isInteger = LL.getValueType().isInteger();
2916 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2917 if (Result != ISD::SETCC_INVALID &&
2918 (!LegalOperations ||
2919 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2920 TLI.isOperationLegal(ISD::SETCC,
2921 getSetCCResultType(N0.getSimpleValueType())))))
2922 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2927 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2928 if (N0.getOpcode() == N1.getOpcode()) {
2929 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2930 if (Tmp.getNode()) return Tmp;
2933 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2934 // fold (and (sra)) -> (and (srl)) when possible.
2935 if (!VT.isVector() &&
2936 SimplifyDemandedBits(SDValue(N, 0)))
2937 return SDValue(N, 0);
2939 // fold (zext_inreg (extload x)) -> (zextload x)
2940 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2941 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2942 EVT MemVT = LN0->getMemoryVT();
2943 // If we zero all the possible extended bits, then we can turn this into
2944 // a zextload if we are running before legalize or the operation is legal.
2945 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2946 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2947 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2948 ((!LegalOperations && !LN0->isVolatile()) ||
2949 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
2950 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2951 LN0->getChain(), LN0->getBasePtr(),
2952 MemVT, LN0->getMemOperand());
2954 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2955 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2958 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2959 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2961 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2962 EVT MemVT = LN0->getMemoryVT();
2963 // If we zero all the possible extended bits, then we can turn this into
2964 // a zextload if we are running before legalize or the operation is legal.
2965 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2966 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2967 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2968 ((!LegalOperations && !LN0->isVolatile()) ||
2969 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
2970 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2971 LN0->getChain(), LN0->getBasePtr(),
2972 MemVT, LN0->getMemOperand());
2974 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2975 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2979 // fold (and (load x), 255) -> (zextload x, i8)
2980 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2981 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2982 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2983 (N0.getOpcode() == ISD::ANY_EXTEND &&
2984 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2985 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2986 LoadSDNode *LN0 = HasAnyExt
2987 ? cast<LoadSDNode>(N0.getOperand(0))
2988 : cast<LoadSDNode>(N0);
2989 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2990 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2991 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2992 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2993 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2994 EVT LoadedVT = LN0->getMemoryVT();
2995 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2997 if (ExtVT == LoadedVT &&
2998 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3002 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3003 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3004 LN0->getMemOperand());
3006 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3007 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3010 // Do not change the width of a volatile load.
3011 // Do not generate loads of non-round integer types since these can
3012 // be expensive (and would be wrong if the type is not byte sized).
3013 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3014 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3016 EVT PtrType = LN0->getOperand(1).getValueType();
3018 unsigned Alignment = LN0->getAlignment();
3019 SDValue NewPtr = LN0->getBasePtr();
3021 // For big endian targets, we need to add an offset to the pointer
3022 // to load the correct bytes. For little endian systems, we merely
3023 // need to read fewer bytes from the same pointer.
3024 if (TLI.isBigEndian()) {
3025 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3026 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3027 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3028 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
3029 NewPtr, DAG.getConstant(PtrOff, PtrType));
3030 Alignment = MinAlign(Alignment, PtrOff);
3033 AddToWorklist(NewPtr.getNode());
3036 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3037 LN0->getChain(), NewPtr,
3038 LN0->getPointerInfo(),
3039 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3040 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3042 CombineTo(LN0, Load, Load.getValue(1));
3043 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3049 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3050 VT.getSizeInBits() <= 64) {
3051 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3052 APInt ADDC = ADDI->getAPIntValue();
3053 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3054 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3055 // immediate for an add, but it is legal if its top c2 bits are set,
3056 // transform the ADD so the immediate doesn't need to be materialized
3058 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3059 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3060 SRLI->getZExtValue());
3061 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3063 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3065 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3066 N0.getOperand(0), DAG.getConstant(ADDC, VT));
3067 CombineTo(N0.getNode(), NewAdd);
3068 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3076 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3077 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3078 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3079 N0.getOperand(1), false);
3080 if (BSwap.getNode())
3087 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3088 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3089 bool DemandHighBits) {
3090 if (!LegalOperations)
3093 EVT VT = N->getValueType(0);
3094 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3096 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3099 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3100 bool LookPassAnd0 = false;
3101 bool LookPassAnd1 = false;
3102 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3104 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3106 if (N0.getOpcode() == ISD::AND) {
3107 if (!N0.getNode()->hasOneUse())
3109 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3110 if (!N01C || N01C->getZExtValue() != 0xFF00)
3112 N0 = N0.getOperand(0);
3113 LookPassAnd0 = true;
3116 if (N1.getOpcode() == ISD::AND) {
3117 if (!N1.getNode()->hasOneUse())
3119 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3120 if (!N11C || N11C->getZExtValue() != 0xFF)
3122 N1 = N1.getOperand(0);
3123 LookPassAnd1 = true;
3126 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3128 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3130 if (!N0.getNode()->hasOneUse() ||
3131 !N1.getNode()->hasOneUse())
3134 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3135 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3138 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3141 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3142 SDValue N00 = N0->getOperand(0);
3143 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3144 if (!N00.getNode()->hasOneUse())
3146 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3147 if (!N001C || N001C->getZExtValue() != 0xFF)
3149 N00 = N00.getOperand(0);
3150 LookPassAnd0 = true;
3153 SDValue N10 = N1->getOperand(0);
3154 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3155 if (!N10.getNode()->hasOneUse())
3157 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3158 if (!N101C || N101C->getZExtValue() != 0xFF00)
3160 N10 = N10.getOperand(0);
3161 LookPassAnd1 = true;
3167 // Make sure everything beyond the low halfword gets set to zero since the SRL
3168 // 16 will clear the top bits.
3169 unsigned OpSizeInBits = VT.getSizeInBits();
3170 if (DemandHighBits && OpSizeInBits > 16) {
3171 // If the left-shift isn't masked out then the only way this is a bswap is
3172 // if all bits beyond the low 8 are 0. In that case the entire pattern
3173 // reduces to a left shift anyway: leave it for other parts of the combiner.
3177 // However, if the right shift isn't masked out then it might be because
3178 // it's not needed. See if we can spot that too.
3179 if (!LookPassAnd1 &&
3180 !DAG.MaskedValueIsZero(
3181 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3185 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3186 if (OpSizeInBits > 16)
3187 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3188 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3192 /// Return true if the specified node is an element that makes up a 32-bit
3193 /// packed halfword byteswap.
3194 /// ((x & 0x000000ff) << 8) |
3195 /// ((x & 0x0000ff00) >> 8) |
3196 /// ((x & 0x00ff0000) << 8) |
3197 /// ((x & 0xff000000) >> 8)
3198 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3199 if (!N.getNode()->hasOneUse())
3202 unsigned Opc = N.getOpcode();
3203 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3206 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3211 switch (N1C->getZExtValue()) {
3214 case 0xFF: Num = 0; break;
3215 case 0xFF00: Num = 1; break;
3216 case 0xFF0000: Num = 2; break;
3217 case 0xFF000000: Num = 3; break;
3220 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3221 SDValue N0 = N.getOperand(0);
3222 if (Opc == ISD::AND) {
3223 if (Num == 0 || Num == 2) {
3225 // (x >> 8) & 0xff0000
3226 if (N0.getOpcode() != ISD::SRL)
3228 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3229 if (!C || C->getZExtValue() != 8)
3232 // (x << 8) & 0xff00
3233 // (x << 8) & 0xff000000
3234 if (N0.getOpcode() != ISD::SHL)
3236 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3237 if (!C || C->getZExtValue() != 8)
3240 } else if (Opc == ISD::SHL) {
3242 // (x & 0xff0000) << 8
3243 if (Num != 0 && Num != 2)
3245 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3246 if (!C || C->getZExtValue() != 8)
3248 } else { // Opc == ISD::SRL
3249 // (x & 0xff00) >> 8
3250 // (x & 0xff000000) >> 8
3251 if (Num != 1 && Num != 3)
3253 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3254 if (!C || C->getZExtValue() != 8)
3261 Parts[Num] = N0.getOperand(0).getNode();
3265 /// Match a 32-bit packed halfword bswap. That is
3266 /// ((x & 0x000000ff) << 8) |
3267 /// ((x & 0x0000ff00) >> 8) |
3268 /// ((x & 0x00ff0000) << 8) |
3269 /// ((x & 0xff000000) >> 8)
3270 /// => (rotl (bswap x), 16)
3271 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3272 if (!LegalOperations)
3275 EVT VT = N->getValueType(0);
3278 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3282 // (or (or (and), (and)), (or (and), (and)))
3283 // (or (or (or (and), (and)), (and)), (and))
3284 if (N0.getOpcode() != ISD::OR)
3286 SDValue N00 = N0.getOperand(0);
3287 SDValue N01 = N0.getOperand(1);
3288 SDNode *Parts[4] = {};
3290 if (N1.getOpcode() == ISD::OR &&
3291 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3292 // (or (or (and), (and)), (or (and), (and)))
3293 SDValue N000 = N00.getOperand(0);
3294 if (!isBSwapHWordElement(N000, Parts))
3297 SDValue N001 = N00.getOperand(1);
3298 if (!isBSwapHWordElement(N001, Parts))
3300 SDValue N010 = N01.getOperand(0);
3301 if (!isBSwapHWordElement(N010, Parts))
3303 SDValue N011 = N01.getOperand(1);
3304 if (!isBSwapHWordElement(N011, Parts))
3307 // (or (or (or (and), (and)), (and)), (and))
3308 if (!isBSwapHWordElement(N1, Parts))
3310 if (!isBSwapHWordElement(N01, Parts))
3312 if (N00.getOpcode() != ISD::OR)
3314 SDValue N000 = N00.getOperand(0);
3315 if (!isBSwapHWordElement(N000, Parts))
3317 SDValue N001 = N00.getOperand(1);
3318 if (!isBSwapHWordElement(N001, Parts))
3322 // Make sure the parts are all coming from the same node.
3323 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3326 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3327 SDValue(Parts[0],0));
3329 // Result of the bswap should be rotated by 16. If it's not legal, then
3330 // do (x << 16) | (x >> 16).
3331 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3332 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3333 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3334 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3335 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3336 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3337 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3338 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3341 SDValue DAGCombiner::visitOR(SDNode *N) {
3342 SDValue N0 = N->getOperand(0);
3343 SDValue N1 = N->getOperand(1);
3344 SDValue LL, LR, RL, RR, CC0, CC1;
3345 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3346 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3347 EVT VT = N1.getValueType();
3350 if (VT.isVector()) {
3351 SDValue FoldedVOp = SimplifyVBinOp(N);
3352 if (FoldedVOp.getNode()) return FoldedVOp;
3354 // fold (or x, 0) -> x, vector edition
3355 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3357 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3360 // fold (or x, -1) -> -1, vector edition
3361 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3362 // do not return N0, because undef node may exist in N0
3363 return DAG.getConstant(
3364 APInt::getAllOnesValue(
3365 N0.getValueType().getScalarType().getSizeInBits()),
3367 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3368 // do not return N1, because undef node may exist in N1
3369 return DAG.getConstant(
3370 APInt::getAllOnesValue(
3371 N1.getValueType().getScalarType().getSizeInBits()),
3374 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3375 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3376 // Do this only if the resulting shuffle is legal.
3377 if (isa<ShuffleVectorSDNode>(N0) &&
3378 isa<ShuffleVectorSDNode>(N1) &&
3379 // Avoid folding a node with illegal type.
3380 TLI.isTypeLegal(VT) &&
3381 N0->getOperand(1) == N1->getOperand(1) &&
3382 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3383 bool CanFold = true;
3384 unsigned NumElts = VT.getVectorNumElements();
3385 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3386 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3387 // We construct two shuffle masks:
3388 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3389 // and N1 as the second operand.
3390 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3391 // and N0 as the second operand.
3392 // We do this because OR is commutable and therefore there might be
3393 // two ways to fold this node into a shuffle.
3394 SmallVector<int,4> Mask1;
3395 SmallVector<int,4> Mask2;
3397 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3398 int M0 = SV0->getMaskElt(i);
3399 int M1 = SV1->getMaskElt(i);
3401 // Both shuffle indexes are undef. Propagate Undef.
3402 if (M0 < 0 && M1 < 0) {
3403 Mask1.push_back(M0);
3404 Mask2.push_back(M0);
3408 if (M0 < 0 || M1 < 0 ||
3409 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3410 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3415 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3416 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3420 // Fold this sequence only if the resulting shuffle is 'legal'.
3421 if (TLI.isShuffleMaskLegal(Mask1, VT))
3422 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3423 N1->getOperand(0), &Mask1[0]);
3424 if (TLI.isShuffleMaskLegal(Mask2, VT))
3425 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3426 N0->getOperand(0), &Mask2[0]);
3431 // fold (or x, undef) -> -1
3432 if (!LegalOperations &&
3433 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3434 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3435 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3437 // fold (or c1, c2) -> c1|c2
3439 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3440 // canonicalize constant to RHS
3442 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3443 // fold (or x, 0) -> x
3444 if (N1C && N1C->isNullValue())
3446 // fold (or x, -1) -> -1
3447 if (N1C && N1C->isAllOnesValue())
3449 // fold (or x, c) -> c iff (x & ~c) == 0
3450 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3453 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3454 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3455 if (BSwap.getNode())
3457 BSwap = MatchBSwapHWordLow(N, N0, N1);
3458 if (BSwap.getNode())
3462 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3465 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3466 // iff (c1 & c2) == 0.
3467 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3468 isa<ConstantSDNode>(N0.getOperand(1))) {
3469 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3470 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3471 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1))
3473 ISD::AND, SDLoc(N), VT,
3474 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3478 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3479 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3480 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3481 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3483 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3484 LL.getValueType().isInteger()) {
3485 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3486 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3487 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3488 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3489 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3490 LR.getValueType(), LL, RL);
3491 AddToWorklist(ORNode.getNode());
3492 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3494 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3495 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3496 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3497 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3498 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3499 LR.getValueType(), LL, RL);
3500 AddToWorklist(ANDNode.getNode());
3501 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3504 // canonicalize equivalent to ll == rl
3505 if (LL == RR && LR == RL) {
3506 Op1 = ISD::getSetCCSwappedOperands(Op1);
3509 if (LL == RL && LR == RR) {
3510 bool isInteger = LL.getValueType().isInteger();
3511 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3512 if (Result != ISD::SETCC_INVALID &&
3513 (!LegalOperations ||
3514 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3515 TLI.isOperationLegal(ISD::SETCC,
3516 getSetCCResultType(N0.getValueType())))))
3517 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3522 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3523 if (N0.getOpcode() == N1.getOpcode()) {
3524 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3525 if (Tmp.getNode()) return Tmp;
3528 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3529 if (N0.getOpcode() == ISD::AND &&
3530 N1.getOpcode() == ISD::AND &&
3531 N0.getOperand(1).getOpcode() == ISD::Constant &&
3532 N1.getOperand(1).getOpcode() == ISD::Constant &&
3533 // Don't increase # computations.
3534 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3535 // We can only do this xform if we know that bits from X that are set in C2
3536 // but not in C1 are already zero. Likewise for Y.
3537 const APInt &LHSMask =
3538 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3539 const APInt &RHSMask =
3540 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3542 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3543 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3544 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3545 N0.getOperand(0), N1.getOperand(0));
3546 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3547 DAG.getConstant(LHSMask | RHSMask, VT));
3551 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3552 if (N0.getOpcode() == ISD::AND &&
3553 N1.getOpcode() == ISD::AND &&
3554 N0.getOperand(0) == N1.getOperand(0) &&
3555 // Don't increase # computations.
3556 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3557 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3558 N0.getOperand(1), N1.getOperand(1));
3559 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0), X);
3562 // See if this is some rotate idiom.
3563 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3564 return SDValue(Rot, 0);
3566 // Simplify the operands using demanded-bits information.
3567 if (!VT.isVector() &&
3568 SimplifyDemandedBits(SDValue(N, 0)))
3569 return SDValue(N, 0);
3574 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3575 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3576 if (Op.getOpcode() == ISD::AND) {
3577 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3578 Mask = Op.getOperand(1);
3579 Op = Op.getOperand(0);
3585 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3593 // Return true if we can prove that, whenever Neg and Pos are both in the
3594 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3595 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3597 // (or (shift1 X, Neg), (shift2 X, Pos))
3599 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3600 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3601 // to consider shift amounts with defined behavior.
3602 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3603 // If OpSize is a power of 2 then:
3605 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3606 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3608 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3609 // for the stronger condition:
3611 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3613 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3614 // we can just replace Neg with Neg' for the rest of the function.
3616 // In other cases we check for the even stronger condition:
3618 // Neg == OpSize - Pos [B]
3620 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3621 // behavior if Pos == 0 (and consequently Neg == OpSize).
3623 // We could actually use [A] whenever OpSize is a power of 2, but the
3624 // only extra cases that it would match are those uninteresting ones
3625 // where Neg and Pos are never in range at the same time. E.g. for
3626 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3627 // as well as (sub 32, Pos), but:
3629 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3631 // always invokes undefined behavior for 32-bit X.
3633 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3634 unsigned MaskLoBits = 0;
3635 if (Neg.getOpcode() == ISD::AND &&
3636 isPowerOf2_64(OpSize) &&
3637 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3638 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3639 Neg = Neg.getOperand(0);
3640 MaskLoBits = Log2_64(OpSize);
3643 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3644 if (Neg.getOpcode() != ISD::SUB)
3646 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3649 SDValue NegOp1 = Neg.getOperand(1);
3651 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3652 // Pos'. The truncation is redundant for the purpose of the equality.
3654 Pos.getOpcode() == ISD::AND &&
3655 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3656 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3657 Pos = Pos.getOperand(0);
3659 // The condition we need is now:
3661 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3663 // If NegOp1 == Pos then we need:
3665 // OpSize & Mask == NegC & Mask
3667 // (because "x & Mask" is a truncation and distributes through subtraction).
3670 Width = NegC->getAPIntValue();
3671 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3672 // Then the condition we want to prove becomes:
3674 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3676 // which, again because "x & Mask" is a truncation, becomes:
3678 // NegC & Mask == (OpSize - PosC) & Mask
3679 // OpSize & Mask == (NegC + PosC) & Mask
3680 else if (Pos.getOpcode() == ISD::ADD &&
3681 Pos.getOperand(0) == NegOp1 &&
3682 Pos.getOperand(1).getOpcode() == ISD::Constant)
3683 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3684 NegC->getAPIntValue());
3688 // Now we just need to check that OpSize & Mask == Width & Mask.
3690 // Opsize & Mask is 0 since Mask is Opsize - 1.
3691 return Width.getLoBits(MaskLoBits) == 0;
3692 return Width == OpSize;
3695 // A subroutine of MatchRotate used once we have found an OR of two opposite
3696 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3697 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3698 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3699 // Neg with outer conversions stripped away.
3700 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3701 SDValue Neg, SDValue InnerPos,
3702 SDValue InnerNeg, unsigned PosOpcode,
3703 unsigned NegOpcode, SDLoc DL) {
3704 // fold (or (shl x, (*ext y)),
3705 // (srl x, (*ext (sub 32, y)))) ->
3706 // (rotl x, y) or (rotr x, (sub 32, y))
3708 // fold (or (shl x, (*ext (sub 32, y))),
3709 // (srl x, (*ext y))) ->
3710 // (rotr x, y) or (rotl x, (sub 32, y))
3711 EVT VT = Shifted.getValueType();
3712 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3713 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3714 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3715 HasPos ? Pos : Neg).getNode();
3721 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3722 // idioms for rotate, and if the target supports rotation instructions, generate
3724 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3725 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3726 EVT VT = LHS.getValueType();
3727 if (!TLI.isTypeLegal(VT)) return nullptr;
3729 // The target must have at least one rotate flavor.
3730 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3731 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3732 if (!HasROTL && !HasROTR) return nullptr;
3734 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3735 SDValue LHSShift; // The shift.
3736 SDValue LHSMask; // AND value if any.
3737 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3738 return nullptr; // Not part of a rotate.
3740 SDValue RHSShift; // The shift.
3741 SDValue RHSMask; // AND value if any.
3742 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3743 return nullptr; // Not part of a rotate.
3745 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3746 return nullptr; // Not shifting the same value.
3748 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3749 return nullptr; // Shifts must disagree.
3751 // Canonicalize shl to left side in a shl/srl pair.
3752 if (RHSShift.getOpcode() == ISD::SHL) {
3753 std::swap(LHS, RHS);
3754 std::swap(LHSShift, RHSShift);
3755 std::swap(LHSMask , RHSMask );
3758 unsigned OpSizeInBits = VT.getSizeInBits();
3759 SDValue LHSShiftArg = LHSShift.getOperand(0);
3760 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3761 SDValue RHSShiftArg = RHSShift.getOperand(0);
3762 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3764 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3765 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3766 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3767 RHSShiftAmt.getOpcode() == ISD::Constant) {
3768 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3769 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3770 if ((LShVal + RShVal) != OpSizeInBits)
3773 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3774 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3776 // If there is an AND of either shifted operand, apply it to the result.
3777 if (LHSMask.getNode() || RHSMask.getNode()) {
3778 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3780 if (LHSMask.getNode()) {
3781 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3782 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3784 if (RHSMask.getNode()) {
3785 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3786 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3789 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3792 return Rot.getNode();
3795 // If there is a mask here, and we have a variable shift, we can't be sure
3796 // that we're masking out the right stuff.
3797 if (LHSMask.getNode() || RHSMask.getNode())
3800 // If the shift amount is sign/zext/any-extended just peel it off.
3801 SDValue LExtOp0 = LHSShiftAmt;
3802 SDValue RExtOp0 = RHSShiftAmt;
3803 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3804 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3805 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3806 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3807 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3808 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3809 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3810 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3811 LExtOp0 = LHSShiftAmt.getOperand(0);
3812 RExtOp0 = RHSShiftAmt.getOperand(0);
3815 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3816 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3820 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3821 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3828 SDValue DAGCombiner::visitXOR(SDNode *N) {
3829 SDValue N0 = N->getOperand(0);
3830 SDValue N1 = N->getOperand(1);
3831 SDValue LHS, RHS, CC;
3832 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3833 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3834 EVT VT = N0.getValueType();
3837 if (VT.isVector()) {
3838 SDValue FoldedVOp = SimplifyVBinOp(N);
3839 if (FoldedVOp.getNode()) return FoldedVOp;
3841 // fold (xor x, 0) -> x, vector edition
3842 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3844 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3848 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3849 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3850 return DAG.getConstant(0, VT);
3851 // fold (xor x, undef) -> undef
3852 if (N0.getOpcode() == ISD::UNDEF)
3854 if (N1.getOpcode() == ISD::UNDEF)
3856 // fold (xor c1, c2) -> c1^c2
3858 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3859 // canonicalize constant to RHS
3861 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3862 // fold (xor x, 0) -> x
3863 if (N1C && N1C->isNullValue())
3866 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3870 // fold !(x cc y) -> (x !cc y)
3871 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3872 bool isInt = LHS.getValueType().isInteger();
3873 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3876 if (!LegalOperations ||
3877 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3878 switch (N0.getOpcode()) {
3880 llvm_unreachable("Unhandled SetCC Equivalent!");
3882 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3883 case ISD::SELECT_CC:
3884 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3885 N0.getOperand(3), NotCC);
3890 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3891 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3892 N0.getNode()->hasOneUse() &&
3893 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3894 SDValue V = N0.getOperand(0);
3895 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3896 DAG.getConstant(1, V.getValueType()));
3897 AddToWorklist(V.getNode());
3898 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3901 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3902 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3903 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3904 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3905 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3906 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3907 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3908 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3909 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3910 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3913 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3914 if (N1C && N1C->isAllOnesValue() &&
3915 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3916 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3917 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3918 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3919 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3920 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3921 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3922 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3925 // fold (xor (and x, y), y) -> (and (not x), y)
3926 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3927 N0->getOperand(1) == N1) {
3928 SDValue X = N0->getOperand(0);
3929 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3930 AddToWorklist(NotX.getNode());
3931 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3933 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3934 if (N1C && N0.getOpcode() == ISD::XOR) {
3935 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3936 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3938 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3939 DAG.getConstant(N1C->getAPIntValue() ^
3940 N00C->getAPIntValue(), VT));
3942 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3943 DAG.getConstant(N1C->getAPIntValue() ^
3944 N01C->getAPIntValue(), VT));
3946 // fold (xor x, x) -> 0
3948 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3950 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3951 if (N0.getOpcode() == N1.getOpcode()) {
3952 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3953 if (Tmp.getNode()) return Tmp;
3956 // Simplify the expression using non-local knowledge.
3957 if (!VT.isVector() &&
3958 SimplifyDemandedBits(SDValue(N, 0)))
3959 return SDValue(N, 0);
3964 /// Handle transforms common to the three shifts, when the shift amount is a
3966 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3967 // We can't and shouldn't fold opaque constants.
3968 if (Amt->isOpaque())
3971 SDNode *LHS = N->getOperand(0).getNode();
3972 if (!LHS->hasOneUse()) return SDValue();
3974 // We want to pull some binops through shifts, so that we have (and (shift))
3975 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3976 // thing happens with address calculations, so it's important to canonicalize
3978 bool HighBitSet = false; // Can we transform this if the high bit is set?
3980 switch (LHS->getOpcode()) {
3981 default: return SDValue();
3984 HighBitSet = false; // We can only transform sra if the high bit is clear.
3987 HighBitSet = true; // We can only transform sra if the high bit is set.
3990 if (N->getOpcode() != ISD::SHL)
3991 return SDValue(); // only shl(add) not sr[al](add).
3992 HighBitSet = false; // We can only transform sra if the high bit is clear.
3996 // We require the RHS of the binop to be a constant and not opaque as well.
3997 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3998 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
4000 // FIXME: disable this unless the input to the binop is a shift by a constant.
4001 // If it is not a shift, it pessimizes some common cases like:
4003 // void foo(int *X, int i) { X[i & 1235] = 1; }
4004 // int bar(int *X, int i) { return X[i & 255]; }
4005 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4006 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4007 BinOpLHSVal->getOpcode() != ISD::SRA &&
4008 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4009 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4012 EVT VT = N->getValueType(0);
4014 // If this is a signed shift right, and the high bit is modified by the
4015 // logical operation, do not perform the transformation. The highBitSet
4016 // boolean indicates the value of the high bit of the constant which would
4017 // cause it to be modified for this operation.
4018 if (N->getOpcode() == ISD::SRA) {
4019 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4020 if (BinOpRHSSignSet != HighBitSet)
4024 if (!TLI.isDesirableToCommuteWithShift(LHS))
4027 // Fold the constants, shifting the binop RHS by the shift amount.
4028 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4030 LHS->getOperand(1), N->getOperand(1));
4031 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4033 // Create the new shift.
4034 SDValue NewShift = DAG.getNode(N->getOpcode(),
4035 SDLoc(LHS->getOperand(0)),
4036 VT, LHS->getOperand(0), N->getOperand(1));
4038 // Create the new binop.
4039 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4042 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4043 assert(N->getOpcode() == ISD::TRUNCATE);
4044 assert(N->getOperand(0).getOpcode() == ISD::AND);
4046 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4047 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4048 SDValue N01 = N->getOperand(0).getOperand(1);
4050 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4051 EVT TruncVT = N->getValueType(0);
4052 SDValue N00 = N->getOperand(0).getOperand(0);
4053 APInt TruncC = N01C->getAPIntValue();
4054 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4056 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4057 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4058 DAG.getConstant(TruncC, TruncVT));
4065 SDValue DAGCombiner::visitRotate(SDNode *N) {
4066 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4067 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4068 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4069 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4070 if (NewOp1.getNode())
4071 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4072 N->getOperand(0), NewOp1);
4077 SDValue DAGCombiner::visitSHL(SDNode *N) {
4078 SDValue N0 = N->getOperand(0);
4079 SDValue N1 = N->getOperand(1);
4080 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4081 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4082 EVT VT = N0.getValueType();
4083 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4086 if (VT.isVector()) {
4087 SDValue FoldedVOp = SimplifyVBinOp(N);
4088 if (FoldedVOp.getNode()) return FoldedVOp;
4090 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4091 // If setcc produces all-one true value then:
4092 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4093 if (N1CV && N1CV->isConstant()) {
4094 if (N0.getOpcode() == ISD::AND) {
4095 SDValue N00 = N0->getOperand(0);
4096 SDValue N01 = N0->getOperand(1);
4097 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4099 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4100 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4101 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4102 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV))
4103 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4106 N1C = isConstOrConstSplat(N1);
4111 // fold (shl c1, c2) -> c1<<c2
4113 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4114 // fold (shl 0, x) -> 0
4115 if (N0C && N0C->isNullValue())
4117 // fold (shl x, c >= size(x)) -> undef
4118 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4119 return DAG.getUNDEF(VT);
4120 // fold (shl x, 0) -> x
4121 if (N1C && N1C->isNullValue())
4123 // fold (shl undef, x) -> 0
4124 if (N0.getOpcode() == ISD::UNDEF)
4125 return DAG.getConstant(0, VT);
4126 // if (shl x, c) is known to be zero, return 0
4127 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4128 APInt::getAllOnesValue(OpSizeInBits)))
4129 return DAG.getConstant(0, VT);
4130 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4131 if (N1.getOpcode() == ISD::TRUNCATE &&
4132 N1.getOperand(0).getOpcode() == ISD::AND) {
4133 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4134 if (NewOp1.getNode())
4135 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4138 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4139 return SDValue(N, 0);
4141 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4142 if (N1C && N0.getOpcode() == ISD::SHL) {
4143 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4144 uint64_t c1 = N0C1->getZExtValue();
4145 uint64_t c2 = N1C->getZExtValue();
4146 if (c1 + c2 >= OpSizeInBits)
4147 return DAG.getConstant(0, VT);
4148 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4149 DAG.getConstant(c1 + c2, N1.getValueType()));
4153 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4154 // For this to be valid, the second form must not preserve any of the bits
4155 // that are shifted out by the inner shift in the first form. This means
4156 // the outer shift size must be >= the number of bits added by the ext.
4157 // As a corollary, we don't care what kind of ext it is.
4158 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4159 N0.getOpcode() == ISD::ANY_EXTEND ||
4160 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4161 N0.getOperand(0).getOpcode() == ISD::SHL) {
4162 SDValue N0Op0 = N0.getOperand(0);
4163 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4164 uint64_t c1 = N0Op0C1->getZExtValue();
4165 uint64_t c2 = N1C->getZExtValue();
4166 EVT InnerShiftVT = N0Op0.getValueType();
4167 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4168 if (c2 >= OpSizeInBits - InnerShiftSize) {
4169 if (c1 + c2 >= OpSizeInBits)
4170 return DAG.getConstant(0, VT);
4171 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4172 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4173 N0Op0->getOperand(0)),
4174 DAG.getConstant(c1 + c2, N1.getValueType()));
4179 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4180 // Only fold this if the inner zext has no other uses to avoid increasing
4181 // the total number of instructions.
4182 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4183 N0.getOperand(0).getOpcode() == ISD::SRL) {
4184 SDValue N0Op0 = N0.getOperand(0);
4185 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4186 uint64_t c1 = N0Op0C1->getZExtValue();
4187 if (c1 < VT.getScalarSizeInBits()) {
4188 uint64_t c2 = N1C->getZExtValue();
4190 SDValue NewOp0 = N0.getOperand(0);
4191 EVT CountVT = NewOp0.getOperand(1).getValueType();
4192 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4193 NewOp0, DAG.getConstant(c2, CountVT));
4194 AddToWorklist(NewSHL.getNode());
4195 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4201 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4202 // (and (srl x, (sub c1, c2), MASK)
4203 // Only fold this if the inner shift has no other uses -- if it does, folding
4204 // this will increase the total number of instructions.
4205 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4206 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4207 uint64_t c1 = N0C1->getZExtValue();
4208 if (c1 < OpSizeInBits) {
4209 uint64_t c2 = N1C->getZExtValue();
4210 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4213 Mask = Mask.shl(c2 - c1);
4214 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4215 DAG.getConstant(c2 - c1, N1.getValueType()));
4217 Mask = Mask.lshr(c1 - c2);
4218 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4219 DAG.getConstant(c1 - c2, N1.getValueType()));
4221 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4222 DAG.getConstant(Mask, VT));
4226 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4227 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4228 unsigned BitSize = VT.getScalarSizeInBits();
4229 SDValue HiBitsMask =
4230 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4231 BitSize - N1C->getZExtValue()), VT);
4232 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4236 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4237 // Variant of version done on multiply, except mul by a power of 2 is turned
4240 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4241 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4242 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4243 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4244 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4245 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4249 SDValue NewSHL = visitShiftByConstant(N, N1C);
4250 if (NewSHL.getNode())
4257 SDValue DAGCombiner::visitSRA(SDNode *N) {
4258 SDValue N0 = N->getOperand(0);
4259 SDValue N1 = N->getOperand(1);
4260 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4261 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4262 EVT VT = N0.getValueType();
4263 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4266 if (VT.isVector()) {
4267 SDValue FoldedVOp = SimplifyVBinOp(N);
4268 if (FoldedVOp.getNode()) return FoldedVOp;
4270 N1C = isConstOrConstSplat(N1);
4273 // fold (sra c1, c2) -> (sra c1, c2)
4275 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4276 // fold (sra 0, x) -> 0
4277 if (N0C && N0C->isNullValue())
4279 // fold (sra -1, x) -> -1
4280 if (N0C && N0C->isAllOnesValue())
4282 // fold (sra x, (setge c, size(x))) -> undef
4283 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4284 return DAG.getUNDEF(VT);
4285 // fold (sra x, 0) -> x
4286 if (N1C && N1C->isNullValue())
4288 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4290 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4291 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4292 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4294 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4295 ExtVT, VT.getVectorNumElements());
4296 if ((!LegalOperations ||
4297 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4298 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4299 N0.getOperand(0), DAG.getValueType(ExtVT));
4302 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4303 if (N1C && N0.getOpcode() == ISD::SRA) {
4304 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4305 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4306 if (Sum >= OpSizeInBits)
4307 Sum = OpSizeInBits - 1;
4308 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4309 DAG.getConstant(Sum, N1.getValueType()));
4313 // fold (sra (shl X, m), (sub result_size, n))
4314 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4315 // result_size - n != m.
4316 // If truncate is free for the target sext(shl) is likely to result in better
4318 if (N0.getOpcode() == ISD::SHL && N1C) {
4319 // Get the two constanst of the shifts, CN0 = m, CN = n.
4320 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4322 LLVMContext &Ctx = *DAG.getContext();
4323 // Determine what the truncate's result bitsize and type would be.
4324 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4327 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4329 // Determine the residual right-shift amount.
4330 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4332 // If the shift is not a no-op (in which case this should be just a sign
4333 // extend already), the truncated to type is legal, sign_extend is legal
4334 // on that type, and the truncate to that type is both legal and free,
4335 // perform the transform.
4336 if ((ShiftAmt > 0) &&
4337 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4338 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4339 TLI.isTruncateFree(VT, TruncVT)) {
4341 SDValue Amt = DAG.getConstant(ShiftAmt,
4342 getShiftAmountTy(N0.getOperand(0).getValueType()));
4343 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4344 N0.getOperand(0), Amt);
4345 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4347 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4348 N->getValueType(0), Trunc);
4353 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4354 if (N1.getOpcode() == ISD::TRUNCATE &&
4355 N1.getOperand(0).getOpcode() == ISD::AND) {
4356 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4357 if (NewOp1.getNode())
4358 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4361 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4362 // if c1 is equal to the number of bits the trunc removes
4363 if (N0.getOpcode() == ISD::TRUNCATE &&
4364 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4365 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4366 N0.getOperand(0).hasOneUse() &&
4367 N0.getOperand(0).getOperand(1).hasOneUse() &&
4369 SDValue N0Op0 = N0.getOperand(0);
4370 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4371 unsigned LargeShiftVal = LargeShift->getZExtValue();
4372 EVT LargeVT = N0Op0.getValueType();
4374 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4376 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4377 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4378 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4379 N0Op0.getOperand(0), Amt);
4380 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4385 // Simplify, based on bits shifted out of the LHS.
4386 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4387 return SDValue(N, 0);
4390 // If the sign bit is known to be zero, switch this to a SRL.
4391 if (DAG.SignBitIsZero(N0))
4392 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4395 SDValue NewSRA = visitShiftByConstant(N, N1C);
4396 if (NewSRA.getNode())
4403 SDValue DAGCombiner::visitSRL(SDNode *N) {
4404 SDValue N0 = N->getOperand(0);
4405 SDValue N1 = N->getOperand(1);
4406 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4407 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4408 EVT VT = N0.getValueType();
4409 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4412 if (VT.isVector()) {
4413 SDValue FoldedVOp = SimplifyVBinOp(N);
4414 if (FoldedVOp.getNode()) return FoldedVOp;
4416 N1C = isConstOrConstSplat(N1);
4419 // fold (srl c1, c2) -> c1 >>u c2
4421 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4422 // fold (srl 0, x) -> 0
4423 if (N0C && N0C->isNullValue())
4425 // fold (srl x, c >= size(x)) -> undef
4426 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4427 return DAG.getUNDEF(VT);
4428 // fold (srl x, 0) -> x
4429 if (N1C && N1C->isNullValue())
4431 // if (srl x, c) is known to be zero, return 0
4432 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4433 APInt::getAllOnesValue(OpSizeInBits)))
4434 return DAG.getConstant(0, VT);
4436 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4437 if (N1C && N0.getOpcode() == ISD::SRL) {
4438 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4439 uint64_t c1 = N01C->getZExtValue();
4440 uint64_t c2 = N1C->getZExtValue();
4441 if (c1 + c2 >= OpSizeInBits)
4442 return DAG.getConstant(0, VT);
4443 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4444 DAG.getConstant(c1 + c2, N1.getValueType()));
4448 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4449 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4450 N0.getOperand(0).getOpcode() == ISD::SRL &&
4451 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4453 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4454 uint64_t c2 = N1C->getZExtValue();
4455 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4456 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4457 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4458 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4459 if (c1 + OpSizeInBits == InnerShiftSize) {
4460 if (c1 + c2 >= InnerShiftSize)
4461 return DAG.getConstant(0, VT);
4462 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4463 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4464 N0.getOperand(0)->getOperand(0),
4465 DAG.getConstant(c1 + c2, ShiftCountVT)));
4469 // fold (srl (shl x, c), c) -> (and x, cst2)
4470 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4471 unsigned BitSize = N0.getScalarValueSizeInBits();
4472 if (BitSize <= 64) {
4473 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4474 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4475 DAG.getConstant(~0ULL >> ShAmt, VT));
4479 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4480 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4481 // Shifting in all undef bits?
4482 EVT SmallVT = N0.getOperand(0).getValueType();
4483 unsigned BitSize = SmallVT.getScalarSizeInBits();
4484 if (N1C->getZExtValue() >= BitSize)
4485 return DAG.getUNDEF(VT);
4487 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4488 uint64_t ShiftAmt = N1C->getZExtValue();
4489 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4491 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4492 AddToWorklist(SmallShift.getNode());
4493 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4494 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4495 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4496 DAG.getConstant(Mask, VT));
4500 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4501 // bit, which is unmodified by sra.
4502 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4503 if (N0.getOpcode() == ISD::SRA)
4504 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4507 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4508 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4509 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4510 APInt KnownZero, KnownOne;
4511 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4513 // If any of the input bits are KnownOne, then the input couldn't be all
4514 // zeros, thus the result of the srl will always be zero.
4515 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4517 // If all of the bits input the to ctlz node are known to be zero, then
4518 // the result of the ctlz is "32" and the result of the shift is one.
4519 APInt UnknownBits = ~KnownZero;
4520 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4522 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4523 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4524 // Okay, we know that only that the single bit specified by UnknownBits
4525 // could be set on input to the CTLZ node. If this bit is set, the SRL
4526 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4527 // to an SRL/XOR pair, which is likely to simplify more.
4528 unsigned ShAmt = UnknownBits.countTrailingZeros();
4529 SDValue Op = N0.getOperand(0);
4532 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4533 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4534 AddToWorklist(Op.getNode());
4537 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4538 Op, DAG.getConstant(1, VT));
4542 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4543 if (N1.getOpcode() == ISD::TRUNCATE &&
4544 N1.getOperand(0).getOpcode() == ISD::AND) {
4545 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4546 if (NewOp1.getNode())
4547 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4550 // fold operands of srl based on knowledge that the low bits are not
4552 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4553 return SDValue(N, 0);
4556 SDValue NewSRL = visitShiftByConstant(N, N1C);
4557 if (NewSRL.getNode())
4561 // Attempt to convert a srl of a load into a narrower zero-extending load.
4562 SDValue NarrowLoad = ReduceLoadWidth(N);
4563 if (NarrowLoad.getNode())
4566 // Here is a common situation. We want to optimize:
4569 // %b = and i32 %a, 2
4570 // %c = srl i32 %b, 1
4571 // brcond i32 %c ...
4577 // %c = setcc eq %b, 0
4580 // However when after the source operand of SRL is optimized into AND, the SRL
4581 // itself may not be optimized further. Look for it and add the BRCOND into
4583 if (N->hasOneUse()) {
4584 SDNode *Use = *N->use_begin();
4585 if (Use->getOpcode() == ISD::BRCOND)
4587 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4588 // Also look pass the truncate.
4589 Use = *Use->use_begin();
4590 if (Use->getOpcode() == ISD::BRCOND)
4598 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4599 SDValue N0 = N->getOperand(0);
4600 EVT VT = N->getValueType(0);
4602 // fold (ctlz c1) -> c2
4603 if (isa<ConstantSDNode>(N0))
4604 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4608 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4609 SDValue N0 = N->getOperand(0);
4610 EVT VT = N->getValueType(0);
4612 // fold (ctlz_zero_undef c1) -> c2
4613 if (isa<ConstantSDNode>(N0))
4614 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4618 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4619 SDValue N0 = N->getOperand(0);
4620 EVT VT = N->getValueType(0);
4622 // fold (cttz c1) -> c2
4623 if (isa<ConstantSDNode>(N0))
4624 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4628 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4629 SDValue N0 = N->getOperand(0);
4630 EVT VT = N->getValueType(0);
4632 // fold (cttz_zero_undef c1) -> c2
4633 if (isa<ConstantSDNode>(N0))
4634 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4638 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4639 SDValue N0 = N->getOperand(0);
4640 EVT VT = N->getValueType(0);
4642 // fold (ctpop c1) -> c2
4643 if (isa<ConstantSDNode>(N0))
4644 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4649 /// \brief Generate Min/Max node
4650 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4651 SDValue True, SDValue False,
4652 ISD::CondCode CC, const TargetLowering &TLI,
4653 SelectionDAG &DAG) {
4654 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4664 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4665 if (TLI.isOperationLegal(Opcode, VT))
4666 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4675 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4676 if (TLI.isOperationLegal(Opcode, VT))
4677 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4685 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4686 SDValue N0 = N->getOperand(0);
4687 SDValue N1 = N->getOperand(1);
4688 SDValue N2 = N->getOperand(2);
4689 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4690 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4691 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4692 EVT VT = N->getValueType(0);
4693 EVT VT0 = N0.getValueType();
4695 // fold (select C, X, X) -> X
4698 // fold (select true, X, Y) -> X
4699 if (N0C && !N0C->isNullValue())
4701 // fold (select false, X, Y) -> Y
4702 if (N0C && N0C->isNullValue())
4704 // fold (select C, 1, X) -> (or C, X)
4705 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4706 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4707 // fold (select C, 0, 1) -> (xor C, 1)
4708 // We can't do this reliably if integer based booleans have different contents
4709 // to floating point based booleans. This is because we can't tell whether we
4710 // have an integer-based boolean or a floating-point-based boolean unless we
4711 // can find the SETCC that produced it and inspect its operands. This is
4712 // fairly easy if C is the SETCC node, but it can potentially be
4713 // undiscoverable (or not reasonably discoverable). For example, it could be
4714 // in another basic block or it could require searching a complicated
4716 if (VT.isInteger() &&
4717 (VT0 == MVT::i1 || (VT0.isInteger() &&
4718 TLI.getBooleanContents(false, false) ==
4719 TLI.getBooleanContents(false, true) &&
4720 TLI.getBooleanContents(false, false) ==
4721 TargetLowering::ZeroOrOneBooleanContent)) &&
4722 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4725 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4726 N0, DAG.getConstant(1, VT0));
4727 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4728 N0, DAG.getConstant(1, VT0));
4729 AddToWorklist(XORNode.getNode());
4731 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4732 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4734 // fold (select C, 0, X) -> (and (not C), X)
4735 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4736 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4737 AddToWorklist(NOTNode.getNode());
4738 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4740 // fold (select C, X, 1) -> (or (not C), X)
4741 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4742 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4743 AddToWorklist(NOTNode.getNode());
4744 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4746 // fold (select C, X, 0) -> (and C, X)
4747 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4748 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4749 // fold (select X, X, Y) -> (or X, Y)
4750 // fold (select X, 1, Y) -> (or X, Y)
4751 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4752 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4753 // fold (select X, Y, X) -> (and X, Y)
4754 // fold (select X, Y, 0) -> (and X, Y)
4755 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4756 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4758 // If we can fold this based on the true/false value, do so.
4759 if (SimplifySelectOps(N, N1, N2))
4760 return SDValue(N, 0); // Don't revisit N.
4762 // fold selects based on a setcc into other things, such as min/max/abs
4763 if (N0.getOpcode() == ISD::SETCC) {
4764 // select x, y (fcmp lt x, y) -> fminnum x, y
4765 // select x, y (fcmp gt x, y) -> fmaxnum x, y
4767 // This is OK if we don't care about what happens if either operand is a
4771 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4772 // no signed zeros as well as no nans.
4773 const TargetOptions &Options = DAG.getTarget().Options;
4774 if (Options.UnsafeFPMath &&
4775 VT.isFloatingPoint() && N0.hasOneUse() &&
4776 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4777 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4780 combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4781 N1, N2, CC, TLI, DAG);
4786 if ((!LegalOperations &&
4787 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4788 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4789 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4790 N0.getOperand(0), N0.getOperand(1),
4791 N1, N2, N0.getOperand(2));
4792 return SimplifySelect(SDLoc(N), N0, N1, N2);
4799 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4802 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4804 // Split the inputs.
4805 SDValue Lo, Hi, LL, LH, RL, RH;
4806 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4807 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4809 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4810 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4812 return std::make_pair(Lo, Hi);
4815 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4816 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4817 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4819 SDValue Cond = N->getOperand(0);
4820 SDValue LHS = N->getOperand(1);
4821 SDValue RHS = N->getOperand(2);
4822 EVT VT = N->getValueType(0);
4823 int NumElems = VT.getVectorNumElements();
4824 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4825 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4826 Cond.getOpcode() == ISD::BUILD_VECTOR);
4828 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4829 // binary ones here.
4830 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4833 // We're sure we have an even number of elements due to the
4834 // concat_vectors we have as arguments to vselect.
4835 // Skip BV elements until we find one that's not an UNDEF
4836 // After we find an UNDEF element, keep looping until we get to half the
4837 // length of the BV and see if all the non-undef nodes are the same.
4838 ConstantSDNode *BottomHalf = nullptr;
4839 for (int i = 0; i < NumElems / 2; ++i) {
4840 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4843 if (BottomHalf == nullptr)
4844 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4845 else if (Cond->getOperand(i).getNode() != BottomHalf)
4849 // Do the same for the second half of the BuildVector
4850 ConstantSDNode *TopHalf = nullptr;
4851 for (int i = NumElems / 2; i < NumElems; ++i) {
4852 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4855 if (TopHalf == nullptr)
4856 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4857 else if (Cond->getOperand(i).getNode() != TopHalf)
4861 assert(TopHalf && BottomHalf &&
4862 "One half of the selector was all UNDEFs and the other was all the "
4863 "same value. This should have been addressed before this function.");
4865 ISD::CONCAT_VECTORS, dl, VT,
4866 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4867 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4870 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
4872 if (Level >= AfterLegalizeTypes)
4875 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
4876 SDValue Mask = MST->getMask();
4877 SDValue Data = MST->getValue();
4880 // If the MSTORE data type requires splitting and the mask is provided by a
4881 // SETCC, then split both nodes and its operands before legalization. This
4882 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4883 // and enables future optimizations (e.g. min/max pattern matching on X86).
4884 if (Mask.getOpcode() == ISD::SETCC) {
4886 // Check if any splitting is required.
4887 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
4888 TargetLowering::TypeSplitVector)
4891 SDValue MaskLo, MaskHi, Lo, Hi;
4892 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4895 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
4897 SDValue Chain = MST->getChain();
4898 SDValue Ptr = MST->getBasePtr();
4900 EVT MemoryVT = MST->getMemoryVT();
4901 unsigned Alignment = MST->getOriginalAlignment();
4903 // if Alignment is equal to the vector size,
4904 // take the half of it for the second part
4905 unsigned SecondHalfAlignment =
4906 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
4907 Alignment/2 : Alignment;
4909 EVT LoMemVT, HiMemVT;
4910 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4912 SDValue DataLo, DataHi;
4913 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
4915 MachineMemOperand *MMO = DAG.getMachineFunction().
4916 getMachineMemOperand(MST->getPointerInfo(),
4917 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
4918 Alignment, MST->getAAInfo(), MST->getRanges());
4920 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
4921 MST->isTruncatingStore());
4923 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4924 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4925 DAG.getConstant(IncrementSize, Ptr.getValueType()));
4927 MMO = DAG.getMachineFunction().
4928 getMachineMemOperand(MST->getPointerInfo(),
4929 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
4930 SecondHalfAlignment, MST->getAAInfo(),
4933 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
4934 MST->isTruncatingStore());
4936 AddToWorklist(Lo.getNode());
4937 AddToWorklist(Hi.getNode());
4939 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
4944 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
4946 if (Level >= AfterLegalizeTypes)
4949 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
4950 SDValue Mask = MLD->getMask();
4953 // If the MLOAD result requires splitting and the mask is provided by a
4954 // SETCC, then split both nodes and its operands before legalization. This
4955 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4956 // and enables future optimizations (e.g. min/max pattern matching on X86).
4958 if (Mask.getOpcode() == ISD::SETCC) {
4959 EVT VT = N->getValueType(0);
4961 // Check if any splitting is required.
4962 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4963 TargetLowering::TypeSplitVector)
4966 SDValue MaskLo, MaskHi, Lo, Hi;
4967 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4969 SDValue Src0 = MLD->getSrc0();
4970 SDValue Src0Lo, Src0Hi;
4971 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
4974 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
4976 SDValue Chain = MLD->getChain();
4977 SDValue Ptr = MLD->getBasePtr();
4978 EVT MemoryVT = MLD->getMemoryVT();
4979 unsigned Alignment = MLD->getOriginalAlignment();
4981 // if Alignment is equal to the vector size,
4982 // take the half of it for the second part
4983 unsigned SecondHalfAlignment =
4984 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
4985 Alignment/2 : Alignment;
4987 EVT LoMemVT, HiMemVT;
4988 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4990 MachineMemOperand *MMO = DAG.getMachineFunction().
4991 getMachineMemOperand(MLD->getPointerInfo(),
4992 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
4993 Alignment, MLD->getAAInfo(), MLD->getRanges());
4995 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
4998 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4999 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5000 DAG.getConstant(IncrementSize, Ptr.getValueType()));
5002 MMO = DAG.getMachineFunction().
5003 getMachineMemOperand(MLD->getPointerInfo(),
5004 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5005 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5007 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5010 AddToWorklist(Lo.getNode());
5011 AddToWorklist(Hi.getNode());
5013 // Build a factor node to remember that this load is independent of the
5015 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5018 // Legalized the chain result - switch anything that used the old chain to
5020 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5022 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5024 SDValue RetOps[] = { LoadRes, Chain };
5025 return DAG.getMergeValues(RetOps, DL);
5030 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5031 SDValue N0 = N->getOperand(0);
5032 SDValue N1 = N->getOperand(1);
5033 SDValue N2 = N->getOperand(2);
5036 // Canonicalize integer abs.
5037 // vselect (setg[te] X, 0), X, -X ->
5038 // vselect (setgt X, -1), X, -X ->
5039 // vselect (setl[te] X, 0), -X, X ->
5040 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5041 if (N0.getOpcode() == ISD::SETCC) {
5042 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5043 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5045 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5047 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5048 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5049 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5050 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5051 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5052 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5053 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5056 EVT VT = LHS.getValueType();
5057 SDValue Shift = DAG.getNode(
5058 ISD::SRA, DL, VT, LHS,
5059 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
5060 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5061 AddToWorklist(Shift.getNode());
5062 AddToWorklist(Add.getNode());
5063 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5067 // If the VSELECT result requires splitting and the mask is provided by a
5068 // SETCC, then split both nodes and its operands before legalization. This
5069 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5070 // and enables future optimizations (e.g. min/max pattern matching on X86).
5071 if (N0.getOpcode() == ISD::SETCC) {
5072 EVT VT = N->getValueType(0);
5074 // Check if any splitting is required.
5075 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5076 TargetLowering::TypeSplitVector)
5079 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5080 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5081 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5082 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5084 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5085 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5087 // Add the new VSELECT nodes to the work list in case they need to be split
5089 AddToWorklist(Lo.getNode());
5090 AddToWorklist(Hi.getNode());
5092 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5095 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5096 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5098 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5099 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5102 // The ConvertSelectToConcatVector function is assuming both the above
5103 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5105 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5106 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5107 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5108 SDValue CV = ConvertSelectToConcatVector(N, DAG);
5116 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5117 SDValue N0 = N->getOperand(0);
5118 SDValue N1 = N->getOperand(1);
5119 SDValue N2 = N->getOperand(2);
5120 SDValue N3 = N->getOperand(3);
5121 SDValue N4 = N->getOperand(4);
5122 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5124 // fold select_cc lhs, rhs, x, x, cc -> x
5128 // Determine if the condition we're dealing with is constant
5129 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5130 N0, N1, CC, SDLoc(N), false);
5131 if (SCC.getNode()) {
5132 AddToWorklist(SCC.getNode());
5134 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5135 if (!SCCC->isNullValue())
5136 return N2; // cond always true -> true val
5138 return N3; // cond always false -> false val
5139 } else if (SCC->getOpcode() == ISD::UNDEF) {
5140 // When the condition is UNDEF, just return the first operand. This is
5141 // coherent the DAG creation, no setcc node is created in this case
5143 } else if (SCC.getOpcode() == ISD::SETCC) {
5144 // Fold to a simpler select_cc
5145 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5146 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5151 // If we can fold this based on the true/false value, do so.
5152 if (SimplifySelectOps(N, N2, N3))
5153 return SDValue(N, 0); // Don't revisit N.
5155 // fold select_cc into other things, such as min/max/abs
5156 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5159 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5160 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5161 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5165 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5166 // dag node into a ConstantSDNode or a build_vector of constants.
5167 // This function is called by the DAGCombiner when visiting sext/zext/aext
5168 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5169 // Vector extends are not folded if operations are legal; this is to
5170 // avoid introducing illegal build_vector dag nodes.
5171 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5172 SelectionDAG &DAG, bool LegalTypes,
5173 bool LegalOperations) {
5174 unsigned Opcode = N->getOpcode();
5175 SDValue N0 = N->getOperand(0);
5176 EVT VT = N->getValueType(0);
5178 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5179 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5181 // fold (sext c1) -> c1
5182 // fold (zext c1) -> c1
5183 // fold (aext c1) -> c1
5184 if (isa<ConstantSDNode>(N0))
5185 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5187 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5188 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5189 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5190 EVT SVT = VT.getScalarType();
5191 if (!(VT.isVector() &&
5192 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5193 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5196 // We can fold this node into a build_vector.
5197 unsigned VTBits = SVT.getSizeInBits();
5198 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5199 unsigned ShAmt = VTBits - EVTBits;
5200 SmallVector<SDValue, 8> Elts;
5201 unsigned NumElts = N0->getNumOperands();
5204 for (unsigned i=0; i != NumElts; ++i) {
5205 SDValue Op = N0->getOperand(i);
5206 if (Op->getOpcode() == ISD::UNDEF) {
5207 Elts.push_back(DAG.getUNDEF(SVT));
5211 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5212 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5213 if (Opcode == ISD::SIGN_EXTEND)
5214 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5217 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5221 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5224 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5225 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5226 // transformation. Returns true if extension are possible and the above
5227 // mentioned transformation is profitable.
5228 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5230 SmallVectorImpl<SDNode *> &ExtendNodes,
5231 const TargetLowering &TLI) {
5232 bool HasCopyToRegUses = false;
5233 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5234 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5235 UE = N0.getNode()->use_end();
5240 if (UI.getUse().getResNo() != N0.getResNo())
5242 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5243 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5244 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5245 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5246 // Sign bits will be lost after a zext.
5249 for (unsigned i = 0; i != 2; ++i) {
5250 SDValue UseOp = User->getOperand(i);
5253 if (!isa<ConstantSDNode>(UseOp))
5258 ExtendNodes.push_back(User);
5261 // If truncates aren't free and there are users we can't
5262 // extend, it isn't worthwhile.
5265 // Remember if this value is live-out.
5266 if (User->getOpcode() == ISD::CopyToReg)
5267 HasCopyToRegUses = true;
5270 if (HasCopyToRegUses) {
5271 bool BothLiveOut = false;
5272 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5274 SDUse &Use = UI.getUse();
5275 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5281 // Both unextended and extended values are live out. There had better be
5282 // a good reason for the transformation.
5283 return ExtendNodes.size();
5288 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5289 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5290 ISD::NodeType ExtType) {
5291 // Extend SetCC uses if necessary.
5292 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5293 SDNode *SetCC = SetCCs[i];
5294 SmallVector<SDValue, 4> Ops;
5296 for (unsigned j = 0; j != 2; ++j) {
5297 SDValue SOp = SetCC->getOperand(j);
5299 Ops.push_back(ExtLoad);
5301 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5304 Ops.push_back(SetCC->getOperand(2));
5305 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5309 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5310 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5311 SDValue N0 = N->getOperand(0);
5312 EVT DstVT = N->getValueType(0);
5313 EVT SrcVT = N0.getValueType();
5315 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5316 N->getOpcode() == ISD::ZERO_EXTEND) &&
5317 "Unexpected node type (not an extend)!");
5319 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5320 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5321 // (v8i32 (sext (v8i16 (load x))))
5323 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5324 // (v4i32 (sextload (x + 16)))))
5325 // Where uses of the original load, i.e.:
5327 // are replaced with:
5329 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5330 // (v4i32 (sextload (x + 16)))))))
5332 // This combine is only applicable to illegal, but splittable, vectors.
5333 // All legal types, and illegal non-vector types, are handled elsewhere.
5334 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5336 if (N0->getOpcode() != ISD::LOAD)
5339 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5341 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5342 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5343 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5346 SmallVector<SDNode *, 4> SetCCs;
5347 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5350 ISD::LoadExtType ExtType =
5351 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5353 // Try to split the vector types to get down to legal types.
5354 EVT SplitSrcVT = SrcVT;
5355 EVT SplitDstVT = DstVT;
5356 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5357 SplitSrcVT.getVectorNumElements() > 1) {
5358 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5359 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5362 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5366 const unsigned NumSplits =
5367 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5368 const unsigned Stride = SplitSrcVT.getStoreSize();
5369 SmallVector<SDValue, 4> Loads;
5370 SmallVector<SDValue, 4> Chains;
5372 SDValue BasePtr = LN0->getBasePtr();
5373 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5374 const unsigned Offset = Idx * Stride;
5375 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5377 SDValue SplitLoad = DAG.getExtLoad(
5378 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5379 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5380 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5381 Align, LN0->getAAInfo());
5383 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5384 DAG.getConstant(Stride, BasePtr.getValueType()));
5386 Loads.push_back(SplitLoad.getValue(0));
5387 Chains.push_back(SplitLoad.getValue(1));
5390 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5391 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5393 CombineTo(N, NewValue);
5395 // Replace uses of the original load (before extension)
5396 // with a truncate of the concatenated sextloaded vectors.
5398 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5399 CombineTo(N0.getNode(), Trunc, NewChain);
5400 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5401 (ISD::NodeType)N->getOpcode());
5402 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5405 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5406 SDValue N0 = N->getOperand(0);
5407 EVT VT = N->getValueType(0);
5409 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5411 return SDValue(Res, 0);
5413 // fold (sext (sext x)) -> (sext x)
5414 // fold (sext (aext x)) -> (sext x)
5415 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5416 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5419 if (N0.getOpcode() == ISD::TRUNCATE) {
5420 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5421 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5422 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5423 if (NarrowLoad.getNode()) {
5424 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5425 if (NarrowLoad.getNode() != N0.getNode()) {
5426 CombineTo(N0.getNode(), NarrowLoad);
5427 // CombineTo deleted the truncate, if needed, but not what's under it.
5430 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5433 // See if the value being truncated is already sign extended. If so, just
5434 // eliminate the trunc/sext pair.
5435 SDValue Op = N0.getOperand(0);
5436 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5437 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5438 unsigned DestBits = VT.getScalarType().getSizeInBits();
5439 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5441 if (OpBits == DestBits) {
5442 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5443 // bits, it is already ready.
5444 if (NumSignBits > DestBits-MidBits)
5446 } else if (OpBits < DestBits) {
5447 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5448 // bits, just sext from i32.
5449 if (NumSignBits > OpBits-MidBits)
5450 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5452 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5453 // bits, just truncate to i32.
5454 if (NumSignBits > OpBits-MidBits)
5455 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5458 // fold (sext (truncate x)) -> (sextinreg x).
5459 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5460 N0.getValueType())) {
5461 if (OpBits < DestBits)
5462 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5463 else if (OpBits > DestBits)
5464 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5465 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5466 DAG.getValueType(N0.getValueType()));
5470 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5471 // Only generate vector extloads when 1) they're legal, and 2) they are
5472 // deemed desirable by the target.
5473 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5474 ((!LegalOperations && !VT.isVector() &&
5475 !cast<LoadSDNode>(N0)->isVolatile()) ||
5476 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5477 bool DoXform = true;
5478 SmallVector<SDNode*, 4> SetCCs;
5479 if (!N0.hasOneUse())
5480 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5482 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5484 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5485 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5487 LN0->getBasePtr(), N0.getValueType(),
5488 LN0->getMemOperand());
5489 CombineTo(N, ExtLoad);
5490 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5491 N0.getValueType(), ExtLoad);
5492 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5493 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5495 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5499 // fold (sext (load x)) to multiple smaller sextloads.
5500 // Only on illegal but splittable vectors.
5501 if (SDValue ExtLoad = CombineExtLoad(N))
5504 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5505 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5506 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5507 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5508 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5509 EVT MemVT = LN0->getMemoryVT();
5510 if ((!LegalOperations && !LN0->isVolatile()) ||
5511 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5512 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5514 LN0->getBasePtr(), MemVT,
5515 LN0->getMemOperand());
5516 CombineTo(N, ExtLoad);
5517 CombineTo(N0.getNode(),
5518 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5519 N0.getValueType(), ExtLoad),
5520 ExtLoad.getValue(1));
5521 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5525 // fold (sext (and/or/xor (load x), cst)) ->
5526 // (and/or/xor (sextload x), (sext cst))
5527 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5528 N0.getOpcode() == ISD::XOR) &&
5529 isa<LoadSDNode>(N0.getOperand(0)) &&
5530 N0.getOperand(1).getOpcode() == ISD::Constant &&
5531 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5532 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5533 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5534 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5535 bool DoXform = true;
5536 SmallVector<SDNode*, 4> SetCCs;
5537 if (!N0.hasOneUse())
5538 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5541 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5542 LN0->getChain(), LN0->getBasePtr(),
5544 LN0->getMemOperand());
5545 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5546 Mask = Mask.sext(VT.getSizeInBits());
5547 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5548 ExtLoad, DAG.getConstant(Mask, VT));
5549 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5550 SDLoc(N0.getOperand(0)),
5551 N0.getOperand(0).getValueType(), ExtLoad);
5553 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5554 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5556 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5561 if (N0.getOpcode() == ISD::SETCC) {
5562 EVT N0VT = N0.getOperand(0).getValueType();
5563 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5564 // Only do this before legalize for now.
5565 if (VT.isVector() && !LegalOperations &&
5566 TLI.getBooleanContents(N0VT) ==
5567 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5568 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5569 // of the same size as the compared operands. Only optimize sext(setcc())
5570 // if this is the case.
5571 EVT SVT = getSetCCResultType(N0VT);
5573 // We know that the # elements of the results is the same as the
5574 // # elements of the compare (and the # elements of the compare result
5575 // for that matter). Check to see that they are the same size. If so,
5576 // we know that the element size of the sext'd result matches the
5577 // element size of the compare operands.
5578 if (VT.getSizeInBits() == SVT.getSizeInBits())
5579 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5581 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5583 // If the desired elements are smaller or larger than the source
5584 // elements we can use a matching integer vector type and then
5585 // truncate/sign extend
5586 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5587 if (SVT == MatchingVectorType) {
5588 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5589 N0.getOperand(0), N0.getOperand(1),
5590 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5591 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5595 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5596 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5598 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5600 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5601 NegOne, DAG.getConstant(0, VT),
5602 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5603 if (SCC.getNode()) return SCC;
5605 if (!VT.isVector()) {
5606 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5607 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5609 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5610 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5611 N0.getOperand(0), N0.getOperand(1), CC);
5612 return DAG.getSelect(DL, VT, SetCC,
5613 NegOne, DAG.getConstant(0, VT));
5618 // fold (sext x) -> (zext x) if the sign bit is known zero.
5619 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5620 DAG.SignBitIsZero(N0))
5621 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5626 // isTruncateOf - If N is a truncate of some other value, return true, record
5627 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5628 // This function computes KnownZero to avoid a duplicated call to
5629 // computeKnownBits in the caller.
5630 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5633 if (N->getOpcode() == ISD::TRUNCATE) {
5634 Op = N->getOperand(0);
5635 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5639 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5640 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5643 SDValue Op0 = N->getOperand(0);
5644 SDValue Op1 = N->getOperand(1);
5645 assert(Op0.getValueType() == Op1.getValueType());
5647 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5648 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5649 if (COp0 && COp0->isNullValue())
5651 else if (COp1 && COp1->isNullValue())
5656 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5658 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5664 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5665 SDValue N0 = N->getOperand(0);
5666 EVT VT = N->getValueType(0);
5668 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5670 return SDValue(Res, 0);
5672 // fold (zext (zext x)) -> (zext x)
5673 // fold (zext (aext x)) -> (zext x)
5674 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5675 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5678 // fold (zext (truncate x)) -> (zext x) or
5679 // (zext (truncate x)) -> (truncate x)
5680 // This is valid when the truncated bits of x are already zero.
5681 // FIXME: We should extend this to work for vectors too.
5684 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5685 APInt TruncatedBits =
5686 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5687 APInt(Op.getValueSizeInBits(), 0) :
5688 APInt::getBitsSet(Op.getValueSizeInBits(),
5689 N0.getValueSizeInBits(),
5690 std::min(Op.getValueSizeInBits(),
5691 VT.getSizeInBits()));
5692 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5693 if (VT.bitsGT(Op.getValueType()))
5694 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5695 if (VT.bitsLT(Op.getValueType()))
5696 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5702 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5703 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5704 if (N0.getOpcode() == ISD::TRUNCATE) {
5705 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5706 if (NarrowLoad.getNode()) {
5707 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5708 if (NarrowLoad.getNode() != N0.getNode()) {
5709 CombineTo(N0.getNode(), NarrowLoad);
5710 // CombineTo deleted the truncate, if needed, but not what's under it.
5713 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5717 // fold (zext (truncate x)) -> (and x, mask)
5718 if (N0.getOpcode() == ISD::TRUNCATE &&
5719 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5721 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5722 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5723 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5724 if (NarrowLoad.getNode()) {
5725 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5726 if (NarrowLoad.getNode() != N0.getNode()) {
5727 CombineTo(N0.getNode(), NarrowLoad);
5728 // CombineTo deleted the truncate, if needed, but not what's under it.
5731 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5734 SDValue Op = N0.getOperand(0);
5735 if (Op.getValueType().bitsLT(VT)) {
5736 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5737 AddToWorklist(Op.getNode());
5738 } else if (Op.getValueType().bitsGT(VT)) {
5739 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5740 AddToWorklist(Op.getNode());
5742 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5743 N0.getValueType().getScalarType());
5746 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5747 // if either of the casts is not free.
5748 if (N0.getOpcode() == ISD::AND &&
5749 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5750 N0.getOperand(1).getOpcode() == ISD::Constant &&
5751 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5752 N0.getValueType()) ||
5753 !TLI.isZExtFree(N0.getValueType(), VT))) {
5754 SDValue X = N0.getOperand(0).getOperand(0);
5755 if (X.getValueType().bitsLT(VT)) {
5756 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5757 } else if (X.getValueType().bitsGT(VT)) {
5758 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5760 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5761 Mask = Mask.zext(VT.getSizeInBits());
5762 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5763 X, DAG.getConstant(Mask, VT));
5766 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5767 // Only generate vector extloads when 1) they're legal, and 2) they are
5768 // deemed desirable by the target.
5769 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5770 ((!LegalOperations && !VT.isVector() &&
5771 !cast<LoadSDNode>(N0)->isVolatile()) ||
5772 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
5773 bool DoXform = true;
5774 SmallVector<SDNode*, 4> SetCCs;
5775 if (!N0.hasOneUse())
5776 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5778 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5780 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5781 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5783 LN0->getBasePtr(), N0.getValueType(),
5784 LN0->getMemOperand());
5785 CombineTo(N, ExtLoad);
5786 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5787 N0.getValueType(), ExtLoad);
5788 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5790 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5792 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5796 // fold (zext (load x)) to multiple smaller zextloads.
5797 // Only on illegal but splittable vectors.
5798 if (SDValue ExtLoad = CombineExtLoad(N))
5801 // fold (zext (and/or/xor (load x), cst)) ->
5802 // (and/or/xor (zextload x), (zext cst))
5803 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5804 N0.getOpcode() == ISD::XOR) &&
5805 isa<LoadSDNode>(N0.getOperand(0)) &&
5806 N0.getOperand(1).getOpcode() == ISD::Constant &&
5807 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
5808 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5809 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5810 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5811 bool DoXform = true;
5812 SmallVector<SDNode*, 4> SetCCs;
5813 if (!N0.hasOneUse())
5814 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5817 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5818 LN0->getChain(), LN0->getBasePtr(),
5820 LN0->getMemOperand());
5821 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5822 Mask = Mask.zext(VT.getSizeInBits());
5823 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5824 ExtLoad, DAG.getConstant(Mask, VT));
5825 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5826 SDLoc(N0.getOperand(0)),
5827 N0.getOperand(0).getValueType(), ExtLoad);
5829 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5830 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5832 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5837 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5838 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5839 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5840 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5841 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5842 EVT MemVT = LN0->getMemoryVT();
5843 if ((!LegalOperations && !LN0->isVolatile()) ||
5844 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
5845 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5847 LN0->getBasePtr(), MemVT,
5848 LN0->getMemOperand());
5849 CombineTo(N, ExtLoad);
5850 CombineTo(N0.getNode(),
5851 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5853 ExtLoad.getValue(1));
5854 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5858 if (N0.getOpcode() == ISD::SETCC) {
5859 if (!LegalOperations && VT.isVector() &&
5860 N0.getValueType().getVectorElementType() == MVT::i1) {
5861 EVT N0VT = N0.getOperand(0).getValueType();
5862 if (getSetCCResultType(N0VT) == N0.getValueType())
5865 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5866 // Only do this before legalize for now.
5867 EVT EltVT = VT.getVectorElementType();
5868 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5869 DAG.getConstant(1, EltVT));
5870 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5871 // We know that the # elements of the results is the same as the
5872 // # elements of the compare (and the # elements of the compare result
5873 // for that matter). Check to see that they are the same size. If so,
5874 // we know that the element size of the sext'd result matches the
5875 // element size of the compare operands.
5876 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5877 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5879 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5880 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5883 // If the desired elements are smaller or larger than the source
5884 // elements we can use a matching integer vector type and then
5885 // truncate/sign extend
5886 EVT MatchingElementType =
5887 EVT::getIntegerVT(*DAG.getContext(),
5888 N0VT.getScalarType().getSizeInBits());
5889 EVT MatchingVectorType =
5890 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5891 N0VT.getVectorNumElements());
5893 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5895 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5896 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5897 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5898 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5901 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5903 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5904 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5905 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5906 if (SCC.getNode()) return SCC;
5909 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5910 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5911 isa<ConstantSDNode>(N0.getOperand(1)) &&
5912 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5914 SDValue ShAmt = N0.getOperand(1);
5915 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5916 if (N0.getOpcode() == ISD::SHL) {
5917 SDValue InnerZExt = N0.getOperand(0);
5918 // If the original shl may be shifting out bits, do not perform this
5920 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5921 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5922 if (ShAmtVal > KnownZeroBits)
5928 // Ensure that the shift amount is wide enough for the shifted value.
5929 if (VT.getSizeInBits() >= 256)
5930 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5932 return DAG.getNode(N0.getOpcode(), DL, VT,
5933 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5940 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5941 SDValue N0 = N->getOperand(0);
5942 EVT VT = N->getValueType(0);
5944 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5946 return SDValue(Res, 0);
5948 // fold (aext (aext x)) -> (aext x)
5949 // fold (aext (zext x)) -> (zext x)
5950 // fold (aext (sext x)) -> (sext x)
5951 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5952 N0.getOpcode() == ISD::ZERO_EXTEND ||
5953 N0.getOpcode() == ISD::SIGN_EXTEND)
5954 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5956 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5957 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5958 if (N0.getOpcode() == ISD::TRUNCATE) {
5959 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5960 if (NarrowLoad.getNode()) {
5961 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5962 if (NarrowLoad.getNode() != N0.getNode()) {
5963 CombineTo(N0.getNode(), NarrowLoad);
5964 // CombineTo deleted the truncate, if needed, but not what's under it.
5967 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5971 // fold (aext (truncate x))
5972 if (N0.getOpcode() == ISD::TRUNCATE) {
5973 SDValue TruncOp = N0.getOperand(0);
5974 if (TruncOp.getValueType() == VT)
5975 return TruncOp; // x iff x size == zext size.
5976 if (TruncOp.getValueType().bitsGT(VT))
5977 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5978 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5981 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5982 // if the trunc is not free.
5983 if (N0.getOpcode() == ISD::AND &&
5984 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5985 N0.getOperand(1).getOpcode() == ISD::Constant &&
5986 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5987 N0.getValueType())) {
5988 SDValue X = N0.getOperand(0).getOperand(0);
5989 if (X.getValueType().bitsLT(VT)) {
5990 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5991 } else if (X.getValueType().bitsGT(VT)) {
5992 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5994 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5995 Mask = Mask.zext(VT.getSizeInBits());
5996 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5997 X, DAG.getConstant(Mask, VT));
6000 // fold (aext (load x)) -> (aext (truncate (extload x)))
6001 // None of the supported targets knows how to perform load and any_ext
6002 // on vectors in one instruction. We only perform this transformation on
6004 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6005 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6006 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6007 bool DoXform = true;
6008 SmallVector<SDNode*, 4> SetCCs;
6009 if (!N0.hasOneUse())
6010 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6012 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6013 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6015 LN0->getBasePtr(), N0.getValueType(),
6016 LN0->getMemOperand());
6017 CombineTo(N, ExtLoad);
6018 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6019 N0.getValueType(), ExtLoad);
6020 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6021 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6023 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6027 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6028 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6029 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6030 if (N0.getOpcode() == ISD::LOAD &&
6031 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6033 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6034 ISD::LoadExtType ExtType = LN0->getExtensionType();
6035 EVT MemVT = LN0->getMemoryVT();
6036 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6037 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6038 VT, LN0->getChain(), LN0->getBasePtr(),
6039 MemVT, LN0->getMemOperand());
6040 CombineTo(N, ExtLoad);
6041 CombineTo(N0.getNode(),
6042 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6043 N0.getValueType(), ExtLoad),
6044 ExtLoad.getValue(1));
6045 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6049 if (N0.getOpcode() == ISD::SETCC) {
6051 // aext(setcc) -> vsetcc
6052 // aext(setcc) -> truncate(vsetcc)
6053 // aext(setcc) -> aext(vsetcc)
6054 // Only do this before legalize for now.
6055 if (VT.isVector() && !LegalOperations) {
6056 EVT N0VT = N0.getOperand(0).getValueType();
6057 // We know that the # elements of the results is the same as the
6058 // # elements of the compare (and the # elements of the compare result
6059 // for that matter). Check to see that they are the same size. If so,
6060 // we know that the element size of the sext'd result matches the
6061 // element size of the compare operands.
6062 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6063 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6065 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6066 // If the desired elements are smaller or larger than the source
6067 // elements we can use a matching integer vector type and then
6068 // truncate/any extend
6070 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6072 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6074 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6075 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6079 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6081 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
6082 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
6083 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6091 /// See if the specified operand can be simplified with the knowledge that only
6092 /// the bits specified by Mask are used. If so, return the simpler operand,
6093 /// otherwise return a null SDValue.
6094 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6095 switch (V.getOpcode()) {
6097 case ISD::Constant: {
6098 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6099 assert(CV && "Const value should be ConstSDNode.");
6100 const APInt &CVal = CV->getAPIntValue();
6101 APInt NewVal = CVal & Mask;
6103 return DAG.getConstant(NewVal, V.getValueType());
6108 // If the LHS or RHS don't contribute bits to the or, drop them.
6109 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6110 return V.getOperand(1);
6111 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6112 return V.getOperand(0);
6115 // Only look at single-use SRLs.
6116 if (!V.getNode()->hasOneUse())
6118 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6119 // See if we can recursively simplify the LHS.
6120 unsigned Amt = RHSC->getZExtValue();
6122 // Watch out for shift count overflow though.
6123 if (Amt >= Mask.getBitWidth()) break;
6124 APInt NewMask = Mask << Amt;
6125 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6126 if (SimplifyLHS.getNode())
6127 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6128 SimplifyLHS, V.getOperand(1));
6134 /// If the result of a wider load is shifted to right of N bits and then
6135 /// truncated to a narrower type and where N is a multiple of number of bits of
6136 /// the narrower type, transform it to a narrower load from address + N / num of
6137 /// bits of new type. If the result is to be extended, also fold the extension
6138 /// to form a extending load.
6139 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6140 unsigned Opc = N->getOpcode();
6142 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6143 SDValue N0 = N->getOperand(0);
6144 EVT VT = N->getValueType(0);
6147 // This transformation isn't valid for vector loads.
6151 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6153 if (Opc == ISD::SIGN_EXTEND_INREG) {
6154 ExtType = ISD::SEXTLOAD;
6155 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6156 } else if (Opc == ISD::SRL) {
6157 // Another special-case: SRL is basically zero-extending a narrower value.
6158 ExtType = ISD::ZEXTLOAD;
6160 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6161 if (!N01) return SDValue();
6162 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6163 VT.getSizeInBits() - N01->getZExtValue());
6165 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6168 unsigned EVTBits = ExtVT.getSizeInBits();
6170 // Do not generate loads of non-round integer types since these can
6171 // be expensive (and would be wrong if the type is not byte sized).
6172 if (!ExtVT.isRound())
6176 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6177 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6178 ShAmt = N01->getZExtValue();
6179 // Is the shift amount a multiple of size of VT?
6180 if ((ShAmt & (EVTBits-1)) == 0) {
6181 N0 = N0.getOperand(0);
6182 // Is the load width a multiple of size of VT?
6183 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6187 // At this point, we must have a load or else we can't do the transform.
6188 if (!isa<LoadSDNode>(N0)) return SDValue();
6190 // Because a SRL must be assumed to *need* to zero-extend the high bits
6191 // (as opposed to anyext the high bits), we can't combine the zextload
6192 // lowering of SRL and an sextload.
6193 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6196 // If the shift amount is larger than the input type then we're not
6197 // accessing any of the loaded bytes. If the load was a zextload/extload
6198 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6199 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6204 // If the load is shifted left (and the result isn't shifted back right),
6205 // we can fold the truncate through the shift.
6206 unsigned ShLeftAmt = 0;
6207 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6208 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6209 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6210 ShLeftAmt = N01->getZExtValue();
6211 N0 = N0.getOperand(0);
6215 // If we haven't found a load, we can't narrow it. Don't transform one with
6216 // multiple uses, this would require adding a new load.
6217 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6220 // Don't change the width of a volatile load.
6221 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6222 if (LN0->isVolatile())
6225 // Verify that we are actually reducing a load width here.
6226 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6229 // For the transform to be legal, the load must produce only two values
6230 // (the value loaded and the chain). Don't transform a pre-increment
6231 // load, for example, which produces an extra value. Otherwise the
6232 // transformation is not equivalent, and the downstream logic to replace
6233 // uses gets things wrong.
6234 if (LN0->getNumValues() > 2)
6237 // If the load that we're shrinking is an extload and we're not just
6238 // discarding the extension we can't simply shrink the load. Bail.
6239 // TODO: It would be possible to merge the extensions in some cases.
6240 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6241 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6244 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6247 EVT PtrType = N0.getOperand(1).getValueType();
6249 if (PtrType == MVT::Untyped || PtrType.isExtended())
6250 // It's not possible to generate a constant of extended or untyped type.
6253 // For big endian targets, we need to adjust the offset to the pointer to
6254 // load the correct bytes.
6255 if (TLI.isBigEndian()) {
6256 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6257 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6258 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6261 uint64_t PtrOff = ShAmt / 8;
6262 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6263 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
6264 PtrType, LN0->getBasePtr(),
6265 DAG.getConstant(PtrOff, PtrType));
6266 AddToWorklist(NewPtr.getNode());
6269 if (ExtType == ISD::NON_EXTLOAD)
6270 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6271 LN0->getPointerInfo().getWithOffset(PtrOff),
6272 LN0->isVolatile(), LN0->isNonTemporal(),
6273 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6275 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6276 LN0->getPointerInfo().getWithOffset(PtrOff),
6277 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6278 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6280 // Replace the old load's chain with the new load's chain.
6281 WorklistRemover DeadNodes(*this);
6282 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6284 // Shift the result left, if we've swallowed a left shift.
6285 SDValue Result = Load;
6286 if (ShLeftAmt != 0) {
6287 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6288 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6290 // If the shift amount is as large as the result size (but, presumably,
6291 // no larger than the source) then the useful bits of the result are
6292 // zero; we can't simply return the shortened shift, because the result
6293 // of that operation is undefined.
6294 if (ShLeftAmt >= VT.getSizeInBits())
6295 Result = DAG.getConstant(0, VT);
6297 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
6298 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
6301 // Return the new loaded value.
6305 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6306 SDValue N0 = N->getOperand(0);
6307 SDValue N1 = N->getOperand(1);
6308 EVT VT = N->getValueType(0);
6309 EVT EVT = cast<VTSDNode>(N1)->getVT();
6310 unsigned VTBits = VT.getScalarType().getSizeInBits();
6311 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6313 // fold (sext_in_reg c1) -> c1
6314 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6315 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6317 // If the input is already sign extended, just drop the extension.
6318 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6321 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6322 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6323 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6324 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6325 N0.getOperand(0), N1);
6327 // fold (sext_in_reg (sext x)) -> (sext x)
6328 // fold (sext_in_reg (aext x)) -> (sext x)
6329 // if x is small enough.
6330 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6331 SDValue N00 = N0.getOperand(0);
6332 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6333 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6334 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6337 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6338 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6339 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6341 // fold operands of sext_in_reg based on knowledge that the top bits are not
6343 if (SimplifyDemandedBits(SDValue(N, 0)))
6344 return SDValue(N, 0);
6346 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6347 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6348 SDValue NarrowLoad = ReduceLoadWidth(N);
6349 if (NarrowLoad.getNode())
6352 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6353 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6354 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6355 if (N0.getOpcode() == ISD::SRL) {
6356 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6357 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6358 // We can turn this into an SRA iff the input to the SRL is already sign
6360 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6361 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6362 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6363 N0.getOperand(0), N0.getOperand(1));
6367 // fold (sext_inreg (extload x)) -> (sextload x)
6368 if (ISD::isEXTLoad(N0.getNode()) &&
6369 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6370 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6371 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6372 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6373 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6374 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6376 LN0->getBasePtr(), EVT,
6377 LN0->getMemOperand());
6378 CombineTo(N, ExtLoad);
6379 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6380 AddToWorklist(ExtLoad.getNode());
6381 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6383 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6384 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6386 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6387 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6388 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6389 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6390 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6392 LN0->getBasePtr(), EVT,
6393 LN0->getMemOperand());
6394 CombineTo(N, ExtLoad);
6395 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6396 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6399 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6400 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6401 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6402 N0.getOperand(1), false);
6403 if (BSwap.getNode())
6404 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6408 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6409 // into a build_vector.
6410 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6411 SmallVector<SDValue, 8> Elts;
6412 unsigned NumElts = N0->getNumOperands();
6413 unsigned ShAmt = VTBits - EVTBits;
6415 for (unsigned i = 0; i != NumElts; ++i) {
6416 SDValue Op = N0->getOperand(i);
6417 if (Op->getOpcode() == ISD::UNDEF) {
6422 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6423 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6424 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6425 Op.getValueType()));
6428 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6434 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6435 SDValue N0 = N->getOperand(0);
6436 EVT VT = N->getValueType(0);
6437 bool isLE = TLI.isLittleEndian();
6440 if (N0.getValueType() == N->getValueType(0))
6442 // fold (truncate c1) -> c1
6443 if (isa<ConstantSDNode>(N0))
6444 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6445 // fold (truncate (truncate x)) -> (truncate x)
6446 if (N0.getOpcode() == ISD::TRUNCATE)
6447 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6448 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6449 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6450 N0.getOpcode() == ISD::SIGN_EXTEND ||
6451 N0.getOpcode() == ISD::ANY_EXTEND) {
6452 if (N0.getOperand(0).getValueType().bitsLT(VT))
6453 // if the source is smaller than the dest, we still need an extend
6454 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6456 if (N0.getOperand(0).getValueType().bitsGT(VT))
6457 // if the source is larger than the dest, than we just need the truncate
6458 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6459 // if the source and dest are the same type, we can drop both the extend
6460 // and the truncate.
6461 return N0.getOperand(0);
6464 // Fold extract-and-trunc into a narrow extract. For example:
6465 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6466 // i32 y = TRUNCATE(i64 x)
6468 // v16i8 b = BITCAST (v2i64 val)
6469 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6471 // Note: We only run this optimization after type legalization (which often
6472 // creates this pattern) and before operation legalization after which
6473 // we need to be more careful about the vector instructions that we generate.
6474 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6475 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6477 EVT VecTy = N0.getOperand(0).getValueType();
6478 EVT ExTy = N0.getValueType();
6479 EVT TrTy = N->getValueType(0);
6481 unsigned NumElem = VecTy.getVectorNumElements();
6482 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6484 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6485 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6487 SDValue EltNo = N0->getOperand(1);
6488 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6489 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6490 EVT IndexTy = TLI.getVectorIdxTy();
6491 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6493 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6494 NVT, N0.getOperand(0));
6496 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6498 DAG.getConstant(Index, IndexTy));
6502 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6503 if (N0.getOpcode() == ISD::SELECT) {
6504 EVT SrcVT = N0.getValueType();
6505 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6506 TLI.isTruncateFree(SrcVT, VT)) {
6508 SDValue Cond = N0.getOperand(0);
6509 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6510 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6511 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6515 // Fold a series of buildvector, bitcast, and truncate if possible.
6517 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6518 // (2xi32 (buildvector x, y)).
6519 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6520 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6521 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6522 N0.getOperand(0).hasOneUse()) {
6524 SDValue BuildVect = N0.getOperand(0);
6525 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6526 EVT TruncVecEltTy = VT.getVectorElementType();
6528 // Check that the element types match.
6529 if (BuildVectEltTy == TruncVecEltTy) {
6530 // Now we only need to compute the offset of the truncated elements.
6531 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6532 unsigned TruncVecNumElts = VT.getVectorNumElements();
6533 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6535 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6536 "Invalid number of elements");
6538 SmallVector<SDValue, 8> Opnds;
6539 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6540 Opnds.push_back(BuildVect.getOperand(i));
6542 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6546 // See if we can simplify the input to this truncate through knowledge that
6547 // only the low bits are being used.
6548 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6549 // Currently we only perform this optimization on scalars because vectors
6550 // may have different active low bits.
6551 if (!VT.isVector()) {
6553 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6554 VT.getSizeInBits()));
6555 if (Shorter.getNode())
6556 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6558 // fold (truncate (load x)) -> (smaller load x)
6559 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6560 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6561 SDValue Reduced = ReduceLoadWidth(N);
6562 if (Reduced.getNode())
6564 // Handle the case where the load remains an extending load even
6565 // after truncation.
6566 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6567 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6568 if (!LN0->isVolatile() &&
6569 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6570 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6571 VT, LN0->getChain(), LN0->getBasePtr(),
6573 LN0->getMemOperand());
6574 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6579 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6580 // where ... are all 'undef'.
6581 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6582 SmallVector<EVT, 8> VTs;
6585 unsigned NumDefs = 0;
6587 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6588 SDValue X = N0.getOperand(i);
6589 if (X.getOpcode() != ISD::UNDEF) {
6594 // Stop if more than one members are non-undef.
6597 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6598 VT.getVectorElementType(),
6599 X.getValueType().getVectorNumElements()));
6603 return DAG.getUNDEF(VT);
6606 assert(V.getNode() && "The single defined operand is empty!");
6607 SmallVector<SDValue, 8> Opnds;
6608 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6610 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6613 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6614 AddToWorklist(NV.getNode());
6615 Opnds.push_back(NV);
6617 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6621 // Simplify the operands using demanded-bits information.
6622 if (!VT.isVector() &&
6623 SimplifyDemandedBits(SDValue(N, 0)))
6624 return SDValue(N, 0);
6629 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6630 SDValue Elt = N->getOperand(i);
6631 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6632 return Elt.getNode();
6633 return Elt.getOperand(Elt.getResNo()).getNode();
6636 /// build_pair (load, load) -> load
6637 /// if load locations are consecutive.
6638 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6639 assert(N->getOpcode() == ISD::BUILD_PAIR);
6641 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6642 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6643 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6644 LD1->getAddressSpace() != LD2->getAddressSpace())
6646 EVT LD1VT = LD1->getValueType(0);
6648 if (ISD::isNON_EXTLoad(LD2) &&
6650 // If both are volatile this would reduce the number of volatile loads.
6651 // If one is volatile it might be ok, but play conservative and bail out.
6652 !LD1->isVolatile() &&
6653 !LD2->isVolatile() &&
6654 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6655 unsigned Align = LD1->getAlignment();
6656 unsigned NewAlign = TLI.getDataLayout()->
6657 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6659 if (NewAlign <= Align &&
6660 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6661 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6662 LD1->getBasePtr(), LD1->getPointerInfo(),
6663 false, false, false, Align);
6669 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6670 SDValue N0 = N->getOperand(0);
6671 EVT VT = N->getValueType(0);
6673 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6674 // Only do this before legalize, since afterward the target may be depending
6675 // on the bitconvert.
6676 // First check to see if this is all constant.
6678 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6680 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6682 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6683 assert(!DestEltVT.isVector() &&
6684 "Element type of vector ValueType must not be vector!");
6686 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6689 // If the input is a constant, let getNode fold it.
6690 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6691 // If we can't allow illegal operations, we need to check that this is just
6692 // a fp -> int or int -> conversion and that the resulting operation will
6694 if (!LegalOperations ||
6695 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
6696 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
6697 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
6698 TLI.isOperationLegal(ISD::Constant, VT)))
6699 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6702 // (conv (conv x, t1), t2) -> (conv x, t2)
6703 if (N0.getOpcode() == ISD::BITCAST)
6704 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6707 // fold (conv (load x)) -> (load (conv*)x)
6708 // If the resultant load doesn't need a higher alignment than the original!
6709 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6710 // Do not change the width of a volatile load.
6711 !cast<LoadSDNode>(N0)->isVolatile() &&
6712 // Do not remove the cast if the types differ in endian layout.
6713 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6714 TLI.hasBigEndianPartOrdering(VT) &&
6715 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6716 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6717 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6718 unsigned Align = TLI.getDataLayout()->
6719 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6720 unsigned OrigAlign = LN0->getAlignment();
6722 if (Align <= OrigAlign) {
6723 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6724 LN0->getBasePtr(), LN0->getPointerInfo(),
6725 LN0->isVolatile(), LN0->isNonTemporal(),
6726 LN0->isInvariant(), OrigAlign,
6728 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6733 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6734 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6735 // This often reduces constant pool loads.
6736 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6737 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6738 N0.getNode()->hasOneUse() && VT.isInteger() &&
6739 !VT.isVector() && !N0.getValueType().isVector()) {
6740 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6742 AddToWorklist(NewConv.getNode());
6744 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6745 if (N0.getOpcode() == ISD::FNEG)
6746 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6747 NewConv, DAG.getConstant(SignBit, VT));
6748 assert(N0.getOpcode() == ISD::FABS);
6749 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6750 NewConv, DAG.getConstant(~SignBit, VT));
6753 // fold (bitconvert (fcopysign cst, x)) ->
6754 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6755 // Note that we don't handle (copysign x, cst) because this can always be
6756 // folded to an fneg or fabs.
6757 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6758 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6759 VT.isInteger() && !VT.isVector()) {
6760 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6761 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6762 if (isTypeLegal(IntXVT)) {
6763 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6764 IntXVT, N0.getOperand(1));
6765 AddToWorklist(X.getNode());
6767 // If X has a different width than the result/lhs, sext it or truncate it.
6768 unsigned VTWidth = VT.getSizeInBits();
6769 if (OrigXWidth < VTWidth) {
6770 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6771 AddToWorklist(X.getNode());
6772 } else if (OrigXWidth > VTWidth) {
6773 // To get the sign bit in the right place, we have to shift it right
6774 // before truncating.
6775 X = DAG.getNode(ISD::SRL, SDLoc(X),
6776 X.getValueType(), X,
6777 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6778 AddToWorklist(X.getNode());
6779 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6780 AddToWorklist(X.getNode());
6783 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6784 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6785 X, DAG.getConstant(SignBit, VT));
6786 AddToWorklist(X.getNode());
6788 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6789 VT, N0.getOperand(0));
6790 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6791 Cst, DAG.getConstant(~SignBit, VT));
6792 AddToWorklist(Cst.getNode());
6794 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6798 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6799 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6800 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6801 if (CombineLD.getNode())
6808 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6809 EVT VT = N->getValueType(0);
6810 return CombineConsecutiveLoads(N, VT);
6813 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6814 /// operands. DstEltVT indicates the destination element value type.
6815 SDValue DAGCombiner::
6816 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6817 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6819 // If this is already the right type, we're done.
6820 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6822 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6823 unsigned DstBitSize = DstEltVT.getSizeInBits();
6825 // If this is a conversion of N elements of one type to N elements of another
6826 // type, convert each element. This handles FP<->INT cases.
6827 if (SrcBitSize == DstBitSize) {
6828 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6829 BV->getValueType(0).getVectorNumElements());
6831 // Due to the FP element handling below calling this routine recursively,
6832 // we can end up with a scalar-to-vector node here.
6833 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6834 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6835 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6836 DstEltVT, BV->getOperand(0)));
6838 SmallVector<SDValue, 8> Ops;
6839 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6840 SDValue Op = BV->getOperand(i);
6841 // If the vector element type is not legal, the BUILD_VECTOR operands
6842 // are promoted and implicitly truncated. Make that explicit here.
6843 if (Op.getValueType() != SrcEltVT)
6844 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6845 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6847 AddToWorklist(Ops.back().getNode());
6849 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6852 // Otherwise, we're growing or shrinking the elements. To avoid having to
6853 // handle annoying details of growing/shrinking FP values, we convert them to
6855 if (SrcEltVT.isFloatingPoint()) {
6856 // Convert the input float vector to a int vector where the elements are the
6858 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6859 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6863 // Now we know the input is an integer vector. If the output is a FP type,
6864 // convert to integer first, then to FP of the right size.
6865 if (DstEltVT.isFloatingPoint()) {
6866 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6867 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6869 // Next, convert to FP elements of the same size.
6870 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6873 // Okay, we know the src/dst types are both integers of differing types.
6874 // Handling growing first.
6875 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6876 if (SrcBitSize < DstBitSize) {
6877 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6879 SmallVector<SDValue, 8> Ops;
6880 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6881 i += NumInputsPerOutput) {
6882 bool isLE = TLI.isLittleEndian();
6883 APInt NewBits = APInt(DstBitSize, 0);
6884 bool EltIsUndef = true;
6885 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6886 // Shift the previously computed bits over.
6887 NewBits <<= SrcBitSize;
6888 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6889 if (Op.getOpcode() == ISD::UNDEF) continue;
6892 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6893 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6897 Ops.push_back(DAG.getUNDEF(DstEltVT));
6899 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6902 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6903 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6906 // Finally, this must be the case where we are shrinking elements: each input
6907 // turns into multiple outputs.
6908 bool isS2V = ISD::isScalarToVector(BV);
6909 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6910 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6911 NumOutputsPerInput*BV->getNumOperands());
6912 SmallVector<SDValue, 8> Ops;
6914 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6915 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6916 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
6920 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6921 getAPIntValue().zextOrTrunc(SrcBitSize);
6923 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6924 APInt ThisVal = OpVal.trunc(DstBitSize);
6925 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6926 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6927 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6928 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6930 OpVal = OpVal.lshr(DstBitSize);
6933 // For big endian targets, swap the order of the pieces of each element.
6934 if (TLI.isBigEndian())
6935 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6938 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6941 SDValue DAGCombiner::visitFADD(SDNode *N) {
6942 SDValue N0 = N->getOperand(0);
6943 SDValue N1 = N->getOperand(1);
6944 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6945 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6946 EVT VT = N->getValueType(0);
6947 const TargetOptions &Options = DAG.getTarget().Options;
6950 if (VT.isVector()) {
6951 SDValue FoldedVOp = SimplifyVBinOp(N);
6952 if (FoldedVOp.getNode()) return FoldedVOp;
6955 // fold (fadd c1, c2) -> c1 + c2
6957 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6959 // canonicalize constant to RHS
6960 if (N0CFP && !N1CFP)
6961 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6963 // fold (fadd A, (fneg B)) -> (fsub A, B)
6964 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6965 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6966 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6967 GetNegatedExpression(N1, DAG, LegalOperations));
6969 // fold (fadd (fneg A), B) -> (fsub B, A)
6970 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6971 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6972 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6973 GetNegatedExpression(N0, DAG, LegalOperations));
6975 // If 'unsafe math' is enabled, fold lots of things.
6976 if (Options.UnsafeFPMath) {
6977 // No FP constant should be created after legalization as Instruction
6978 // Selection pass has a hard time dealing with FP constants.
6979 bool AllowNewConst = (Level < AfterLegalizeDAG);
6981 // fold (fadd A, 0) -> A
6982 if (N1CFP && N1CFP->getValueAPF().isZero())
6985 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6986 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6987 isa<ConstantFPSDNode>(N0.getOperand(1)))
6988 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6989 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6990 N0.getOperand(1), N1));
6992 // If allowed, fold (fadd (fneg x), x) -> 0.0
6993 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6994 return DAG.getConstantFP(0.0, VT);
6996 // If allowed, fold (fadd x, (fneg x)) -> 0.0
6997 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6998 return DAG.getConstantFP(0.0, VT);
7000 // We can fold chains of FADD's of the same value into multiplications.
7001 // This transform is not safe in general because we are reducing the number
7002 // of rounding steps.
7003 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7004 if (N0.getOpcode() == ISD::FMUL) {
7005 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7006 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7008 // (fadd (fmul x, c), x) -> (fmul x, c+1)
7009 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7010 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7012 DAG.getConstantFP(1.0, VT));
7013 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
7016 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7017 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7018 N1.getOperand(0) == N1.getOperand(1) &&
7019 N0.getOperand(0) == N1.getOperand(0)) {
7020 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7022 DAG.getConstantFP(2.0, VT));
7023 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7024 N0.getOperand(0), NewCFP);
7028 if (N1.getOpcode() == ISD::FMUL) {
7029 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7030 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7032 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7033 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7034 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7036 DAG.getConstantFP(1.0, VT));
7037 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
7040 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7041 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7042 N0.getOperand(0) == N0.getOperand(1) &&
7043 N1.getOperand(0) == N0.getOperand(0)) {
7044 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7046 DAG.getConstantFP(2.0, VT));
7047 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
7051 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7052 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7053 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7054 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7055 (N0.getOperand(0) == N1))
7056 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7057 N1, DAG.getConstantFP(3.0, VT));
7060 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7061 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7062 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7063 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7064 N1.getOperand(0) == N0)
7065 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7066 N0, DAG.getConstantFP(3.0, VT));
7069 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7070 if (AllowNewConst &&
7071 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7072 N0.getOperand(0) == N0.getOperand(1) &&
7073 N1.getOperand(0) == N1.getOperand(1) &&
7074 N0.getOperand(0) == N1.getOperand(0))
7075 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7076 N0.getOperand(0), DAG.getConstantFP(4.0, VT));
7078 } // enable-unsafe-fp-math
7080 // FADD -> FMA combines:
7081 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
7082 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7083 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
7085 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7086 if (N0.getOpcode() == ISD::FMUL &&
7087 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
7088 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7089 N0.getOperand(0), N0.getOperand(1), N1);
7091 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7092 // Note: Commutes FADD operands.
7093 if (N1.getOpcode() == ISD::FMUL &&
7094 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
7095 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7096 N1.getOperand(0), N1.getOperand(1), N0);
7098 // When FP_EXTEND nodes are free on the target, and there is an opportunity
7099 // to combine into FMA, arrange such nodes accordingly.
7100 if (TLI.isFPExtFree(VT)) {
7102 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7103 if (N0.getOpcode() == ISD::FP_EXTEND) {
7104 SDValue N00 = N0.getOperand(0);
7105 if (N00.getOpcode() == ISD::FMUL)
7106 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7107 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7109 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7110 N00.getOperand(1)), N1);
7113 // fold (fadd x, (fpext (fmul y, z)), z) -> (fma (fpext y), (fpext z), x)
7114 // Note: Commutes FADD operands.
7115 if (N1.getOpcode() == ISD::FP_EXTEND) {
7116 SDValue N10 = N1.getOperand(0);
7117 if (N10.getOpcode() == ISD::FMUL)
7118 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7119 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7121 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7122 N10.getOperand(1)), N0);
7126 // More folding opportunities when target permits.
7127 if (TLI.enableAggressiveFMAFusion(VT)) {
7129 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7130 if (N0.getOpcode() == ISD::FMA &&
7131 N0.getOperand(2).getOpcode() == ISD::FMUL)
7132 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7133 N0.getOperand(0), N0.getOperand(1),
7134 DAG.getNode(ISD::FMA, SDLoc(N), VT,
7135 N0.getOperand(2).getOperand(0),
7136 N0.getOperand(2).getOperand(1),
7139 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7140 if (N1->getOpcode() == ISD::FMA &&
7141 N1.getOperand(2).getOpcode() == ISD::FMUL)
7142 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7143 N1.getOperand(0), N1.getOperand(1),
7144 DAG.getNode(ISD::FMA, SDLoc(N), VT,
7145 N1.getOperand(2).getOperand(0),
7146 N1.getOperand(2).getOperand(1),
7154 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7155 SDValue N0 = N->getOperand(0);
7156 SDValue N1 = N->getOperand(1);
7157 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7158 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7159 EVT VT = N->getValueType(0);
7161 const TargetOptions &Options = DAG.getTarget().Options;
7164 if (VT.isVector()) {
7165 SDValue FoldedVOp = SimplifyVBinOp(N);
7166 if (FoldedVOp.getNode()) return FoldedVOp;
7169 // fold (fsub c1, c2) -> c1-c2
7171 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
7173 // fold (fsub A, (fneg B)) -> (fadd A, B)
7174 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7175 return DAG.getNode(ISD::FADD, dl, VT, N0,
7176 GetNegatedExpression(N1, DAG, LegalOperations));
7178 // If 'unsafe math' is enabled, fold lots of things.
7179 if (Options.UnsafeFPMath) {
7181 if (N1CFP && N1CFP->getValueAPF().isZero())
7184 // (fsub 0, B) -> -B
7185 if (N0CFP && N0CFP->getValueAPF().isZero()) {
7186 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7187 return GetNegatedExpression(N1, DAG, LegalOperations);
7188 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7189 return DAG.getNode(ISD::FNEG, dl, VT, N1);
7192 // (fsub x, x) -> 0.0
7194 return DAG.getConstantFP(0.0f, VT);
7196 // (fsub x, (fadd x, y)) -> (fneg y)
7197 // (fsub x, (fadd y, x)) -> (fneg y)
7198 if (N1.getOpcode() == ISD::FADD) {
7199 SDValue N10 = N1->getOperand(0);
7200 SDValue N11 = N1->getOperand(1);
7202 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7203 return GetNegatedExpression(N11, DAG, LegalOperations);
7205 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7206 return GetNegatedExpression(N10, DAG, LegalOperations);
7210 // FSUB -> FMA combines:
7211 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
7212 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7213 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
7215 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7216 if (N0.getOpcode() == ISD::FMUL &&
7217 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
7218 return DAG.getNode(ISD::FMA, dl, VT,
7219 N0.getOperand(0), N0.getOperand(1),
7220 DAG.getNode(ISD::FNEG, dl, VT, N1));
7222 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7223 // Note: Commutes FSUB operands.
7224 if (N1.getOpcode() == ISD::FMUL &&
7225 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
7226 return DAG.getNode(ISD::FMA, dl, VT,
7227 DAG.getNode(ISD::FNEG, dl, VT,
7229 N1.getOperand(1), N0);
7231 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7232 if (N0.getOpcode() == ISD::FNEG &&
7233 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7234 ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
7235 TLI.enableAggressiveFMAFusion(VT))) {
7236 SDValue N00 = N0.getOperand(0).getOperand(0);
7237 SDValue N01 = N0.getOperand(0).getOperand(1);
7238 return DAG.getNode(ISD::FMA, dl, VT,
7239 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
7240 DAG.getNode(ISD::FNEG, dl, VT, N1));
7243 // When FP_EXTEND nodes are free on the target, and there is an opportunity
7244 // to combine into FMA, arrange such nodes accordingly.
7245 if (TLI.isFPExtFree(VT)) {
7247 // fold (fsub (fpext (fmul x, y)), z)
7248 // -> (fma (fpext x), (fpext y), (fneg z))
7249 if (N0.getOpcode() == ISD::FP_EXTEND) {
7250 SDValue N00 = N0.getOperand(0);
7251 if (N00.getOpcode() == ISD::FMUL)
7252 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7253 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7255 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7257 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N1));
7260 // fold (fsub x, (fpext (fmul y, z)))
7261 // -> (fma (fneg (fpext y)), (fpext z), x)
7262 // Note: Commutes FSUB operands.
7263 if (N1.getOpcode() == ISD::FP_EXTEND) {
7264 SDValue N10 = N1.getOperand(0);
7265 if (N10.getOpcode() == ISD::FMUL)
7266 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7267 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7268 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7269 VT, N10.getOperand(0))),
7270 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7275 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7276 // -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7277 if (N0.getOpcode() == ISD::FP_EXTEND) {
7278 SDValue N00 = N0.getOperand(0);
7279 if (N00.getOpcode() == ISD::FNEG) {
7280 SDValue N000 = N00.getOperand(0);
7281 if (N000.getOpcode() == ISD::FMUL) {
7282 return DAG.getNode(ISD::FMA, dl, VT,
7283 DAG.getNode(ISD::FNEG, dl, VT,
7284 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7285 VT, N000.getOperand(0))),
7286 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7287 N000.getOperand(1)),
7288 DAG.getNode(ISD::FNEG, dl, VT, N1));
7293 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7294 // -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7295 if (N0.getOpcode() == ISD::FNEG) {
7296 SDValue N00 = N0.getOperand(0);
7297 if (N00.getOpcode() == ISD::FP_EXTEND) {
7298 SDValue N000 = N00.getOperand(0);
7299 if (N000.getOpcode() == ISD::FMUL) {
7300 return DAG.getNode(ISD::FMA, dl, VT,
7301 DAG.getNode(ISD::FNEG, dl, VT,
7302 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7303 VT, N000.getOperand(0))),
7304 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7305 N000.getOperand(1)),
7306 DAG.getNode(ISD::FNEG, dl, VT, N1));
7312 // More folding opportunities when target permits.
7313 if (TLI.enableAggressiveFMAFusion(VT)) {
7315 // fold (fsub (fma x, y, (fmul u, v)), z)
7316 // -> (fma x, y (fma u, v, (fneg z)))
7317 if (N0.getOpcode() == ISD::FMA &&
7318 N0.getOperand(2).getOpcode() == ISD::FMUL)
7319 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7320 N0.getOperand(0), N0.getOperand(1),
7321 DAG.getNode(ISD::FMA, SDLoc(N), VT,
7322 N0.getOperand(2).getOperand(0),
7323 N0.getOperand(2).getOperand(1),
7324 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7327 // fold (fsub x, (fma y, z, (fmul u, v)))
7328 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7329 if (N1.getOpcode() == ISD::FMA &&
7330 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7331 SDValue N20 = N1.getOperand(2).getOperand(0);
7332 SDValue N21 = N1.getOperand(2).getOperand(1);
7333 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7334 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7337 DAG.getNode(ISD::FMA, SDLoc(N), VT,
7338 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7348 SDValue DAGCombiner::visitFMUL(SDNode *N) {
7349 SDValue N0 = N->getOperand(0);
7350 SDValue N1 = N->getOperand(1);
7351 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7352 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7353 EVT VT = N->getValueType(0);
7354 const TargetOptions &Options = DAG.getTarget().Options;
7357 if (VT.isVector()) {
7358 // This just handles C1 * C2 for vectors. Other vector folds are below.
7359 SDValue FoldedVOp = SimplifyVBinOp(N);
7360 if (FoldedVOp.getNode())
7362 // Canonicalize vector constant to RHS.
7363 if (N0.getOpcode() == ISD::BUILD_VECTOR &&
7364 N1.getOpcode() != ISD::BUILD_VECTOR)
7365 if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
7366 if (BV0->isConstant())
7367 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
7370 // fold (fmul c1, c2) -> c1*c2
7372 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
7374 // canonicalize constant to RHS
7375 if (N0CFP && !N1CFP)
7376 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
7378 // fold (fmul A, 1.0) -> A
7379 if (N1CFP && N1CFP->isExactlyValue(1.0))
7382 if (Options.UnsafeFPMath) {
7383 // fold (fmul A, 0) -> 0
7384 if (N1CFP && N1CFP->getValueAPF().isZero())
7387 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7388 if (N0.getOpcode() == ISD::FMUL) {
7389 // Fold scalars or any vector constants (not just splats).
7390 // This fold is done in general by InstCombine, but extra fmul insts
7391 // may have been generated during lowering.
7392 SDValue N01 = N0.getOperand(1);
7393 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7394 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7395 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7396 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7398 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7399 return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
7403 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7404 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7405 // during an early run of DAGCombiner can prevent folding with fmuls
7406 // inserted during lowering.
7407 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7409 const SDValue Two = DAG.getConstantFP(2.0, VT);
7410 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7411 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7415 // fold (fmul X, 2.0) -> (fadd X, X)
7416 if (N1CFP && N1CFP->isExactlyValue(+2.0))
7417 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
7419 // fold (fmul X, -1.0) -> (fneg X)
7420 if (N1CFP && N1CFP->isExactlyValue(-1.0))
7421 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7422 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
7424 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7425 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7426 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7427 // Both can be negated for free, check to see if at least one is cheaper
7429 if (LHSNeg == 2 || RHSNeg == 2)
7430 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7431 GetNegatedExpression(N0, DAG, LegalOperations),
7432 GetNegatedExpression(N1, DAG, LegalOperations));
7439 SDValue DAGCombiner::visitFMA(SDNode *N) {
7440 SDValue N0 = N->getOperand(0);
7441 SDValue N1 = N->getOperand(1);
7442 SDValue N2 = N->getOperand(2);
7443 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7444 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7445 EVT VT = N->getValueType(0);
7447 const TargetOptions &Options = DAG.getTarget().Options;
7449 // Constant fold FMA.
7450 if (isa<ConstantFPSDNode>(N0) &&
7451 isa<ConstantFPSDNode>(N1) &&
7452 isa<ConstantFPSDNode>(N2)) {
7453 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7456 if (Options.UnsafeFPMath) {
7457 if (N0CFP && N0CFP->isZero())
7459 if (N1CFP && N1CFP->isZero())
7462 if (N0CFP && N0CFP->isExactlyValue(1.0))
7463 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
7464 if (N1CFP && N1CFP->isExactlyValue(1.0))
7465 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
7467 // Canonicalize (fma c, x, y) -> (fma x, c, y)
7468 if (N0CFP && !N1CFP)
7469 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
7471 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
7472 if (Options.UnsafeFPMath && N1CFP &&
7473 N2.getOpcode() == ISD::FMUL &&
7474 N0 == N2.getOperand(0) &&
7475 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7476 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7477 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7481 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
7482 if (Options.UnsafeFPMath &&
7483 N0.getOpcode() == ISD::FMUL && N1CFP &&
7484 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7485 return DAG.getNode(ISD::FMA, dl, VT,
7487 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7491 // (fma x, 1, y) -> (fadd x, y)
7492 // (fma x, -1, y) -> (fadd (fneg x), y)
7494 if (N1CFP->isExactlyValue(1.0))
7495 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7497 if (N1CFP->isExactlyValue(-1.0) &&
7498 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7499 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
7500 AddToWorklist(RHSNeg.getNode());
7501 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7505 // (fma x, c, x) -> (fmul x, (c+1))
7506 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
7507 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7508 DAG.getNode(ISD::FADD, dl, VT,
7509 N1, DAG.getConstantFP(1.0, VT)));
7511 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
7512 if (Options.UnsafeFPMath && N1CFP &&
7513 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7514 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7515 DAG.getNode(ISD::FADD, dl, VT,
7516 N1, DAG.getConstantFP(-1.0, VT)));
7522 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7523 SDValue N0 = N->getOperand(0);
7524 SDValue N1 = N->getOperand(1);
7525 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7526 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7527 EVT VT = N->getValueType(0);
7529 const TargetOptions &Options = DAG.getTarget().Options;
7532 if (VT.isVector()) {
7533 SDValue FoldedVOp = SimplifyVBinOp(N);
7534 if (FoldedVOp.getNode()) return FoldedVOp;
7537 // fold (fdiv c1, c2) -> c1/c2
7539 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7541 if (Options.UnsafeFPMath) {
7542 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7544 // Compute the reciprocal 1.0 / c2.
7545 APFloat N1APF = N1CFP->getValueAPF();
7546 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7547 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7548 // Only do the transform if the reciprocal is a legal fp immediate that
7549 // isn't too nasty (eg NaN, denormal, ...).
7550 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7551 (!LegalOperations ||
7552 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7553 // backend)... we should handle this gracefully after Legalize.
7554 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7555 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7556 TLI.isFPImmLegal(Recip, VT)))
7557 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7558 DAG.getConstantFP(Recip, VT));
7561 // If this FDIV is part of a reciprocal square root, it may be folded
7562 // into a target-specific square root estimate instruction.
7563 if (N1.getOpcode() == ISD::FSQRT) {
7564 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7565 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7567 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7568 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7569 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7570 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7571 AddToWorklist(RV.getNode());
7572 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7574 } else if (N1.getOpcode() == ISD::FP_ROUND &&
7575 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7576 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7577 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7578 AddToWorklist(RV.getNode());
7579 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7581 } else if (N1.getOpcode() == ISD::FMUL) {
7582 // Look through an FMUL. Even though this won't remove the FDIV directly,
7583 // it's still worthwhile to get rid of the FSQRT if possible.
7586 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7587 SqrtOp = N1.getOperand(0);
7588 OtherOp = N1.getOperand(1);
7589 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7590 SqrtOp = N1.getOperand(1);
7591 OtherOp = N1.getOperand(0);
7593 if (SqrtOp.getNode()) {
7594 // We found a FSQRT, so try to make this fold:
7595 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7596 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7597 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7598 AddToWorklist(RV.getNode());
7599 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7604 // Fold into a reciprocal estimate and multiply instead of a real divide.
7605 if (SDValue RV = BuildReciprocalEstimate(N1)) {
7606 AddToWorklist(RV.getNode());
7607 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7611 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7612 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7613 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7614 // Both can be negated for free, check to see if at least one is cheaper
7616 if (LHSNeg == 2 || RHSNeg == 2)
7617 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7618 GetNegatedExpression(N0, DAG, LegalOperations),
7619 GetNegatedExpression(N1, DAG, LegalOperations));
7623 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7625 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
7626 // Notice that this is not always beneficial. One reason is different target
7627 // may have different costs for FDIV and FMUL, so sometimes the cost of two
7628 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
7629 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
7630 if (Options.UnsafeFPMath) {
7631 // Skip if current node is a reciprocal.
7632 if (N0CFP && N0CFP->isExactlyValue(1.0))
7635 SmallVector<SDNode *, 4> Users;
7636 // Find all FDIV users of the same divisor.
7637 for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
7638 UE = N1.getNode()->use_end();
7640 SDNode *User = UI.getUse().getUser();
7641 if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
7642 Users.push_back(User);
7645 if (TLI.combineRepeatedFPDivisors(Users.size())) {
7646 SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
7647 SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
7649 // Dividend / Divisor -> Dividend * Reciprocal
7650 for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
7651 if ((*I)->getOperand(0) != FPOne) {
7652 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
7653 (*I)->getOperand(0), Reciprocal);
7654 DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
7664 SDValue DAGCombiner::visitFREM(SDNode *N) {
7665 SDValue N0 = N->getOperand(0);
7666 SDValue N1 = N->getOperand(1);
7667 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7668 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7669 EVT VT = N->getValueType(0);
7671 // fold (frem c1, c2) -> fmod(c1,c2)
7673 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7678 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7679 if (DAG.getTarget().Options.UnsafeFPMath &&
7680 !TLI.isFsqrtCheap()) {
7681 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
7682 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7683 EVT VT = RV.getValueType();
7684 RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7685 AddToWorklist(RV.getNode());
7687 // Unfortunately, RV is now NaN if the input was exactly 0.
7688 // Select out this case and force the answer to 0.
7689 SDValue Zero = DAG.getConstantFP(0.0, VT);
7691 DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7692 N->getOperand(0), Zero, ISD::SETEQ);
7693 AddToWorklist(ZeroCmp.getNode());
7694 AddToWorklist(RV.getNode());
7696 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7697 SDLoc(N), VT, ZeroCmp, Zero, RV);
7704 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7705 SDValue N0 = N->getOperand(0);
7706 SDValue N1 = N->getOperand(1);
7707 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7708 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7709 EVT VT = N->getValueType(0);
7711 if (N0CFP && N1CFP) // Constant fold
7712 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7715 const APFloat& V = N1CFP->getValueAPF();
7716 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7717 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7718 if (!V.isNegative()) {
7719 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7720 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7722 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7723 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7724 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7728 // copysign(fabs(x), y) -> copysign(x, y)
7729 // copysign(fneg(x), y) -> copysign(x, y)
7730 // copysign(copysign(x,z), y) -> copysign(x, y)
7731 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7732 N0.getOpcode() == ISD::FCOPYSIGN)
7733 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7734 N0.getOperand(0), N1);
7736 // copysign(x, abs(y)) -> abs(x)
7737 if (N1.getOpcode() == ISD::FABS)
7738 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7740 // copysign(x, copysign(y,z)) -> copysign(x, z)
7741 if (N1.getOpcode() == ISD::FCOPYSIGN)
7742 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7743 N0, N1.getOperand(1));
7745 // copysign(x, fp_extend(y)) -> copysign(x, y)
7746 // copysign(x, fp_round(y)) -> copysign(x, y)
7747 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7748 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7749 N0, N1.getOperand(0));
7754 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7755 SDValue N0 = N->getOperand(0);
7756 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7757 EVT VT = N->getValueType(0);
7758 EVT OpVT = N0.getValueType();
7760 // fold (sint_to_fp c1) -> c1fp
7762 // ...but only if the target supports immediate floating-point values
7763 (!LegalOperations ||
7764 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7765 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7767 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7768 // but UINT_TO_FP is legal on this target, try to convert.
7769 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7770 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7771 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7772 if (DAG.SignBitIsZero(N0))
7773 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7776 // The next optimizations are desirable only if SELECT_CC can be lowered.
7777 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7778 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7779 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7781 (!LegalOperations ||
7782 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7784 { N0.getOperand(0), N0.getOperand(1),
7785 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7787 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7790 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7791 // (select_cc x, y, 1.0, 0.0,, cc)
7792 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7793 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7794 (!LegalOperations ||
7795 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7797 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7798 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7799 N0.getOperand(0).getOperand(2) };
7800 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7807 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7808 SDValue N0 = N->getOperand(0);
7809 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7810 EVT VT = N->getValueType(0);
7811 EVT OpVT = N0.getValueType();
7813 // fold (uint_to_fp c1) -> c1fp
7815 // ...but only if the target supports immediate floating-point values
7816 (!LegalOperations ||
7817 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7818 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7820 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7821 // but SINT_TO_FP is legal on this target, try to convert.
7822 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7823 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7824 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7825 if (DAG.SignBitIsZero(N0))
7826 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7829 // The next optimizations are desirable only if SELECT_CC can be lowered.
7830 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7831 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7833 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7834 (!LegalOperations ||
7835 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7837 { N0.getOperand(0), N0.getOperand(1),
7838 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7840 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7847 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
7848 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
7849 SDValue N0 = N->getOperand(0);
7850 EVT VT = N->getValueType(0);
7852 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
7855 SDValue Src = N0.getOperand(0);
7856 EVT SrcVT = Src.getValueType();
7857 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
7858 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
7860 // We can safely assume the conversion won't overflow the output range,
7861 // because (for example) (uint8_t)18293.f is undefined behavior.
7863 // Since we can assume the conversion won't overflow, our decision as to
7864 // whether the input will fit in the float should depend on the minimum
7865 // of the input range and output range.
7867 // This means this is also safe for a signed input and unsigned output, since
7868 // a negative input would lead to undefined behavior.
7869 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
7870 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
7871 unsigned ActualSize = std::min(InputSize, OutputSize);
7872 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
7874 // We can only fold away the float conversion if the input range can be
7875 // represented exactly in the float range.
7876 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
7877 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
7878 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
7880 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
7882 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
7883 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
7886 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
7891 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7892 SDValue N0 = N->getOperand(0);
7893 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7894 EVT VT = N->getValueType(0);
7896 // fold (fp_to_sint c1fp) -> c1
7898 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7900 return FoldIntToFPToInt(N, DAG);
7903 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7904 SDValue N0 = N->getOperand(0);
7905 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7906 EVT VT = N->getValueType(0);
7908 // fold (fp_to_uint c1fp) -> c1
7910 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7912 return FoldIntToFPToInt(N, DAG);
7915 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7916 SDValue N0 = N->getOperand(0);
7917 SDValue N1 = N->getOperand(1);
7918 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7919 EVT VT = N->getValueType(0);
7921 // fold (fp_round c1fp) -> c1fp
7923 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7925 // fold (fp_round (fp_extend x)) -> x
7926 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7927 return N0.getOperand(0);
7929 // fold (fp_round (fp_round x)) -> (fp_round x)
7930 if (N0.getOpcode() == ISD::FP_ROUND) {
7931 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
7932 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
7933 // If the first fp_round isn't a value preserving truncation, it might
7934 // introduce a tie in the second fp_round, that wouldn't occur in the
7935 // single-step fp_round we want to fold to.
7936 // In other words, double rounding isn't the same as rounding.
7937 // Also, this is a value preserving truncation iff both fp_round's are.
7938 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc)
7939 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7940 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc));
7943 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7944 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7945 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7946 N0.getOperand(0), N1);
7947 AddToWorklist(Tmp.getNode());
7948 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7949 Tmp, N0.getOperand(1));
7955 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7956 SDValue N0 = N->getOperand(0);
7957 EVT VT = N->getValueType(0);
7958 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7959 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7961 // fold (fp_round_inreg c1fp) -> c1fp
7962 if (N0CFP && isTypeLegal(EVT)) {
7963 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7964 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7970 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7971 SDValue N0 = N->getOperand(0);
7972 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7973 EVT VT = N->getValueType(0);
7975 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7976 if (N->hasOneUse() &&
7977 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7980 // fold (fp_extend c1fp) -> c1fp
7982 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7984 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7986 if (N0.getOpcode() == ISD::FP_ROUND
7987 && N0.getNode()->getConstantOperandVal(1) == 1) {
7988 SDValue In = N0.getOperand(0);
7989 if (In.getValueType() == VT) return In;
7990 if (VT.bitsLT(In.getValueType()))
7991 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7992 In, N0.getOperand(1));
7993 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7996 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7997 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7998 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
7999 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8000 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8002 LN0->getBasePtr(), N0.getValueType(),
8003 LN0->getMemOperand());
8004 CombineTo(N, ExtLoad);
8005 CombineTo(N0.getNode(),
8006 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8007 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
8008 ExtLoad.getValue(1));
8009 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8015 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8016 SDValue N0 = N->getOperand(0);
8017 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8018 EVT VT = N->getValueType(0);
8020 // fold (fceil c1) -> fceil(c1)
8022 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8027 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8028 SDValue N0 = N->getOperand(0);
8029 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8030 EVT VT = N->getValueType(0);
8032 // fold (ftrunc c1) -> ftrunc(c1)
8034 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8039 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8040 SDValue N0 = N->getOperand(0);
8041 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8042 EVT VT = N->getValueType(0);
8044 // fold (ffloor c1) -> ffloor(c1)
8046 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8051 // FIXME: FNEG and FABS have a lot in common; refactor.
8052 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8053 SDValue N0 = N->getOperand(0);
8054 EVT VT = N->getValueType(0);
8056 if (VT.isVector()) {
8057 SDValue FoldedVOp = SimplifyVUnaryOp(N);
8058 if (FoldedVOp.getNode()) return FoldedVOp;
8061 // Constant fold FNEG.
8062 if (isa<ConstantFPSDNode>(N0))
8063 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
8065 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8066 &DAG.getTarget().Options))
8067 return GetNegatedExpression(N0, DAG, LegalOperations);
8069 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8070 // constant pool values.
8071 if (!TLI.isFNegFree(VT) &&
8072 N0.getOpcode() == ISD::BITCAST &&
8073 N0.getNode()->hasOneUse()) {
8074 SDValue Int = N0.getOperand(0);
8075 EVT IntVT = Int.getValueType();
8076 if (IntVT.isInteger() && !IntVT.isVector()) {
8078 if (N0.getValueType().isVector()) {
8079 // For a vector, get a mask such as 0x80... per scalar element
8081 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8082 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8084 // For a scalar, just generate 0x80...
8085 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8087 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
8088 DAG.getConstant(SignMask, IntVT));
8089 AddToWorklist(Int.getNode());
8090 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8094 // (fneg (fmul c, x)) -> (fmul -c, x)
8095 if (N0.getOpcode() == ISD::FMUL) {
8096 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8098 APFloat CVal = CFP1->getValueAPF();
8100 if (Level >= AfterLegalizeDAG &&
8101 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8102 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8104 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8105 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8112 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8113 SDValue N0 = N->getOperand(0);
8114 SDValue N1 = N->getOperand(1);
8115 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8116 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8118 if (N0CFP && N1CFP) {
8119 const APFloat &C0 = N0CFP->getValueAPF();
8120 const APFloat &C1 = N1CFP->getValueAPF();
8121 return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
8125 EVT VT = N->getValueType(0);
8126 // Canonicalize to constant on RHS.
8127 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8133 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8134 SDValue N0 = N->getOperand(0);
8135 SDValue N1 = N->getOperand(1);
8136 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8137 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8139 if (N0CFP && N1CFP) {
8140 const APFloat &C0 = N0CFP->getValueAPF();
8141 const APFloat &C1 = N1CFP->getValueAPF();
8142 return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
8146 EVT VT = N->getValueType(0);
8147 // Canonicalize to constant on RHS.
8148 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8154 SDValue DAGCombiner::visitFABS(SDNode *N) {
8155 SDValue N0 = N->getOperand(0);
8156 EVT VT = N->getValueType(0);
8158 if (VT.isVector()) {
8159 SDValue FoldedVOp = SimplifyVUnaryOp(N);
8160 if (FoldedVOp.getNode()) return FoldedVOp;
8163 // fold (fabs c1) -> fabs(c1)
8164 if (isa<ConstantFPSDNode>(N0))
8165 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8167 // fold (fabs (fabs x)) -> (fabs x)
8168 if (N0.getOpcode() == ISD::FABS)
8169 return N->getOperand(0);
8171 // fold (fabs (fneg x)) -> (fabs x)
8172 // fold (fabs (fcopysign x, y)) -> (fabs x)
8173 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8174 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8176 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8177 // constant pool values.
8178 if (!TLI.isFAbsFree(VT) &&
8179 N0.getOpcode() == ISD::BITCAST &&
8180 N0.getNode()->hasOneUse()) {
8181 SDValue Int = N0.getOperand(0);
8182 EVT IntVT = Int.getValueType();
8183 if (IntVT.isInteger() && !IntVT.isVector()) {
8185 if (N0.getValueType().isVector()) {
8186 // For a vector, get a mask such as 0x7f... per scalar element
8188 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8189 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8191 // For a scalar, just generate 0x7f...
8192 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8194 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
8195 DAG.getConstant(SignMask, IntVT));
8196 AddToWorklist(Int.getNode());
8197 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8204 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8205 SDValue Chain = N->getOperand(0);
8206 SDValue N1 = N->getOperand(1);
8207 SDValue N2 = N->getOperand(2);
8209 // If N is a constant we could fold this into a fallthrough or unconditional
8210 // branch. However that doesn't happen very often in normal code, because
8211 // Instcombine/SimplifyCFG should have handled the available opportunities.
8212 // If we did this folding here, it would be necessary to update the
8213 // MachineBasicBlock CFG, which is awkward.
8215 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8217 if (N1.getOpcode() == ISD::SETCC &&
8218 TLI.isOperationLegalOrCustom(ISD::BR_CC,
8219 N1.getOperand(0).getValueType())) {
8220 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8221 Chain, N1.getOperand(2),
8222 N1.getOperand(0), N1.getOperand(1), N2);
8225 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8226 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8227 (N1.getOperand(0).hasOneUse() &&
8228 N1.getOperand(0).getOpcode() == ISD::SRL))) {
8229 SDNode *Trunc = nullptr;
8230 if (N1.getOpcode() == ISD::TRUNCATE) {
8231 // Look pass the truncate.
8232 Trunc = N1.getNode();
8233 N1 = N1.getOperand(0);
8236 // Match this pattern so that we can generate simpler code:
8239 // %b = and i32 %a, 2
8240 // %c = srl i32 %b, 1
8241 // brcond i32 %c ...
8246 // %b = and i32 %a, 2
8247 // %c = setcc eq %b, 0
8250 // This applies only when the AND constant value has one bit set and the
8251 // SRL constant is equal to the log2 of the AND constant. The back-end is
8252 // smart enough to convert the result into a TEST/JMP sequence.
8253 SDValue Op0 = N1.getOperand(0);
8254 SDValue Op1 = N1.getOperand(1);
8256 if (Op0.getOpcode() == ISD::AND &&
8257 Op1.getOpcode() == ISD::Constant) {
8258 SDValue AndOp1 = Op0.getOperand(1);
8260 if (AndOp1.getOpcode() == ISD::Constant) {
8261 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8263 if (AndConst.isPowerOf2() &&
8264 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8266 DAG.getSetCC(SDLoc(N),
8267 getSetCCResultType(Op0.getValueType()),
8268 Op0, DAG.getConstant(0, Op0.getValueType()),
8271 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
8272 MVT::Other, Chain, SetCC, N2);
8273 // Don't add the new BRCond into the worklist or else SimplifySelectCC
8274 // will convert it back to (X & C1) >> C2.
8275 CombineTo(N, NewBRCond, false);
8276 // Truncate is dead.
8278 deleteAndRecombine(Trunc);
8279 // Replace the uses of SRL with SETCC
8280 WorklistRemover DeadNodes(*this);
8281 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8282 deleteAndRecombine(N1.getNode());
8283 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8289 // Restore N1 if the above transformation doesn't match.
8290 N1 = N->getOperand(1);
8293 // Transform br(xor(x, y)) -> br(x != y)
8294 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8295 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8296 SDNode *TheXor = N1.getNode();
8297 SDValue Op0 = TheXor->getOperand(0);
8298 SDValue Op1 = TheXor->getOperand(1);
8299 if (Op0.getOpcode() == Op1.getOpcode()) {
8300 // Avoid missing important xor optimizations.
8301 SDValue Tmp = visitXOR(TheXor);
8302 if (Tmp.getNode()) {
8303 if (Tmp.getNode() != TheXor) {
8304 DEBUG(dbgs() << "\nReplacing.8 ";
8306 dbgs() << "\nWith: ";
8307 Tmp.getNode()->dump(&DAG);
8309 WorklistRemover DeadNodes(*this);
8310 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8311 deleteAndRecombine(TheXor);
8312 return DAG.getNode(ISD::BRCOND, SDLoc(N),
8313 MVT::Other, Chain, Tmp, N2);
8316 // visitXOR has changed XOR's operands or replaced the XOR completely,
8318 return SDValue(N, 0);
8322 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8324 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8325 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8326 Op0.getOpcode() == ISD::XOR) {
8327 TheXor = Op0.getNode();
8331 EVT SetCCVT = N1.getValueType();
8333 SetCCVT = getSetCCResultType(SetCCVT);
8334 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8337 Equal ? ISD::SETEQ : ISD::SETNE);
8338 // Replace the uses of XOR with SETCC
8339 WorklistRemover DeadNodes(*this);
8340 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8341 deleteAndRecombine(N1.getNode());
8342 return DAG.getNode(ISD::BRCOND, SDLoc(N),
8343 MVT::Other, Chain, SetCC, N2);
8350 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8352 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
8353 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
8354 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
8356 // If N is a constant we could fold this into a fallthrough or unconditional
8357 // branch. However that doesn't happen very often in normal code, because
8358 // Instcombine/SimplifyCFG should have handled the available opportunities.
8359 // If we did this folding here, it would be necessary to update the
8360 // MachineBasicBlock CFG, which is awkward.
8362 // Use SimplifySetCC to simplify SETCC's.
8363 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
8364 CondLHS, CondRHS, CC->get(), SDLoc(N),
8366 if (Simp.getNode()) AddToWorklist(Simp.getNode());
8368 // fold to a simpler setcc
8369 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
8370 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8371 N->getOperand(0), Simp.getOperand(2),
8372 Simp.getOperand(0), Simp.getOperand(1),
8378 /// Return true if 'Use' is a load or a store that uses N as its base pointer
8379 /// and that N may be folded in the load / store addressing mode.
8380 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8382 const TargetLowering &TLI) {
8384 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
8385 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8387 VT = Use->getValueType(0);
8388 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
8389 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8391 VT = ST->getValue().getValueType();
8395 TargetLowering::AddrMode AM;
8396 if (N->getOpcode() == ISD::ADD) {
8397 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8400 AM.BaseOffs = Offset->getSExtValue();
8404 } else if (N->getOpcode() == ISD::SUB) {
8405 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8408 AM.BaseOffs = -Offset->getSExtValue();
8415 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8418 /// Try turning a load/store into a pre-indexed load/store when the base
8419 /// pointer is an add or subtract and it has other uses besides the load/store.
8420 /// After the transformation, the new indexed load/store has effectively folded
8421 /// the add/subtract in and all of its other uses are redirected to the
8423 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8424 if (Level < AfterLegalizeDAG)
8430 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8431 if (LD->isIndexed())
8433 VT = LD->getMemoryVT();
8434 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8435 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8437 Ptr = LD->getBasePtr();
8438 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8439 if (ST->isIndexed())
8441 VT = ST->getMemoryVT();
8442 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8443 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8445 Ptr = ST->getBasePtr();
8451 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8452 // out. There is no reason to make this a preinc/predec.
8453 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
8454 Ptr.getNode()->hasOneUse())
8457 // Ask the target to do addressing mode selection.
8460 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8461 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8464 // Backends without true r+i pre-indexed forms may need to pass a
8465 // constant base with a variable offset so that constant coercion
8466 // will work with the patterns in canonical form.
8467 bool Swapped = false;
8468 if (isa<ConstantSDNode>(BasePtr)) {
8469 std::swap(BasePtr, Offset);
8473 // Don't create a indexed load / store with zero offset.
8474 if (isa<ConstantSDNode>(Offset) &&
8475 cast<ConstantSDNode>(Offset)->isNullValue())
8478 // Try turning it into a pre-indexed load / store except when:
8479 // 1) The new base ptr is a frame index.
8480 // 2) If N is a store and the new base ptr is either the same as or is a
8481 // predecessor of the value being stored.
8482 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
8483 // that would create a cycle.
8484 // 4) All uses are load / store ops that use it as old base ptr.
8486 // Check #1. Preinc'ing a frame index would require copying the stack pointer
8487 // (plus the implicit offset) to a register to preinc anyway.
8488 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8493 SDValue Val = cast<StoreSDNode>(N)->getValue();
8494 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
8498 // If the offset is a constant, there may be other adds of constants that
8499 // can be folded with this one. We should do this to avoid having to keep
8500 // a copy of the original base pointer.
8501 SmallVector<SDNode *, 16> OtherUses;
8502 if (isa<ConstantSDNode>(Offset))
8503 for (SDNode *Use : BasePtr.getNode()->uses()) {
8504 if (Use == Ptr.getNode())
8507 if (Use->isPredecessorOf(N))
8510 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8515 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8516 if (Op1.getNode() == BasePtr.getNode())
8517 std::swap(Op0, Op1);
8518 assert(Op0.getNode() == BasePtr.getNode() &&
8519 "Use of ADD/SUB but not an operand");
8521 if (!isa<ConstantSDNode>(Op1)) {
8526 // FIXME: In some cases, we can be smarter about this.
8527 if (Op1.getValueType() != Offset.getValueType()) {
8532 OtherUses.push_back(Use);
8536 std::swap(BasePtr, Offset);
8538 // Now check for #3 and #4.
8539 bool RealUse = false;
8541 // Caches for hasPredecessorHelper
8542 SmallPtrSet<const SDNode *, 32> Visited;
8543 SmallVector<const SDNode *, 16> Worklist;
8545 for (SDNode *Use : Ptr.getNode()->uses()) {
8548 if (N->hasPredecessorHelper(Use, Visited, Worklist))
8551 // If Ptr may be folded in addressing mode of other use, then it's
8552 // not profitable to do this transformation.
8553 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
8562 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8563 BasePtr, Offset, AM);
8565 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8566 BasePtr, Offset, AM);
8569 DEBUG(dbgs() << "\nReplacing.4 ";
8571 dbgs() << "\nWith: ";
8572 Result.getNode()->dump(&DAG);
8574 WorklistRemover DeadNodes(*this);
8576 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8577 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8579 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8582 // Finally, since the node is now dead, remove it from the graph.
8583 deleteAndRecombine(N);
8586 std::swap(BasePtr, Offset);
8588 // Replace other uses of BasePtr that can be updated to use Ptr
8589 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8590 unsigned OffsetIdx = 1;
8591 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8593 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8594 BasePtr.getNode() && "Expected BasePtr operand");
8596 // We need to replace ptr0 in the following expression:
8597 // x0 * offset0 + y0 * ptr0 = t0
8599 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
8601 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8602 // indexed load/store and the expresion that needs to be re-written.
8604 // Therefore, we have:
8605 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
8607 ConstantSDNode *CN =
8608 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
8610 APInt Offset0 = CN->getAPIntValue();
8611 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8613 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8614 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8615 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8616 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8618 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8620 APInt CNV = Offset0;
8621 if (X0 < 0) CNV = -CNV;
8622 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8623 else CNV = CNV - Offset1;
8625 // We can now generate the new expression.
8626 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8627 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8629 SDValue NewUse = DAG.getNode(Opcode,
8630 SDLoc(OtherUses[i]),
8631 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8632 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8633 deleteAndRecombine(OtherUses[i]);
8636 // Replace the uses of Ptr with uses of the updated base value.
8637 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8638 deleteAndRecombine(Ptr.getNode());
8643 /// Try to combine a load/store with a add/sub of the base pointer node into a
8644 /// post-indexed load/store. The transformation folded the add/subtract into the
8645 /// new indexed load/store effectively and all of its uses are redirected to the
8647 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
8648 if (Level < AfterLegalizeDAG)
8654 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8655 if (LD->isIndexed())
8657 VT = LD->getMemoryVT();
8658 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8659 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8661 Ptr = LD->getBasePtr();
8662 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8663 if (ST->isIndexed())
8665 VT = ST->getMemoryVT();
8666 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8667 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8669 Ptr = ST->getBasePtr();
8675 if (Ptr.getNode()->hasOneUse())
8678 for (SDNode *Op : Ptr.getNode()->uses()) {
8680 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8685 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8686 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8687 // Don't create a indexed load / store with zero offset.
8688 if (isa<ConstantSDNode>(Offset) &&
8689 cast<ConstantSDNode>(Offset)->isNullValue())
8692 // Try turning it into a post-indexed load / store except when
8693 // 1) All uses are load / store ops that use it as base ptr (and
8694 // it may be folded as addressing mmode).
8695 // 2) Op must be independent of N, i.e. Op is neither a predecessor
8696 // nor a successor of N. Otherwise, if Op is folded that would
8699 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8703 bool TryNext = false;
8704 for (SDNode *Use : BasePtr.getNode()->uses()) {
8705 if (Use == Ptr.getNode())
8708 // If all the uses are load / store addresses, then don't do the
8710 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8711 bool RealUse = false;
8712 for (SDNode *UseUse : Use->uses()) {
8713 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8728 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8729 SDValue Result = isLoad
8730 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8731 BasePtr, Offset, AM)
8732 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8733 BasePtr, Offset, AM);
8736 DEBUG(dbgs() << "\nReplacing.5 ";
8738 dbgs() << "\nWith: ";
8739 Result.getNode()->dump(&DAG);
8741 WorklistRemover DeadNodes(*this);
8743 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8744 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8746 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8749 // Finally, since the node is now dead, remove it from the graph.
8750 deleteAndRecombine(N);
8752 // Replace the uses of Use with uses of the updated base value.
8753 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8754 Result.getValue(isLoad ? 1 : 0));
8755 deleteAndRecombine(Op);
8764 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8765 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8766 ISD::MemIndexedMode AM = LD->getAddressingMode();
8767 assert(AM != ISD::UNINDEXED);
8768 SDValue BP = LD->getOperand(1);
8769 SDValue Inc = LD->getOperand(2);
8771 // Some backends use TargetConstants for load offsets, but don't expect
8772 // TargetConstants in general ADD nodes. We can convert these constants into
8773 // regular Constants (if the constant is not opaque).
8774 assert((Inc.getOpcode() != ISD::TargetConstant ||
8775 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8776 "Cannot split out indexing using opaque target constants");
8777 if (Inc.getOpcode() == ISD::TargetConstant) {
8778 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8779 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8780 ConstInc->getValueType(0));
8784 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8785 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8788 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8789 LoadSDNode *LD = cast<LoadSDNode>(N);
8790 SDValue Chain = LD->getChain();
8791 SDValue Ptr = LD->getBasePtr();
8793 // If load is not volatile and there are no uses of the loaded value (and
8794 // the updated indexed value in case of indexed loads), change uses of the
8795 // chain value into uses of the chain input (i.e. delete the dead load).
8796 if (!LD->isVolatile()) {
8797 if (N->getValueType(1) == MVT::Other) {
8799 if (!N->hasAnyUseOfValue(0)) {
8800 // It's not safe to use the two value CombineTo variant here. e.g.
8801 // v1, chain2 = load chain1, loc
8802 // v2, chain3 = load chain2, loc
8804 // Now we replace use of chain2 with chain1. This makes the second load
8805 // isomorphic to the one we are deleting, and thus makes this load live.
8806 DEBUG(dbgs() << "\nReplacing.6 ";
8808 dbgs() << "\nWith chain: ";
8809 Chain.getNode()->dump(&DAG);
8811 WorklistRemover DeadNodes(*this);
8812 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8815 deleteAndRecombine(N);
8817 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8821 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8823 // If this load has an opaque TargetConstant offset, then we cannot split
8824 // the indexing into an add/sub directly (that TargetConstant may not be
8825 // valid for a different type of node, and we cannot convert an opaque
8826 // target constant into a regular constant).
8827 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8828 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8830 if (!N->hasAnyUseOfValue(0) &&
8831 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8832 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8834 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8835 Index = SplitIndexingFromLoad(LD);
8836 // Try to fold the base pointer arithmetic into subsequent loads and
8838 AddUsersToWorklist(N);
8840 Index = DAG.getUNDEF(N->getValueType(1));
8841 DEBUG(dbgs() << "\nReplacing.7 ";
8843 dbgs() << "\nWith: ";
8844 Undef.getNode()->dump(&DAG);
8845 dbgs() << " and 2 other values\n");
8846 WorklistRemover DeadNodes(*this);
8847 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8848 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8849 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8850 deleteAndRecombine(N);
8851 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8856 // If this load is directly stored, replace the load value with the stored
8858 // TODO: Handle store large -> read small portion.
8859 // TODO: Handle TRUNCSTORE/LOADEXT
8860 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8861 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8862 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8863 if (PrevST->getBasePtr() == Ptr &&
8864 PrevST->getValue().getValueType() == N->getValueType(0))
8865 return CombineTo(N, Chain.getOperand(1), Chain);
8869 // Try to infer better alignment information than the load already has.
8870 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8871 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8872 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8874 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8875 LD->getValueType(0),
8876 Chain, Ptr, LD->getPointerInfo(),
8878 LD->isVolatile(), LD->isNonTemporal(),
8879 LD->isInvariant(), Align, LD->getAAInfo());
8880 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8885 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
8886 : DAG.getSubtarget().useAA();
8888 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8889 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8892 if (UseAA && LD->isUnindexed()) {
8893 // Walk up chain skipping non-aliasing memory nodes.
8894 SDValue BetterChain = FindBetterChain(N, Chain);
8896 // If there is a better chain.
8897 if (Chain != BetterChain) {
8900 // Replace the chain to void dependency.
8901 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8902 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8903 BetterChain, Ptr, LD->getMemOperand());
8905 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8906 LD->getValueType(0),
8907 BetterChain, Ptr, LD->getMemoryVT(),
8908 LD->getMemOperand());
8911 // Create token factor to keep old chain connected.
8912 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8913 MVT::Other, Chain, ReplLoad.getValue(1));
8915 // Make sure the new and old chains are cleaned up.
8916 AddToWorklist(Token.getNode());
8918 // Replace uses with load result and token factor. Don't add users
8920 return CombineTo(N, ReplLoad.getValue(0), Token, false);
8924 // Try transforming N to an indexed load.
8925 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8926 return SDValue(N, 0);
8928 // Try to slice up N to more direct loads if the slices are mapped to
8929 // different register banks or pairing can take place.
8931 return SDValue(N, 0);
8937 /// \brief Helper structure used to slice a load in smaller loads.
8938 /// Basically a slice is obtained from the following sequence:
8939 /// Origin = load Ty1, Base
8940 /// Shift = srl Ty1 Origin, CstTy Amount
8941 /// Inst = trunc Shift to Ty2
8943 /// Then, it will be rewriten into:
8944 /// Slice = load SliceTy, Base + SliceOffset
8945 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8947 /// SliceTy is deduced from the number of bits that are actually used to
8949 struct LoadedSlice {
8950 /// \brief Helper structure used to compute the cost of a slice.
8952 /// Are we optimizing for code size.
8957 unsigned CrossRegisterBanksCopies;
8961 Cost(bool ForCodeSize = false)
8962 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8963 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8965 /// \brief Get the cost of one isolated slice.
8966 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8967 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8968 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8969 EVT TruncType = LS.Inst->getValueType(0);
8970 EVT LoadedType = LS.getLoadedType();
8971 if (TruncType != LoadedType &&
8972 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8976 /// \brief Account for slicing gain in the current cost.
8977 /// Slicing provide a few gains like removing a shift or a
8978 /// truncate. This method allows to grow the cost of the original
8979 /// load with the gain from this slice.
8980 void addSliceGain(const LoadedSlice &LS) {
8981 // Each slice saves a truncate.
8982 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8983 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8984 LS.Inst->getOperand(0).getValueType()))
8986 // If there is a shift amount, this slice gets rid of it.
8989 // If this slice can merge a cross register bank copy, account for it.
8990 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8991 ++CrossRegisterBanksCopies;
8994 Cost &operator+=(const Cost &RHS) {
8996 Truncates += RHS.Truncates;
8997 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9003 bool operator==(const Cost &RHS) const {
9004 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9005 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9006 ZExts == RHS.ZExts && Shift == RHS.Shift;
9009 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9011 bool operator<(const Cost &RHS) const {
9012 // Assume cross register banks copies are as expensive as loads.
9013 // FIXME: Do we want some more target hooks?
9014 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9015 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9016 // Unless we are optimizing for code size, consider the
9017 // expensive operation first.
9018 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9019 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9020 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9021 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9024 bool operator>(const Cost &RHS) const { return RHS < *this; }
9026 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9028 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9030 // The last instruction that represent the slice. This should be a
9031 // truncate instruction.
9033 // The original load instruction.
9035 // The right shift amount in bits from the original load.
9037 // The DAG from which Origin came from.
9038 // This is used to get some contextual information about legal types, etc.
9041 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9042 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9043 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9045 LoadedSlice(const LoadedSlice &LS)
9046 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
9048 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9049 /// \return Result is \p BitWidth and has used bits set to 1 and
9050 /// not used bits set to 0.
9051 APInt getUsedBits() const {
9052 // Reproduce the trunc(lshr) sequence:
9053 // - Start from the truncated value.
9054 // - Zero extend to the desired bit width.
9056 assert(Origin && "No original load to compare against.");
9057 unsigned BitWidth = Origin->getValueSizeInBits(0);
9058 assert(Inst && "This slice is not bound to an instruction");
9059 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9060 "Extracted slice is bigger than the whole type!");
9061 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9062 UsedBits.setAllBits();
9063 UsedBits = UsedBits.zext(BitWidth);
9068 /// \brief Get the size of the slice to be loaded in bytes.
9069 unsigned getLoadedSize() const {
9070 unsigned SliceSize = getUsedBits().countPopulation();
9071 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9072 return SliceSize / 8;
9075 /// \brief Get the type that will be loaded for this slice.
9076 /// Note: This may not be the final type for the slice.
9077 EVT getLoadedType() const {
9078 assert(DAG && "Missing context");
9079 LLVMContext &Ctxt = *DAG->getContext();
9080 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9083 /// \brief Get the alignment of the load used for this slice.
9084 unsigned getAlignment() const {
9085 unsigned Alignment = Origin->getAlignment();
9086 unsigned Offset = getOffsetFromBase();
9088 Alignment = MinAlign(Alignment, Alignment + Offset);
9092 /// \brief Check if this slice can be rewritten with legal operations.
9093 bool isLegal() const {
9094 // An invalid slice is not legal.
9095 if (!Origin || !Inst || !DAG)
9098 // Offsets are for indexed load only, we do not handle that.
9099 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9102 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9104 // Check that the type is legal.
9105 EVT SliceType = getLoadedType();
9106 if (!TLI.isTypeLegal(SliceType))
9109 // Check that the load is legal for this type.
9110 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9113 // Check that the offset can be computed.
9114 // 1. Check its type.
9115 EVT PtrType = Origin->getBasePtr().getValueType();
9116 if (PtrType == MVT::Untyped || PtrType.isExtended())
9119 // 2. Check that it fits in the immediate.
9120 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9123 // 3. Check that the computation is legal.
9124 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9127 // Check that the zext is legal if it needs one.
9128 EVT TruncateType = Inst->getValueType(0);
9129 if (TruncateType != SliceType &&
9130 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9136 /// \brief Get the offset in bytes of this slice in the original chunk of
9138 /// \pre DAG != nullptr.
9139 uint64_t getOffsetFromBase() const {
9140 assert(DAG && "Missing context.");
9142 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9143 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9144 uint64_t Offset = Shift / 8;
9145 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9146 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9147 "The size of the original loaded type is not a multiple of a"
9149 // If Offset is bigger than TySizeInBytes, it means we are loading all
9150 // zeros. This should have been optimized before in the process.
9151 assert(TySizeInBytes > Offset &&
9152 "Invalid shift amount for given loaded size");
9154 Offset = TySizeInBytes - Offset - getLoadedSize();
9158 /// \brief Generate the sequence of instructions to load the slice
9159 /// represented by this object and redirect the uses of this slice to
9160 /// this new sequence of instructions.
9161 /// \pre this->Inst && this->Origin are valid Instructions and this
9162 /// object passed the legal check: LoadedSlice::isLegal returned true.
9163 /// \return The last instruction of the sequence used to load the slice.
9164 SDValue loadSlice() const {
9165 assert(Inst && Origin && "Unable to replace a non-existing slice.");
9166 const SDValue &OldBaseAddr = Origin->getBasePtr();
9167 SDValue BaseAddr = OldBaseAddr;
9168 // Get the offset in that chunk of bytes w.r.t. the endianess.
9169 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9170 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9172 // BaseAddr = BaseAddr + Offset.
9173 EVT ArithType = BaseAddr.getValueType();
9174 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
9175 DAG->getConstant(Offset, ArithType));
9178 // Create the type of the loaded slice according to its size.
9179 EVT SliceType = getLoadedType();
9181 // Create the load for the slice.
9182 SDValue LastInst = DAG->getLoad(
9183 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9184 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9185 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9186 // If the final type is not the same as the loaded type, this means that
9187 // we have to pad with zero. Create a zero extend for that.
9188 EVT FinalType = Inst->getValueType(0);
9189 if (SliceType != FinalType)
9191 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9195 /// \brief Check if this slice can be merged with an expensive cross register
9196 /// bank copy. E.g.,
9198 /// f = bitcast i32 i to float
9199 bool canMergeExpensiveCrossRegisterBankCopy() const {
9200 if (!Inst || !Inst->hasOneUse())
9202 SDNode *Use = *Inst->use_begin();
9203 if (Use->getOpcode() != ISD::BITCAST)
9205 assert(DAG && "Missing context");
9206 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9207 EVT ResVT = Use->getValueType(0);
9208 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9209 const TargetRegisterClass *ArgRC =
9210 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9211 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9214 // At this point, we know that we perform a cross-register-bank copy.
9215 // Check if it is expensive.
9216 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9217 // Assume bitcasts are cheap, unless both register classes do not
9218 // explicitly share a common sub class.
9219 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9222 // Check if it will be merged with the load.
9223 // 1. Check the alignment constraint.
9224 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9225 ResVT.getTypeForEVT(*DAG->getContext()));
9227 if (RequiredAlignment > getAlignment())
9230 // 2. Check that the load is a legal operation for that type.
9231 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9234 // 3. Check that we do not have a zext in the way.
9235 if (Inst->getValueType(0) != getLoadedType())
9243 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9244 /// \p UsedBits looks like 0..0 1..1 0..0.
9245 static bool areUsedBitsDense(const APInt &UsedBits) {
9246 // If all the bits are one, this is dense!
9247 if (UsedBits.isAllOnesValue())
9250 // Get rid of the unused bits on the right.
9251 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9252 // Get rid of the unused bits on the left.
9253 if (NarrowedUsedBits.countLeadingZeros())
9254 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9255 // Check that the chunk of bits is completely used.
9256 return NarrowedUsedBits.isAllOnesValue();
9259 /// \brief Check whether or not \p First and \p Second are next to each other
9260 /// in memory. This means that there is no hole between the bits loaded
9261 /// by \p First and the bits loaded by \p Second.
9262 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9263 const LoadedSlice &Second) {
9264 assert(First.Origin == Second.Origin && First.Origin &&
9265 "Unable to match different memory origins.");
9266 APInt UsedBits = First.getUsedBits();
9267 assert((UsedBits & Second.getUsedBits()) == 0 &&
9268 "Slices are not supposed to overlap.");
9269 UsedBits |= Second.getUsedBits();
9270 return areUsedBitsDense(UsedBits);
9273 /// \brief Adjust the \p GlobalLSCost according to the target
9274 /// paring capabilities and the layout of the slices.
9275 /// \pre \p GlobalLSCost should account for at least as many loads as
9276 /// there is in the slices in \p LoadedSlices.
9277 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9278 LoadedSlice::Cost &GlobalLSCost) {
9279 unsigned NumberOfSlices = LoadedSlices.size();
9280 // If there is less than 2 elements, no pairing is possible.
9281 if (NumberOfSlices < 2)
9284 // Sort the slices so that elements that are likely to be next to each
9285 // other in memory are next to each other in the list.
9286 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9287 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9288 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9289 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9291 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9292 // First (resp. Second) is the first (resp. Second) potentially candidate
9293 // to be placed in a paired load.
9294 const LoadedSlice *First = nullptr;
9295 const LoadedSlice *Second = nullptr;
9296 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9297 // Set the beginning of the pair.
9300 Second = &LoadedSlices[CurrSlice];
9302 // If First is NULL, it means we start a new pair.
9303 // Get to the next slice.
9307 EVT LoadedType = First->getLoadedType();
9309 // If the types of the slices are different, we cannot pair them.
9310 if (LoadedType != Second->getLoadedType())
9313 // Check if the target supplies paired loads for this type.
9314 unsigned RequiredAlignment = 0;
9315 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9316 // move to the next pair, this type is hopeless.
9320 // Check if we meet the alignment requirement.
9321 if (RequiredAlignment > First->getAlignment())
9324 // Check that both loads are next to each other in memory.
9325 if (!areSlicesNextToEachOther(*First, *Second))
9328 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9329 --GlobalLSCost.Loads;
9330 // Move to the next pair.
9335 /// \brief Check the profitability of all involved LoadedSlice.
9336 /// Currently, it is considered profitable if there is exactly two
9337 /// involved slices (1) which are (2) next to each other in memory, and
9338 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9340 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9341 /// the elements themselves.
9343 /// FIXME: When the cost model will be mature enough, we can relax
9344 /// constraints (1) and (2).
9345 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9346 const APInt &UsedBits, bool ForCodeSize) {
9347 unsigned NumberOfSlices = LoadedSlices.size();
9348 if (StressLoadSlicing)
9349 return NumberOfSlices > 1;
9352 if (NumberOfSlices != 2)
9356 if (!areUsedBitsDense(UsedBits))
9360 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9361 // The original code has one big load.
9363 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9364 const LoadedSlice &LS = LoadedSlices[CurrSlice];
9365 // Accumulate the cost of all the slices.
9366 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9367 GlobalSlicingCost += SliceCost;
9369 // Account as cost in the original configuration the gain obtained
9370 // with the current slices.
9371 OrigCost.addSliceGain(LS);
9374 // If the target supports paired load, adjust the cost accordingly.
9375 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9376 return OrigCost > GlobalSlicingCost;
9379 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9380 /// operations, split it in the various pieces being extracted.
9382 /// This sort of thing is introduced by SROA.
9383 /// This slicing takes care not to insert overlapping loads.
9384 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
9385 bool DAGCombiner::SliceUpLoad(SDNode *N) {
9386 if (Level < AfterLegalizeDAG)
9389 LoadSDNode *LD = cast<LoadSDNode>(N);
9390 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9391 !LD->getValueType(0).isInteger())
9394 // Keep track of already used bits to detect overlapping values.
9395 // In that case, we will just abort the transformation.
9396 APInt UsedBits(LD->getValueSizeInBits(0), 0);
9398 SmallVector<LoadedSlice, 4> LoadedSlices;
9400 // Check if this load is used as several smaller chunks of bits.
9401 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9402 // of computation for each trunc.
9403 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9404 UI != UIEnd; ++UI) {
9405 // Skip the uses of the chain.
9406 if (UI.getUse().getResNo() != 0)
9412 // Check if this is a trunc(lshr).
9413 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9414 isa<ConstantSDNode>(User->getOperand(1))) {
9415 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9416 User = *User->use_begin();
9419 // At this point, User is a Truncate, iff we encountered, trunc or
9421 if (User->getOpcode() != ISD::TRUNCATE)
9424 // The width of the type must be a power of 2 and greater than 8-bits.
9425 // Otherwise the load cannot be represented in LLVM IR.
9426 // Moreover, if we shifted with a non-8-bits multiple, the slice
9427 // will be across several bytes. We do not support that.
9428 unsigned Width = User->getValueSizeInBits(0);
9429 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9432 // Build the slice for this chain of computations.
9433 LoadedSlice LS(User, LD, Shift, &DAG);
9434 APInt CurrentUsedBits = LS.getUsedBits();
9436 // Check if this slice overlaps with another.
9437 if ((CurrentUsedBits & UsedBits) != 0)
9439 // Update the bits used globally.
9440 UsedBits |= CurrentUsedBits;
9442 // Check if the new slice would be legal.
9446 // Record the slice.
9447 LoadedSlices.push_back(LS);
9450 // Abort slicing if it does not seem to be profitable.
9451 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9456 // Rewrite each chain to use an independent load.
9457 // By construction, each chain can be represented by a unique load.
9459 // Prepare the argument for the new token factor for all the slices.
9460 SmallVector<SDValue, 8> ArgChains;
9461 for (SmallVectorImpl<LoadedSlice>::const_iterator
9462 LSIt = LoadedSlices.begin(),
9463 LSItEnd = LoadedSlices.end();
9464 LSIt != LSItEnd; ++LSIt) {
9465 SDValue SliceInst = LSIt->loadSlice();
9466 CombineTo(LSIt->Inst, SliceInst, true);
9467 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9468 SliceInst = SliceInst.getOperand(0);
9469 assert(SliceInst->getOpcode() == ISD::LOAD &&
9470 "It takes more than a zext to get to the loaded slice!!");
9471 ArgChains.push_back(SliceInst.getValue(1));
9474 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
9476 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9480 /// Check to see if V is (and load (ptr), imm), where the load is having
9481 /// specific bytes cleared out. If so, return the byte size being masked out
9482 /// and the shift amount.
9483 static std::pair<unsigned, unsigned>
9484 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9485 std::pair<unsigned, unsigned> Result(0, 0);
9487 // Check for the structure we're looking for.
9488 if (V->getOpcode() != ISD::AND ||
9489 !isa<ConstantSDNode>(V->getOperand(1)) ||
9490 !ISD::isNormalLoad(V->getOperand(0).getNode()))
9493 // Check the chain and pointer.
9494 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
9495 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
9497 // The store should be chained directly to the load or be an operand of a
9499 if (LD == Chain.getNode())
9501 else if (Chain->getOpcode() != ISD::TokenFactor)
9502 return Result; // Fail.
9505 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9506 if (Chain->getOperand(i).getNode() == LD) {
9510 if (!isOk) return Result;
9513 // This only handles simple types.
9514 if (V.getValueType() != MVT::i16 &&
9515 V.getValueType() != MVT::i32 &&
9516 V.getValueType() != MVT::i64)
9519 // Check the constant mask. Invert it so that the bits being masked out are
9520 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
9521 // follow the sign bit for uniformity.
9522 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
9523 unsigned NotMaskLZ = countLeadingZeros(NotMask);
9524 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
9525 unsigned NotMaskTZ = countTrailingZeros(NotMask);
9526 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
9527 if (NotMaskLZ == 64) return Result; // All zero mask.
9529 // See if we have a continuous run of bits. If so, we have 0*1+0*
9530 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
9533 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9534 if (V.getValueType() != MVT::i64 && NotMaskLZ)
9535 NotMaskLZ -= 64-V.getValueSizeInBits();
9537 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9538 switch (MaskedBytes) {
9542 default: return Result; // All one mask, or 5-byte mask.
9545 // Verify that the first bit starts at a multiple of mask so that the access
9546 // is aligned the same as the access width.
9547 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
9549 Result.first = MaskedBytes;
9550 Result.second = NotMaskTZ/8;
9555 /// Check to see if IVal is something that provides a value as specified by
9556 /// MaskInfo. If so, replace the specified store with a narrower store of
9559 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9560 SDValue IVal, StoreSDNode *St,
9562 unsigned NumBytes = MaskInfo.first;
9563 unsigned ByteShift = MaskInfo.second;
9564 SelectionDAG &DAG = DC->getDAG();
9566 // Check to see if IVal is all zeros in the part being masked in by the 'or'
9567 // that uses this. If not, this is not a replacement.
9568 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9569 ByteShift*8, (ByteShift+NumBytes)*8);
9570 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
9572 // Check that it is legal on the target to do this. It is legal if the new
9573 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9575 MVT VT = MVT::getIntegerVT(NumBytes*8);
9576 if (!DC->isTypeLegal(VT))
9579 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
9580 // shifted by ByteShift and truncated down to NumBytes.
9582 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
9583 DAG.getConstant(ByteShift*8,
9584 DC->getShiftAmountTy(IVal.getValueType())));
9586 // Figure out the offset for the store and the alignment of the access.
9588 unsigned NewAlign = St->getAlignment();
9590 if (DAG.getTargetLoweringInfo().isLittleEndian())
9591 StOffset = ByteShift;
9593 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
9595 SDValue Ptr = St->getBasePtr();
9597 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
9598 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9599 NewAlign = MinAlign(NewAlign, StOffset);
9602 // Truncate down to the new size.
9603 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
9606 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
9607 St->getPointerInfo().getWithOffset(StOffset),
9608 false, false, NewAlign).getNode();
9612 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9613 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9614 /// narrowing the load and store if it would end up being a win for performance
9616 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9617 StoreSDNode *ST = cast<StoreSDNode>(N);
9618 if (ST->isVolatile())
9621 SDValue Chain = ST->getChain();
9622 SDValue Value = ST->getValue();
9623 SDValue Ptr = ST->getBasePtr();
9624 EVT VT = Value.getValueType();
9626 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9629 unsigned Opc = Value.getOpcode();
9631 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9632 // is a byte mask indicating a consecutive number of bytes, check to see if
9633 // Y is known to provide just those bytes. If so, we try to replace the
9634 // load + replace + store sequence with a single (narrower) store, which makes
9636 if (Opc == ISD::OR) {
9637 std::pair<unsigned, unsigned> MaskedLoad;
9638 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9639 if (MaskedLoad.first)
9640 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9641 Value.getOperand(1), ST,this))
9642 return SDValue(NewST, 0);
9644 // Or is commutative, so try swapping X and Y.
9645 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9646 if (MaskedLoad.first)
9647 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9648 Value.getOperand(0), ST,this))
9649 return SDValue(NewST, 0);
9652 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9653 Value.getOperand(1).getOpcode() != ISD::Constant)
9656 SDValue N0 = Value.getOperand(0);
9657 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9658 Chain == SDValue(N0.getNode(), 1)) {
9659 LoadSDNode *LD = cast<LoadSDNode>(N0);
9660 if (LD->getBasePtr() != Ptr ||
9661 LD->getPointerInfo().getAddrSpace() !=
9662 ST->getPointerInfo().getAddrSpace())
9665 // Find the type to narrow it the load / op / store to.
9666 SDValue N1 = Value.getOperand(1);
9667 unsigned BitWidth = N1.getValueSizeInBits();
9668 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9669 if (Opc == ISD::AND)
9670 Imm ^= APInt::getAllOnesValue(BitWidth);
9671 if (Imm == 0 || Imm.isAllOnesValue())
9673 unsigned ShAmt = Imm.countTrailingZeros();
9674 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9675 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9676 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9677 // The narrowing should be profitable, the load/store operation should be
9678 // legal (or custom) and the store size should be equal to the NewVT width.
9679 while (NewBW < BitWidth &&
9680 (NewVT.getStoreSizeInBits() != NewBW ||
9681 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
9682 !TLI.isNarrowingProfitable(VT, NewVT))) {
9683 NewBW = NextPowerOf2(NewBW);
9684 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9686 if (NewBW >= BitWidth)
9689 // If the lsb changed does not start at the type bitwidth boundary,
9690 // start at the previous one.
9692 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9693 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9694 std::min(BitWidth, ShAmt + NewBW));
9695 if ((Imm & Mask) == Imm) {
9696 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9697 if (Opc == ISD::AND)
9698 NewImm ^= APInt::getAllOnesValue(NewBW);
9699 uint64_t PtrOff = ShAmt / 8;
9700 // For big endian targets, we need to adjust the offset to the pointer to
9701 // load the correct bytes.
9702 if (TLI.isBigEndian())
9703 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9705 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9706 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9707 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9710 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9711 Ptr.getValueType(), Ptr,
9712 DAG.getConstant(PtrOff, Ptr.getValueType()));
9713 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9714 LD->getChain(), NewPtr,
9715 LD->getPointerInfo().getWithOffset(PtrOff),
9716 LD->isVolatile(), LD->isNonTemporal(),
9717 LD->isInvariant(), NewAlign,
9719 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9720 DAG.getConstant(NewImm, NewVT));
9721 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9723 ST->getPointerInfo().getWithOffset(PtrOff),
9724 false, false, NewAlign);
9726 AddToWorklist(NewPtr.getNode());
9727 AddToWorklist(NewLD.getNode());
9728 AddToWorklist(NewVal.getNode());
9729 WorklistRemover DeadNodes(*this);
9730 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9739 /// For a given floating point load / store pair, if the load value isn't used
9740 /// by any other operations, then consider transforming the pair to integer
9741 /// load / store operations if the target deems the transformation profitable.
9742 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9743 StoreSDNode *ST = cast<StoreSDNode>(N);
9744 SDValue Chain = ST->getChain();
9745 SDValue Value = ST->getValue();
9746 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9747 Value.hasOneUse() &&
9748 Chain == SDValue(Value.getNode(), 1)) {
9749 LoadSDNode *LD = cast<LoadSDNode>(Value);
9750 EVT VT = LD->getMemoryVT();
9751 if (!VT.isFloatingPoint() ||
9752 VT != ST->getMemoryVT() ||
9753 LD->isNonTemporal() ||
9754 ST->isNonTemporal() ||
9755 LD->getPointerInfo().getAddrSpace() != 0 ||
9756 ST->getPointerInfo().getAddrSpace() != 0)
9759 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9760 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9761 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9762 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9763 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9766 unsigned LDAlign = LD->getAlignment();
9767 unsigned STAlign = ST->getAlignment();
9768 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9769 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9770 if (LDAlign < ABIAlign || STAlign < ABIAlign)
9773 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9774 LD->getChain(), LD->getBasePtr(),
9775 LD->getPointerInfo(),
9776 false, false, false, LDAlign);
9778 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9779 NewLD, ST->getBasePtr(),
9780 ST->getPointerInfo(),
9781 false, false, STAlign);
9783 AddToWorklist(NewLD.getNode());
9784 AddToWorklist(NewST.getNode());
9785 WorklistRemover DeadNodes(*this);
9786 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9794 /// Helper struct to parse and store a memory address as base + index + offset.
9795 /// We ignore sign extensions when it is safe to do so.
9796 /// The following two expressions are not equivalent. To differentiate we need
9797 /// to store whether there was a sign extension involved in the index
9799 /// (load (i64 add (i64 copyfromreg %c)
9800 /// (i64 signextend (add (i8 load %index)
9804 /// (load (i64 add (i64 copyfromreg %c)
9805 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
9807 struct BaseIndexOffset {
9811 bool IsIndexSignExt;
9813 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9815 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9816 bool IsIndexSignExt) :
9817 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9819 bool equalBaseIndex(const BaseIndexOffset &Other) {
9820 return Other.Base == Base && Other.Index == Index &&
9821 Other.IsIndexSignExt == IsIndexSignExt;
9824 /// Parses tree in Ptr for base, index, offset addresses.
9825 static BaseIndexOffset match(SDValue Ptr) {
9826 bool IsIndexSignExt = false;
9828 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9829 // instruction, then it could be just the BASE or everything else we don't
9830 // know how to handle. Just use Ptr as BASE and give up.
9831 if (Ptr->getOpcode() != ISD::ADD)
9832 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9834 // We know that we have at least an ADD instruction. Try to pattern match
9835 // the simple case of BASE + OFFSET.
9836 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9837 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9838 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9842 // Inside a loop the current BASE pointer is calculated using an ADD and a
9843 // MUL instruction. In this case Ptr is the actual BASE pointer.
9844 // (i64 add (i64 %array_ptr)
9845 // (i64 mul (i64 %induction_var)
9846 // (i64 %element_size)))
9847 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9848 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9850 // Look at Base + Index + Offset cases.
9851 SDValue Base = Ptr->getOperand(0);
9852 SDValue IndexOffset = Ptr->getOperand(1);
9854 // Skip signextends.
9855 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9856 IndexOffset = IndexOffset->getOperand(0);
9857 IsIndexSignExt = true;
9860 // Either the case of Base + Index (no offset) or something else.
9861 if (IndexOffset->getOpcode() != ISD::ADD)
9862 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9864 // Now we have the case of Base + Index + offset.
9865 SDValue Index = IndexOffset->getOperand(0);
9866 SDValue Offset = IndexOffset->getOperand(1);
9868 if (!isa<ConstantSDNode>(Offset))
9869 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9871 // Ignore signextends.
9872 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9873 Index = Index->getOperand(0);
9874 IsIndexSignExt = true;
9875 } else IsIndexSignExt = false;
9877 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9878 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9882 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
9883 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
9884 unsigned NumElem, bool IsConstantSrc, bool UseVector) {
9885 // Make sure we have something to merge.
9889 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
9890 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9891 unsigned EarliestNodeUsed = 0;
9893 for (unsigned i=0; i < NumElem; ++i) {
9894 // Find a chain for the new wide-store operand. Notice that some
9895 // of the store nodes that we found may not be selected for inclusion
9896 // in the wide store. The chain we use needs to be the chain of the
9897 // earliest store node which is *used* and replaced by the wide store.
9898 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9899 EarliestNodeUsed = i;
9902 // The earliest Node in the DAG.
9903 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9904 SDLoc DL(StoreNodes[0].MemNode);
9908 // Find a legal type for the vector store.
9909 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9910 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9911 if (IsConstantSrc) {
9912 // A vector store with a constant source implies that the constant is
9913 // zero; we only handle merging stores of constant zeros because the zero
9914 // can be materialized without a load.
9915 // It may be beneficial to loosen this restriction to allow non-zero
9917 StoredVal = DAG.getConstant(0, Ty);
9919 SmallVector<SDValue, 8> Ops;
9920 for (unsigned i = 0; i < NumElem ; ++i) {
9921 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9922 SDValue Val = St->getValue();
9923 // All of the operands of a BUILD_VECTOR must have the same type.
9924 if (Val.getValueType() != MemVT)
9929 // Build the extracted vector elements back into a vector.
9930 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
9933 // We should always use a vector store when merging extracted vector
9934 // elements, so this path implies a store of constants.
9935 assert(IsConstantSrc && "Merged vector elements should use vector store");
9937 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9938 APInt StoreInt(StoreBW, 0);
9940 // Construct a single integer constant which is made of the smaller
9942 bool IsLE = TLI.isLittleEndian();
9943 for (unsigned i = 0; i < NumElem ; ++i) {
9944 unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
9945 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9946 SDValue Val = St->getValue();
9947 StoreInt <<= ElementSizeBytes*8;
9948 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9949 StoreInt |= C->getAPIntValue().zext(StoreBW);
9950 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9951 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9953 llvm_unreachable("Invalid constant element type");
9957 // Create the new Load and Store operations.
9958 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9959 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9962 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9963 FirstInChain->getBasePtr(),
9964 FirstInChain->getPointerInfo(),
9966 FirstInChain->getAlignment());
9968 // Replace the first store with the new store
9969 CombineTo(EarliestOp, NewStore);
9970 // Erase all other stores.
9971 for (unsigned i = 0; i < NumElem ; ++i) {
9972 if (StoreNodes[i].MemNode == EarliestOp)
9974 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9975 // ReplaceAllUsesWith will replace all uses that existed when it was
9976 // called, but graph optimizations may cause new ones to appear. For
9977 // example, the case in pr14333 looks like
9979 // St's chain -> St -> another store -> X
9981 // And the only difference from St to the other store is the chain.
9982 // When we change it's chain to be St's chain they become identical,
9983 // get CSEed and the net result is that X is now a use of St.
9984 // Since we know that St is redundant, just iterate.
9985 while (!St->use_empty())
9986 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9987 deleteAndRecombine(St);
9993 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9994 EVT MemVT = St->getMemoryVT();
9995 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9996 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
9997 Attribute::NoImplicitFloat);
9999 // Don't merge vectors into wider inputs.
10000 if (MemVT.isVector() || !MemVT.isSimple())
10003 // Perform an early exit check. Do not bother looking at stored values that
10004 // are not constants, loads, or extracted vector elements.
10005 SDValue StoredVal = St->getValue();
10006 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10007 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10008 isa<ConstantFPSDNode>(StoredVal);
10009 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10011 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10014 // Only look at ends of store sequences.
10015 SDValue Chain = SDValue(St, 0);
10016 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10019 // This holds the base pointer, index, and the offset in bytes from the base
10021 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10023 // We must have a base and an offset.
10024 if (!BasePtr.Base.getNode())
10027 // Do not handle stores to undef base pointers.
10028 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10031 // Save the LoadSDNodes that we find in the chain.
10032 // We need to make sure that these nodes do not interfere with
10033 // any of the store nodes.
10034 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10036 // Save the StoreSDNodes that we find in the chain.
10037 SmallVector<MemOpLink, 8> StoreNodes;
10039 // Walk up the chain and look for nodes with offsets from the same
10040 // base pointer. Stop when reaching an instruction with a different kind
10041 // or instruction which has a different base pointer.
10043 StoreSDNode *Index = St;
10045 // If the chain has more than one use, then we can't reorder the mem ops.
10046 if (Index != St && !SDValue(Index, 0)->hasOneUse())
10049 // Find the base pointer and offset for this memory node.
10050 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10052 // Check that the base pointer is the same as the original one.
10053 if (!Ptr.equalBaseIndex(BasePtr))
10056 // Check that the alignment is the same.
10057 if (Index->getAlignment() != St->getAlignment())
10060 // The memory operands must not be volatile.
10061 if (Index->isVolatile() || Index->isIndexed())
10065 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10066 if (St->isTruncatingStore())
10069 // The stored memory type must be the same.
10070 if (Index->getMemoryVT() != MemVT)
10073 // We do not allow unaligned stores because we want to prevent overriding
10075 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
10078 // We found a potential memory operand to merge.
10079 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10081 // Find the next memory operand in the chain. If the next operand in the
10082 // chain is a store then move up and continue the scan with the next
10083 // memory operand. If the next operand is a load save it and use alias
10084 // information to check if it interferes with anything.
10085 SDNode *NextInChain = Index->getChain().getNode();
10087 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10088 // We found a store node. Use it for the next iteration.
10091 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10092 if (Ldn->isVolatile()) {
10097 // Save the load node for later. Continue the scan.
10098 AliasLoadNodes.push_back(Ldn);
10099 NextInChain = Ldn->getChain().getNode();
10108 // Check if there is anything to merge.
10109 if (StoreNodes.size() < 2)
10112 // Sort the memory operands according to their distance from the base pointer.
10113 std::sort(StoreNodes.begin(), StoreNodes.end(),
10114 [](MemOpLink LHS, MemOpLink RHS) {
10115 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10116 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10117 LHS.SequenceNum > RHS.SequenceNum);
10120 // Scan the memory operations on the chain and find the first non-consecutive
10121 // store memory address.
10122 unsigned LastConsecutiveStore = 0;
10123 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10124 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10126 // Check that the addresses are consecutive starting from the second
10127 // element in the list of stores.
10129 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10130 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10134 bool Alias = false;
10135 // Check if this store interferes with any of the loads that we found.
10136 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10137 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10141 // We found a load that alias with this store. Stop the sequence.
10145 // Mark this node as useful.
10146 LastConsecutiveStore = i;
10149 // The node with the lowest store address.
10150 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10152 // Store the constants into memory as one consecutive store.
10153 if (IsConstantSrc) {
10154 unsigned LastLegalType = 0;
10155 unsigned LastLegalVectorType = 0;
10156 bool NonZero = false;
10157 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10158 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10159 SDValue StoredVal = St->getValue();
10161 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10162 NonZero |= !C->isNullValue();
10163 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10164 NonZero |= !C->getConstantFPValue()->isNullValue();
10170 // Find a legal type for the constant store.
10171 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10172 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10173 if (TLI.isTypeLegal(StoreTy))
10174 LastLegalType = i+1;
10175 // Or check whether a truncstore is legal.
10176 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10177 TargetLowering::TypePromoteInteger) {
10178 EVT LegalizedStoredValueTy =
10179 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10180 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
10181 LastLegalType = i+1;
10184 // Find a legal type for the vector store.
10185 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10186 if (TLI.isTypeLegal(Ty))
10187 LastLegalVectorType = i + 1;
10190 // We only use vectors if the constant is known to be zero and the
10191 // function is not marked with the noimplicitfloat attribute.
10192 if (NonZero || NoVectors)
10193 LastLegalVectorType = 0;
10195 // Check if we found a legal integer type to store.
10196 if (LastLegalType == 0 && LastLegalVectorType == 0)
10199 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10200 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10202 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10206 // When extracting multiple vector elements, try to store them
10207 // in one vector store rather than a sequence of scalar stores.
10208 if (IsExtractVecEltSrc) {
10209 unsigned NumElem = 0;
10210 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10211 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10212 SDValue StoredVal = St->getValue();
10213 // This restriction could be loosened.
10214 // Bail out if any stored values are not elements extracted from a vector.
10215 // It should be possible to handle mixed sources, but load sources need
10216 // more careful handling (see the block of code below that handles
10217 // consecutive loads).
10218 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10221 // Find a legal type for the vector store.
10222 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10223 if (TLI.isTypeLegal(Ty))
10227 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10231 // Below we handle the case of multiple consecutive stores that
10232 // come from multiple consecutive loads. We merge them into a single
10233 // wide load and a single wide store.
10235 // Look for load nodes which are used by the stored values.
10236 SmallVector<MemOpLink, 8> LoadNodes;
10238 // Find acceptable loads. Loads need to have the same chain (token factor),
10239 // must not be zext, volatile, indexed, and they must be consecutive.
10240 BaseIndexOffset LdBasePtr;
10241 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10242 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10243 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10246 // Loads must only have one use.
10247 if (!Ld->hasNUsesOfValue(1, 0))
10250 // Check that the alignment is the same as the stores.
10251 if (Ld->getAlignment() != St->getAlignment())
10254 // The memory operands must not be volatile.
10255 if (Ld->isVolatile() || Ld->isIndexed())
10258 // We do not accept ext loads.
10259 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10262 // The stored memory type must be the same.
10263 if (Ld->getMemoryVT() != MemVT)
10266 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10267 // If this is not the first ptr that we check.
10268 if (LdBasePtr.Base.getNode()) {
10269 // The base ptr must be the same.
10270 if (!LdPtr.equalBaseIndex(LdBasePtr))
10273 // Check that all other base pointers are the same as this one.
10277 // We found a potential memory operand to merge.
10278 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10281 if (LoadNodes.size() < 2)
10284 // If we have load/store pair instructions and we only have two values,
10286 unsigned RequiredAlignment;
10287 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10288 St->getAlignment() >= RequiredAlignment)
10291 // Scan the memory operations on the chain and find the first non-consecutive
10292 // load memory address. These variables hold the index in the store node
10294 unsigned LastConsecutiveLoad = 0;
10295 // This variable refers to the size and not index in the array.
10296 unsigned LastLegalVectorType = 0;
10297 unsigned LastLegalIntegerType = 0;
10298 StartAddress = LoadNodes[0].OffsetFromBase;
10299 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10300 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10301 // All loads much share the same chain.
10302 if (LoadNodes[i].MemNode->getChain() != FirstChain)
10305 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10306 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10308 LastConsecutiveLoad = i;
10310 // Find a legal type for the vector store.
10311 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10312 if (TLI.isTypeLegal(StoreTy))
10313 LastLegalVectorType = i + 1;
10315 // Find a legal type for the integer store.
10316 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10317 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10318 if (TLI.isTypeLegal(StoreTy))
10319 LastLegalIntegerType = i + 1;
10320 // Or check whether a truncstore and extload is legal.
10321 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10322 TargetLowering::TypePromoteInteger) {
10323 EVT LegalizedStoredValueTy =
10324 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10325 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10326 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10327 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10328 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
10329 LastLegalIntegerType = i+1;
10333 // Only use vector types if the vector type is larger than the integer type.
10334 // If they are the same, use integers.
10335 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
10336 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10338 // We add +1 here because the LastXXX variables refer to location while
10339 // the NumElem refers to array/index size.
10340 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10341 NumElem = std::min(LastLegalType, NumElem);
10346 // The earliest Node in the DAG.
10347 unsigned EarliestNodeUsed = 0;
10348 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10349 for (unsigned i=1; i<NumElem; ++i) {
10350 // Find a chain for the new wide-store operand. Notice that some
10351 // of the store nodes that we found may not be selected for inclusion
10352 // in the wide store. The chain we use needs to be the chain of the
10353 // earliest store node which is *used* and replaced by the wide store.
10354 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
10355 EarliestNodeUsed = i;
10358 // Find if it is better to use vectors or integers to load and store
10362 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10364 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10365 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10368 SDLoc LoadDL(LoadNodes[0].MemNode);
10369 SDLoc StoreDL(StoreNodes[0].MemNode);
10371 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10372 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10373 FirstLoad->getChain(),
10374 FirstLoad->getBasePtr(),
10375 FirstLoad->getPointerInfo(),
10376 false, false, false,
10377 FirstLoad->getAlignment());
10379 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
10380 FirstInChain->getBasePtr(),
10381 FirstInChain->getPointerInfo(), false, false,
10382 FirstInChain->getAlignment());
10384 // Replace one of the loads with the new load.
10385 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10386 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10387 SDValue(NewLoad.getNode(), 1));
10389 // Remove the rest of the load chains.
10390 for (unsigned i = 1; i < NumElem ; ++i) {
10391 // Replace all chain users of the old load nodes with the chain of the new
10393 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
10394 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10397 // Replace the first store with the new store.
10398 CombineTo(EarliestOp, NewStore);
10399 // Erase all other stores.
10400 for (unsigned i = 0; i < NumElem ; ++i) {
10401 // Remove all Store nodes.
10402 if (StoreNodes[i].MemNode == EarliestOp)
10404 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10405 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
10406 deleteAndRecombine(St);
10412 SDValue DAGCombiner::visitSTORE(SDNode *N) {
10413 StoreSDNode *ST = cast<StoreSDNode>(N);
10414 SDValue Chain = ST->getChain();
10415 SDValue Value = ST->getValue();
10416 SDValue Ptr = ST->getBasePtr();
10418 // If this is a store of a bit convert, store the input value if the
10419 // resultant store does not need a higher alignment than the original.
10420 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
10421 ST->isUnindexed()) {
10422 unsigned OrigAlign = ST->getAlignment();
10423 EVT SVT = Value.getOperand(0).getValueType();
10424 unsigned Align = TLI.getDataLayout()->
10425 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
10426 if (Align <= OrigAlign &&
10427 ((!LegalOperations && !ST->isVolatile()) ||
10428 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
10429 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
10430 Ptr, ST->getPointerInfo(), ST->isVolatile(),
10431 ST->isNonTemporal(), OrigAlign,
10435 // Turn 'store undef, Ptr' -> nothing.
10436 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10439 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
10440 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
10441 // NOTE: If the original store is volatile, this transform must not increase
10442 // the number of stores. For example, on x86-32 an f64 can be stored in one
10443 // processor operation but an i64 (which is not legal) requires two. So the
10444 // transform should not be done in this case.
10445 if (Value.getOpcode() != ISD::TargetConstantFP) {
10447 switch (CFP->getSimpleValueType(0).SimpleTy) {
10448 default: llvm_unreachable("Unknown FP type");
10449 case MVT::f16: // We don't do this for these yet.
10455 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
10456 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10457 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
10458 bitcastToAPInt().getZExtValue(), MVT::i32);
10459 return DAG.getStore(Chain, SDLoc(N), Tmp,
10460 Ptr, ST->getMemOperand());
10464 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
10465 !ST->isVolatile()) ||
10466 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
10467 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
10468 getZExtValue(), MVT::i64);
10469 return DAG.getStore(Chain, SDLoc(N), Tmp,
10470 Ptr, ST->getMemOperand());
10473 if (!ST->isVolatile() &&
10474 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10475 // Many FP stores are not made apparent until after legalize, e.g. for
10476 // argument passing. Since this is so common, custom legalize the
10477 // 64-bit integer store into two 32-bit stores.
10478 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
10479 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10480 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
10481 if (TLI.isBigEndian()) std::swap(Lo, Hi);
10483 unsigned Alignment = ST->getAlignment();
10484 bool isVolatile = ST->isVolatile();
10485 bool isNonTemporal = ST->isNonTemporal();
10486 AAMDNodes AAInfo = ST->getAAInfo();
10488 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
10489 Ptr, ST->getPointerInfo(),
10490 isVolatile, isNonTemporal,
10491 ST->getAlignment(), AAInfo);
10492 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
10493 DAG.getConstant(4, Ptr.getValueType()));
10494 Alignment = MinAlign(Alignment, 4U);
10495 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
10496 Ptr, ST->getPointerInfo().getWithOffset(4),
10497 isVolatile, isNonTemporal,
10498 Alignment, AAInfo);
10499 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10508 // Try to infer better alignment information than the store already has.
10509 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
10510 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10511 if (Align > ST->getAlignment())
10512 return DAG.getTruncStore(Chain, SDLoc(N), Value,
10513 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
10514 ST->isVolatile(), ST->isNonTemporal(), Align,
10519 // Try transforming a pair floating point load / store ops to integer
10520 // load / store ops.
10521 SDValue NewST = TransformFPLoadStorePair(N);
10522 if (NewST.getNode())
10525 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10526 : DAG.getSubtarget().useAA();
10528 if (CombinerAAOnlyFunc.getNumOccurrences() &&
10529 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10532 if (UseAA && ST->isUnindexed()) {
10533 // Walk up chain skipping non-aliasing memory nodes.
10534 SDValue BetterChain = FindBetterChain(N, Chain);
10536 // If there is a better chain.
10537 if (Chain != BetterChain) {
10540 // Replace the chain to avoid dependency.
10541 if (ST->isTruncatingStore()) {
10542 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
10543 ST->getMemoryVT(), ST->getMemOperand());
10545 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
10546 ST->getMemOperand());
10549 // Create token to keep both nodes around.
10550 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10551 MVT::Other, Chain, ReplStore);
10553 // Make sure the new and old chains are cleaned up.
10554 AddToWorklist(Token.getNode());
10556 // Don't add users to work list.
10557 return CombineTo(N, Token, false);
10561 // Try transforming N to an indexed store.
10562 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10563 return SDValue(N, 0);
10565 // FIXME: is there such a thing as a truncating indexed store?
10566 if (ST->isTruncatingStore() && ST->isUnindexed() &&
10567 Value.getValueType().isInteger()) {
10568 // See if we can simplify the input to this truncstore with knowledge that
10569 // only the low bits are being used. For example:
10570 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
10572 GetDemandedBits(Value,
10573 APInt::getLowBitsSet(
10574 Value.getValueType().getScalarType().getSizeInBits(),
10575 ST->getMemoryVT().getScalarType().getSizeInBits()));
10576 AddToWorklist(Value.getNode());
10577 if (Shorter.getNode())
10578 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
10579 Ptr, ST->getMemoryVT(), ST->getMemOperand());
10581 // Otherwise, see if we can simplify the operation with
10582 // SimplifyDemandedBits, which only works if the value has a single use.
10583 if (SimplifyDemandedBits(Value,
10584 APInt::getLowBitsSet(
10585 Value.getValueType().getScalarType().getSizeInBits(),
10586 ST->getMemoryVT().getScalarType().getSizeInBits())))
10587 return SDValue(N, 0);
10590 // If this is a load followed by a store to the same location, then the store
10592 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
10593 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
10594 ST->isUnindexed() && !ST->isVolatile() &&
10595 // There can't be any side effects between the load and store, such as
10596 // a call or store.
10597 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
10598 // The store is dead, remove it.
10603 // If this is a store followed by a store with the same value to the same
10604 // location, then the store is dead/noop.
10605 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
10606 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
10607 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
10608 ST1->isUnindexed() && !ST1->isVolatile()) {
10609 // The store is dead, remove it.
10614 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
10615 // truncating store. We can do this even if this is already a truncstore.
10616 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
10617 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
10618 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
10619 ST->getMemoryVT())) {
10620 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
10621 Ptr, ST->getMemoryVT(), ST->getMemOperand());
10624 // Only perform this optimization before the types are legal, because we
10625 // don't want to perform this optimization on every DAGCombine invocation.
10627 bool EverChanged = false;
10630 // There can be multiple store sequences on the same chain.
10631 // Keep trying to merge store sequences until we are unable to do so
10632 // or until we merge the last store on the chain.
10633 bool Changed = MergeConsecutiveStores(ST);
10634 EverChanged |= Changed;
10635 if (!Changed) break;
10636 } while (ST->getOpcode() != ISD::DELETED_NODE);
10639 return SDValue(N, 0);
10642 return ReduceLoadOpStoreWidth(N);
10645 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
10646 SDValue InVec = N->getOperand(0);
10647 SDValue InVal = N->getOperand(1);
10648 SDValue EltNo = N->getOperand(2);
10651 // If the inserted element is an UNDEF, just use the input vector.
10652 if (InVal.getOpcode() == ISD::UNDEF)
10655 EVT VT = InVec.getValueType();
10657 // If we can't generate a legal BUILD_VECTOR, exit
10658 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10661 // Check that we know which element is being inserted
10662 if (!isa<ConstantSDNode>(EltNo))
10664 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10666 // Canonicalize insert_vector_elt dag nodes.
10668 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10669 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10671 // Do this only if the child insert_vector node has one use; also
10672 // do this only if indices are both constants and Idx1 < Idx0.
10673 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10674 && isa<ConstantSDNode>(InVec.getOperand(2))) {
10675 unsigned OtherElt =
10676 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10677 if (Elt < OtherElt) {
10679 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10680 InVec.getOperand(0), InVal, EltNo);
10681 AddToWorklist(NewOp.getNode());
10682 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10683 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10687 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10688 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
10689 // vector elements.
10690 SmallVector<SDValue, 8> Ops;
10691 // Do not combine these two vectors if the output vector will not replace
10692 // the input vector.
10693 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
10694 Ops.append(InVec.getNode()->op_begin(),
10695 InVec.getNode()->op_end());
10696 } else if (InVec.getOpcode() == ISD::UNDEF) {
10697 unsigned NElts = VT.getVectorNumElements();
10698 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10703 // Insert the element
10704 if (Elt < Ops.size()) {
10705 // All the operands of BUILD_VECTOR must have the same type;
10706 // we enforce that here.
10707 EVT OpVT = Ops[0].getValueType();
10708 if (InVal.getValueType() != OpVT)
10709 InVal = OpVT.bitsGT(InVal.getValueType()) ?
10710 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10711 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10715 // Return the new vector
10716 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
10719 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10720 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10721 EVT ResultVT = EVE->getValueType(0);
10722 EVT VecEltVT = InVecVT.getVectorElementType();
10723 unsigned Align = OriginalLoad->getAlignment();
10724 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10725 VecEltVT.getTypeForEVT(*DAG.getContext()));
10727 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10732 SDValue NewPtr = OriginalLoad->getBasePtr();
10734 EVT PtrType = NewPtr.getValueType();
10735 MachinePointerInfo MPI;
10736 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10737 int Elt = ConstEltNo->getZExtValue();
10738 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10739 if (TLI.isBigEndian())
10740 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10741 Offset = DAG.getConstant(PtrOff, PtrType);
10742 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10744 Offset = DAG.getNode(
10745 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10746 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10747 if (TLI.isBigEndian())
10748 Offset = DAG.getNode(
10749 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10750 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10751 MPI = OriginalLoad->getPointerInfo();
10753 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10755 // The replacement we need to do here is a little tricky: we need to
10756 // replace an extractelement of a load with a load.
10757 // Use ReplaceAllUsesOfValuesWith to do the replacement.
10758 // Note that this replacement assumes that the extractvalue is the only
10759 // use of the load; that's okay because we don't want to perform this
10760 // transformation in other cases anyway.
10763 if (ResultVT.bitsGT(VecEltVT)) {
10764 // If the result type of vextract is wider than the load, then issue an
10765 // extending load instead.
10766 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
10770 Load = DAG.getExtLoad(
10771 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10772 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10773 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10774 Chain = Load.getValue(1);
10776 Load = DAG.getLoad(
10777 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10778 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10779 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10780 Chain = Load.getValue(1);
10781 if (ResultVT.bitsLT(VecEltVT))
10782 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10784 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10786 WorklistRemover DeadNodes(*this);
10787 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10788 SDValue To[] = { Load, Chain };
10789 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10790 // Since we're explicitly calling ReplaceAllUses, add the new node to the
10791 // worklist explicitly as well.
10792 AddToWorklist(Load.getNode());
10793 AddUsersToWorklist(Load.getNode()); // Add users too
10794 // Make sure to revisit this node to clean it up; it will usually be dead.
10795 AddToWorklist(EVE);
10797 return SDValue(EVE, 0);
10800 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10801 // (vextract (scalar_to_vector val, 0) -> val
10802 SDValue InVec = N->getOperand(0);
10803 EVT VT = InVec.getValueType();
10804 EVT NVT = N->getValueType(0);
10806 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10807 // Check if the result type doesn't match the inserted element type. A
10808 // SCALAR_TO_VECTOR may truncate the inserted element and the
10809 // EXTRACT_VECTOR_ELT may widen the extracted vector.
10810 SDValue InOp = InVec.getOperand(0);
10811 if (InOp.getValueType() != NVT) {
10812 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10813 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10818 SDValue EltNo = N->getOperand(1);
10819 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10821 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10822 // We only perform this optimization before the op legalization phase because
10823 // we may introduce new vector instructions which are not backed by TD
10824 // patterns. For example on AVX, extracting elements from a wide vector
10825 // without using extract_subvector. However, if we can find an underlying
10826 // scalar value, then we can always use that.
10827 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10829 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10830 int NumElem = VT.getVectorNumElements();
10831 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10832 // Find the new index to extract from.
10833 int OrigElt = SVOp->getMaskElt(Elt);
10835 // Extracting an undef index is undef.
10837 return DAG.getUNDEF(NVT);
10839 // Select the right vector half to extract from.
10841 if (OrigElt < NumElem) {
10842 SVInVec = InVec->getOperand(0);
10844 SVInVec = InVec->getOperand(1);
10845 OrigElt -= NumElem;
10848 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10849 SDValue InOp = SVInVec.getOperand(OrigElt);
10850 if (InOp.getValueType() != NVT) {
10851 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10852 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10858 // FIXME: We should handle recursing on other vector shuffles and
10859 // scalar_to_vector here as well.
10861 if (!LegalOperations) {
10862 EVT IndexTy = TLI.getVectorIdxTy();
10863 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10864 SVInVec, DAG.getConstant(OrigElt, IndexTy));
10868 bool BCNumEltsChanged = false;
10869 EVT ExtVT = VT.getVectorElementType();
10872 // If the result of load has to be truncated, then it's not necessarily
10874 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10877 if (InVec.getOpcode() == ISD::BITCAST) {
10878 // Don't duplicate a load with other uses.
10879 if (!InVec.hasOneUse())
10882 EVT BCVT = InVec.getOperand(0).getValueType();
10883 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10885 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10886 BCNumEltsChanged = true;
10887 InVec = InVec.getOperand(0);
10888 ExtVT = BCVT.getVectorElementType();
10891 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10892 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10893 ISD::isNormalLoad(InVec.getNode()) &&
10894 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10895 SDValue Index = N->getOperand(1);
10896 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10897 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10901 // Perform only after legalization to ensure build_vector / vector_shuffle
10902 // optimizations have already been done.
10903 if (!LegalOperations) return SDValue();
10905 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10906 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10907 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10910 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10912 LoadSDNode *LN0 = nullptr;
10913 const ShuffleVectorSDNode *SVN = nullptr;
10914 if (ISD::isNormalLoad(InVec.getNode())) {
10915 LN0 = cast<LoadSDNode>(InVec);
10916 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10917 InVec.getOperand(0).getValueType() == ExtVT &&
10918 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10919 // Don't duplicate a load with other uses.
10920 if (!InVec.hasOneUse())
10923 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10924 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10925 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10927 // (load $addr+1*size)
10929 // Don't duplicate a load with other uses.
10930 if (!InVec.hasOneUse())
10933 // If the bit convert changed the number of elements, it is unsafe
10934 // to examine the mask.
10935 if (BCNumEltsChanged)
10938 // Select the input vector, guarding against out of range extract vector.
10939 unsigned NumElems = VT.getVectorNumElements();
10940 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10941 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10943 if (InVec.getOpcode() == ISD::BITCAST) {
10944 // Don't duplicate a load with other uses.
10945 if (!InVec.hasOneUse())
10948 InVec = InVec.getOperand(0);
10950 if (ISD::isNormalLoad(InVec.getNode())) {
10951 LN0 = cast<LoadSDNode>(InVec);
10952 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10953 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10957 // Make sure we found a non-volatile load and the extractelement is
10959 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10962 // If Idx was -1 above, Elt is going to be -1, so just return undef.
10964 return DAG.getUNDEF(LVT);
10966 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10972 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10973 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10974 // We perform this optimization post type-legalization because
10975 // the type-legalizer often scalarizes integer-promoted vectors.
10976 // Performing this optimization before may create bit-casts which
10977 // will be type-legalized to complex code sequences.
10978 // We perform this optimization only before the operation legalizer because we
10979 // may introduce illegal operations.
10980 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10983 unsigned NumInScalars = N->getNumOperands();
10985 EVT VT = N->getValueType(0);
10987 // Check to see if this is a BUILD_VECTOR of a bunch of values
10988 // which come from any_extend or zero_extend nodes. If so, we can create
10989 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10990 // optimizations. We do not handle sign-extend because we can't fill the sign
10992 EVT SourceType = MVT::Other;
10993 bool AllAnyExt = true;
10995 for (unsigned i = 0; i != NumInScalars; ++i) {
10996 SDValue In = N->getOperand(i);
10997 // Ignore undef inputs.
10998 if (In.getOpcode() == ISD::UNDEF) continue;
11000 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
11001 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11003 // Abort if the element is not an extension.
11004 if (!ZeroExt && !AnyExt) {
11005 SourceType = MVT::Other;
11009 // The input is a ZeroExt or AnyExt. Check the original type.
11010 EVT InTy = In.getOperand(0).getValueType();
11012 // Check that all of the widened source types are the same.
11013 if (SourceType == MVT::Other)
11016 else if (InTy != SourceType) {
11017 // Multiple income types. Abort.
11018 SourceType = MVT::Other;
11022 // Check if all of the extends are ANY_EXTENDs.
11023 AllAnyExt &= AnyExt;
11026 // In order to have valid types, all of the inputs must be extended from the
11027 // same source type and all of the inputs must be any or zero extend.
11028 // Scalar sizes must be a power of two.
11029 EVT OutScalarTy = VT.getScalarType();
11030 bool ValidTypes = SourceType != MVT::Other &&
11031 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11032 isPowerOf2_32(SourceType.getSizeInBits());
11034 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11035 // turn into a single shuffle instruction.
11039 bool isLE = TLI.isLittleEndian();
11040 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11041 assert(ElemRatio > 1 && "Invalid element size ratio");
11042 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11043 DAG.getConstant(0, SourceType);
11045 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11046 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11048 // Populate the new build_vector
11049 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11050 SDValue Cast = N->getOperand(i);
11051 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11052 Cast.getOpcode() == ISD::ZERO_EXTEND ||
11053 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11055 if (Cast.getOpcode() == ISD::UNDEF)
11056 In = DAG.getUNDEF(SourceType);
11058 In = Cast->getOperand(0);
11059 unsigned Index = isLE ? (i * ElemRatio) :
11060 (i * ElemRatio + (ElemRatio - 1));
11062 assert(Index < Ops.size() && "Invalid index");
11066 // The type of the new BUILD_VECTOR node.
11067 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11068 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11069 "Invalid vector size");
11070 // Check if the new vector type is legal.
11071 if (!isTypeLegal(VecVT)) return SDValue();
11073 // Make the new BUILD_VECTOR.
11074 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11076 // The new BUILD_VECTOR node has the potential to be further optimized.
11077 AddToWorklist(BV.getNode());
11078 // Bitcast to the desired type.
11079 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11082 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11083 EVT VT = N->getValueType(0);
11085 unsigned NumInScalars = N->getNumOperands();
11088 EVT SrcVT = MVT::Other;
11089 unsigned Opcode = ISD::DELETED_NODE;
11090 unsigned NumDefs = 0;
11092 for (unsigned i = 0; i != NumInScalars; ++i) {
11093 SDValue In = N->getOperand(i);
11094 unsigned Opc = In.getOpcode();
11096 if (Opc == ISD::UNDEF)
11099 // If all scalar values are floats and converted from integers.
11100 if (Opcode == ISD::DELETED_NODE &&
11101 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11108 EVT InVT = In.getOperand(0).getValueType();
11110 // If all scalar values are typed differently, bail out. It's chosen to
11111 // simplify BUILD_VECTOR of integer types.
11112 if (SrcVT == MVT::Other)
11119 // If the vector has just one element defined, it's not worth to fold it into
11120 // a vectorized one.
11124 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11125 && "Should only handle conversion from integer to float.");
11126 assert(SrcVT != MVT::Other && "Cannot determine source type!");
11128 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11130 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11133 SmallVector<SDValue, 8> Opnds;
11134 for (unsigned i = 0; i != NumInScalars; ++i) {
11135 SDValue In = N->getOperand(i);
11137 if (In.getOpcode() == ISD::UNDEF)
11138 Opnds.push_back(DAG.getUNDEF(SrcVT));
11140 Opnds.push_back(In.getOperand(0));
11142 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11143 AddToWorklist(BV.getNode());
11145 return DAG.getNode(Opcode, dl, VT, BV);
11148 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11149 unsigned NumInScalars = N->getNumOperands();
11151 EVT VT = N->getValueType(0);
11153 // A vector built entirely of undefs is undef.
11154 if (ISD::allOperandsUndef(N))
11155 return DAG.getUNDEF(VT);
11157 SDValue V = reduceBuildVecExtToExtBuildVec(N);
11161 V = reduceBuildVecConvertToConvertBuildVec(N);
11165 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11166 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11167 // at most two distinct vectors, turn this into a shuffle node.
11169 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11170 if (!isTypeLegal(VT))
11173 // May only combine to shuffle after legalize if shuffle is legal.
11174 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11177 SDValue VecIn1, VecIn2;
11178 bool UsesZeroVector = false;
11179 for (unsigned i = 0; i != NumInScalars; ++i) {
11180 SDValue Op = N->getOperand(i);
11181 // Ignore undef inputs.
11182 if (Op.getOpcode() == ISD::UNDEF) continue;
11184 // See if we can combine this build_vector into a blend with a zero vector.
11185 if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
11186 cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
11187 (Op.getOpcode() == ISD::ConstantFP &&
11188 cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11189 UsesZeroVector = true;
11193 // If this input is something other than a EXTRACT_VECTOR_ELT with a
11194 // constant index, bail out.
11195 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11196 !isa<ConstantSDNode>(Op.getOperand(1))) {
11197 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11201 // We allow up to two distinct input vectors.
11202 SDValue ExtractedFromVec = Op.getOperand(0);
11203 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11206 if (!VecIn1.getNode()) {
11207 VecIn1 = ExtractedFromVec;
11208 } else if (!VecIn2.getNode() && !UsesZeroVector) {
11209 VecIn2 = ExtractedFromVec;
11211 // Too many inputs.
11212 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11217 // If everything is good, we can make a shuffle operation.
11218 if (VecIn1.getNode()) {
11219 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11220 SmallVector<int, 8> Mask;
11221 for (unsigned i = 0; i != NumInScalars; ++i) {
11222 unsigned Opcode = N->getOperand(i).getOpcode();
11223 if (Opcode == ISD::UNDEF) {
11224 Mask.push_back(-1);
11228 // Operands can also be zero.
11229 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11230 assert(UsesZeroVector &&
11231 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11232 "Unexpected node found!");
11233 Mask.push_back(NumInScalars+i);
11237 // If extracting from the first vector, just use the index directly.
11238 SDValue Extract = N->getOperand(i);
11239 SDValue ExtVal = Extract.getOperand(1);
11240 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11241 if (Extract.getOperand(0) == VecIn1) {
11242 Mask.push_back(ExtIndex);
11246 // Otherwise, use InIdx + InputVecSize
11247 Mask.push_back(InNumElements + ExtIndex);
11250 // Avoid introducing illegal shuffles with zero.
11251 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11254 // We can't generate a shuffle node with mismatched input and output types.
11255 // Attempt to transform a single input vector to the correct type.
11256 if ((VT != VecIn1.getValueType())) {
11257 // If the input vector type has a different base type to the output
11258 // vector type, bail out.
11259 EVT VTElemType = VT.getVectorElementType();
11260 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11261 (VecIn2.getNode() &&
11262 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11265 // If the input vector is too small, widen it.
11266 // We only support widening of vectors which are half the size of the
11267 // output registers. For example XMM->YMM widening on X86 with AVX.
11268 EVT VecInT = VecIn1.getValueType();
11269 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11270 // If we only have one small input, widen it by adding undef values.
11271 if (!VecIn2.getNode())
11272 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11273 DAG.getUNDEF(VecIn1.getValueType()));
11274 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11275 // If we have two small inputs of the same type, try to concat them.
11276 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11277 VecIn2 = SDValue(nullptr, 0);
11280 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11281 // If the input vector is too large, try to split it.
11282 // We don't support having two input vectors that are too large.
11283 if (VecIn2.getNode())
11286 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11289 // Try to replace VecIn1 with two extract_subvectors
11290 // No need to update the masks, they should still be correct.
11291 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11292 DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy()));
11293 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11294 DAG.getConstant(0, TLI.getVectorIdxTy()));
11295 UsesZeroVector = false;
11300 if (UsesZeroVector)
11301 VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
11302 DAG.getConstantFP(0.0, VT);
11304 // If VecIn2 is unused then change it to undef.
11305 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11307 // Check that we were able to transform all incoming values to the same
11309 if (VecIn2.getValueType() != VecIn1.getValueType() ||
11310 VecIn1.getValueType() != VT)
11313 // Return the new VECTOR_SHUFFLE node.
11317 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
11323 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
11324 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11325 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
11326 // inputs come from at most two distinct vectors, turn this into a shuffle
11329 // If we only have one input vector, we don't need to do any concatenation.
11330 if (N->getNumOperands() == 1)
11331 return N->getOperand(0);
11333 // Check if all of the operands are undefs.
11334 EVT VT = N->getValueType(0);
11335 if (ISD::allOperandsUndef(N))
11336 return DAG.getUNDEF(VT);
11338 // Optimize concat_vectors where one of the vectors is undef.
11339 if (N->getNumOperands() == 2 &&
11340 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
11341 SDValue In = N->getOperand(0);
11342 assert(In.getValueType().isVector() && "Must concat vectors");
11344 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11345 if (In->getOpcode() == ISD::BITCAST &&
11346 !In->getOperand(0)->getValueType(0).isVector()) {
11347 SDValue Scalar = In->getOperand(0);
11348 EVT SclTy = Scalar->getValueType(0);
11350 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
11353 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
11354 VT.getSizeInBits() / SclTy.getSizeInBits());
11355 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
11358 SDLoc dl = SDLoc(N);
11359 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
11360 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
11364 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
11365 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
11366 if (N->getNumOperands() == 2 &&
11367 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
11368 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
11369 EVT VT = N->getValueType(0);
11370 SDValue N0 = N->getOperand(0);
11371 SDValue N1 = N->getOperand(1);
11372 SmallVector<SDValue, 8> Opnds;
11373 unsigned BuildVecNumElts = N0.getNumOperands();
11375 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
11376 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
11377 if (SclTy0.isFloatingPoint()) {
11378 for (unsigned i = 0; i != BuildVecNumElts; ++i)
11379 Opnds.push_back(N0.getOperand(i));
11380 for (unsigned i = 0; i != BuildVecNumElts; ++i)
11381 Opnds.push_back(N1.getOperand(i));
11383 // If BUILD_VECTOR are from built from integer, they may have different
11384 // operand types. Get the smaller type and truncate all operands to it.
11385 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
11386 for (unsigned i = 0; i != BuildVecNumElts; ++i)
11387 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
11388 N0.getOperand(i)));
11389 for (unsigned i = 0; i != BuildVecNumElts; ++i)
11390 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
11391 N1.getOperand(i)));
11394 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
11397 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
11398 // nodes often generate nop CONCAT_VECTOR nodes.
11399 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
11400 // place the incoming vectors at the exact same location.
11401 SDValue SingleSource = SDValue();
11402 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
11404 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11405 SDValue Op = N->getOperand(i);
11407 if (Op.getOpcode() == ISD::UNDEF)
11410 // Check if this is the identity extract:
11411 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
11414 // Find the single incoming vector for the extract_subvector.
11415 if (SingleSource.getNode()) {
11416 if (Op.getOperand(0) != SingleSource)
11419 SingleSource = Op.getOperand(0);
11421 // Check the source type is the same as the type of the result.
11422 // If not, this concat may extend the vector, so we can not
11423 // optimize it away.
11424 if (SingleSource.getValueType() != N->getValueType(0))
11428 unsigned IdentityIndex = i * PartNumElem;
11429 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11430 // The extract index must be constant.
11434 // Check that we are reading from the identity index.
11435 if (CS->getZExtValue() != IdentityIndex)
11439 if (SingleSource.getNode())
11440 return SingleSource;
11445 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
11446 EVT NVT = N->getValueType(0);
11447 SDValue V = N->getOperand(0);
11449 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
11451 // (extract_subvec (concat V1, V2, ...), i)
11454 // Only operand 0 is checked as 'concat' assumes all inputs of the same
11456 if (V->getOperand(0).getValueType() != NVT)
11458 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11459 unsigned NumElems = NVT.getVectorNumElements();
11460 assert((Idx % NumElems) == 0 &&
11461 "IDX in concat is not a multiple of the result vector length.");
11462 return V->getOperand(Idx / NumElems);
11466 if (V->getOpcode() == ISD::BITCAST)
11467 V = V.getOperand(0);
11469 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
11471 // Handle only simple case where vector being inserted and vector
11472 // being extracted are of same type, and are half size of larger vectors.
11473 EVT BigVT = V->getOperand(0).getValueType();
11474 EVT SmallVT = V->getOperand(1).getValueType();
11475 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
11478 // Only handle cases where both indexes are constants with the same type.
11479 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11480 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
11482 if (InsIdx && ExtIdx &&
11483 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
11484 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
11486 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
11488 // indices are equal or bit offsets are equal => V1
11489 // otherwise => (extract_subvec V1, ExtIdx)
11490 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
11491 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
11492 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
11493 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
11494 DAG.getNode(ISD::BITCAST, dl,
11495 N->getOperand(0).getValueType(),
11496 V->getOperand(0)), N->getOperand(1));
11503 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
11504 SDValue V, SelectionDAG &DAG) {
11506 EVT VT = V.getValueType();
11508 switch (V.getOpcode()) {
11512 case ISD::CONCAT_VECTORS: {
11513 EVT OpVT = V->getOperand(0).getValueType();
11514 int OpSize = OpVT.getVectorNumElements();
11515 SmallBitVector OpUsedElements(OpSize, false);
11516 bool FoundSimplification = false;
11517 SmallVector<SDValue, 4> NewOps;
11518 NewOps.reserve(V->getNumOperands());
11519 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
11520 SDValue Op = V->getOperand(i);
11521 bool OpUsed = false;
11522 for (int j = 0; j < OpSize; ++j)
11523 if (UsedElements[i * OpSize + j]) {
11524 OpUsedElements[j] = true;
11528 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
11529 : DAG.getUNDEF(OpVT));
11530 FoundSimplification |= Op == NewOps.back();
11531 OpUsedElements.reset();
11533 if (FoundSimplification)
11534 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
11538 case ISD::INSERT_SUBVECTOR: {
11539 SDValue BaseV = V->getOperand(0);
11540 SDValue SubV = V->getOperand(1);
11541 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
11545 int SubSize = SubV.getValueType().getVectorNumElements();
11546 int Idx = IdxN->getZExtValue();
11547 bool SubVectorUsed = false;
11548 SmallBitVector SubUsedElements(SubSize, false);
11549 for (int i = 0; i < SubSize; ++i)
11550 if (UsedElements[i + Idx]) {
11551 SubVectorUsed = true;
11552 SubUsedElements[i] = true;
11553 UsedElements[i + Idx] = false;
11556 // Now recurse on both the base and sub vectors.
11557 SDValue SimplifiedSubV =
11559 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
11560 : DAG.getUNDEF(SubV.getValueType());
11561 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
11562 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
11563 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
11564 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
11570 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
11571 SDValue N1, SelectionDAG &DAG) {
11572 EVT VT = SVN->getValueType(0);
11573 int NumElts = VT.getVectorNumElements();
11574 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
11575 for (int M : SVN->getMask())
11576 if (M >= 0 && M < NumElts)
11577 N0UsedElements[M] = true;
11578 else if (M >= NumElts)
11579 N1UsedElements[M - NumElts] = true;
11581 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
11582 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
11583 if (S0 == N0 && S1 == N1)
11586 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
11589 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
11590 // or turn a shuffle of a single concat into simpler shuffle then concat.
11591 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
11592 EVT VT = N->getValueType(0);
11593 unsigned NumElts = VT.getVectorNumElements();
11595 SDValue N0 = N->getOperand(0);
11596 SDValue N1 = N->getOperand(1);
11597 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11599 SmallVector<SDValue, 4> Ops;
11600 EVT ConcatVT = N0.getOperand(0).getValueType();
11601 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
11602 unsigned NumConcats = NumElts / NumElemsPerConcat;
11604 // Special case: shuffle(concat(A,B)) can be more efficiently represented
11605 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
11606 // half vector elements.
11607 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
11608 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
11609 SVN->getMask().end(), [](int i) { return i == -1; })) {
11610 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
11611 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
11612 N1 = DAG.getUNDEF(ConcatVT);
11613 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
11616 // Look at every vector that's inserted. We're looking for exact
11617 // subvector-sized copies from a concatenated vector
11618 for (unsigned I = 0; I != NumConcats; ++I) {
11619 // Make sure we're dealing with a copy.
11620 unsigned Begin = I * NumElemsPerConcat;
11621 bool AllUndef = true, NoUndef = true;
11622 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
11623 if (SVN->getMaskElt(J) >= 0)
11630 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
11633 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
11634 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
11637 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
11638 if (FirstElt < N0.getNumOperands())
11639 Ops.push_back(N0.getOperand(FirstElt));
11641 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
11643 } else if (AllUndef) {
11644 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
11645 } else { // Mixed with general masks and undefs, can't do optimization.
11650 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
11653 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
11654 EVT VT = N->getValueType(0);
11655 unsigned NumElts = VT.getVectorNumElements();
11657 SDValue N0 = N->getOperand(0);
11658 SDValue N1 = N->getOperand(1);
11660 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
11662 // Canonicalize shuffle undef, undef -> undef
11663 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
11664 return DAG.getUNDEF(VT);
11666 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11668 // Canonicalize shuffle v, v -> v, undef
11670 SmallVector<int, 8> NewMask;
11671 for (unsigned i = 0; i != NumElts; ++i) {
11672 int Idx = SVN->getMaskElt(i);
11673 if (Idx >= (int)NumElts) Idx -= NumElts;
11674 NewMask.push_back(Idx);
11676 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
11680 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
11681 if (N0.getOpcode() == ISD::UNDEF) {
11682 SmallVector<int, 8> NewMask;
11683 for (unsigned i = 0; i != NumElts; ++i) {
11684 int Idx = SVN->getMaskElt(i);
11686 if (Idx >= (int)NumElts)
11689 Idx = -1; // remove reference to lhs
11691 NewMask.push_back(Idx);
11693 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
11697 // Remove references to rhs if it is undef
11698 if (N1.getOpcode() == ISD::UNDEF) {
11699 bool Changed = false;
11700 SmallVector<int, 8> NewMask;
11701 for (unsigned i = 0; i != NumElts; ++i) {
11702 int Idx = SVN->getMaskElt(i);
11703 if (Idx >= (int)NumElts) {
11707 NewMask.push_back(Idx);
11710 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
11713 // If it is a splat, check if the argument vector is another splat or a
11715 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
11716 SDNode *V = N0.getNode();
11718 // If this is a bit convert that changes the element type of the vector but
11719 // not the number of vector elements, look through it. Be careful not to
11720 // look though conversions that change things like v4f32 to v2f64.
11721 if (V->getOpcode() == ISD::BITCAST) {
11722 SDValue ConvInput = V->getOperand(0);
11723 if (ConvInput.getValueType().isVector() &&
11724 ConvInput.getValueType().getVectorNumElements() == NumElts)
11725 V = ConvInput.getNode();
11728 if (V->getOpcode() == ISD::BUILD_VECTOR) {
11729 assert(V->getNumOperands() == NumElts &&
11730 "BUILD_VECTOR has wrong number of operands");
11732 bool AllSame = true;
11733 for (unsigned i = 0; i != NumElts; ++i) {
11734 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11735 Base = V->getOperand(i);
11739 // Splat of <u, u, u, u>, return <u, u, u, u>
11740 if (!Base.getNode())
11742 for (unsigned i = 0; i != NumElts; ++i) {
11743 if (V->getOperand(i) != Base) {
11748 // Splat of <x, x, x, x>, return <x, x, x, x>
11752 // Canonicalize any other splat as a build_vector.
11753 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
11754 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
11755 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
11756 V->getValueType(0), Ops);
11758 // We may have jumped through bitcasts, so the type of the
11759 // BUILD_VECTOR may not match the type of the shuffle.
11760 if (V->getValueType(0) != VT)
11761 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
11766 // There are various patterns used to build up a vector from smaller vectors,
11767 // subvectors, or elements. Scan chains of these and replace unused insertions
11768 // or components with undef.
11769 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11772 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11773 Level < AfterLegalizeVectorOps &&
11774 (N1.getOpcode() == ISD::UNDEF ||
11775 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11776 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11777 SDValue V = partitionShuffleOfConcats(N, DAG);
11783 // Canonicalize shuffles according to rules:
11784 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
11785 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
11786 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
11787 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
11788 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11789 TLI.isTypeLegal(VT)) {
11790 // The incoming shuffle must be of the same type as the result of the
11791 // current shuffle.
11792 assert(N1->getOperand(0).getValueType() == VT &&
11793 "Shuffle types don't match");
11795 SDValue SV0 = N1->getOperand(0);
11796 SDValue SV1 = N1->getOperand(1);
11797 bool HasSameOp0 = N0 == SV0;
11798 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11799 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
11800 // Commute the operands of this shuffle so that next rule
11802 return DAG.getCommutedVectorShuffle(*SVN);
11805 // Try to fold according to rules:
11806 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11807 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11808 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11809 // Don't try to fold shuffles with illegal type.
11810 // Only fold if this shuffle is the only user of the other shuffle.
11811 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
11812 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
11813 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11815 // The incoming shuffle must be of the same type as the result of the
11816 // current shuffle.
11817 assert(OtherSV->getOperand(0).getValueType() == VT &&
11818 "Shuffle types don't match");
11821 SmallVector<int, 4> Mask;
11822 // Compute the combined shuffle mask for a shuffle with SV0 as the first
11823 // operand, and SV1 as the second operand.
11824 for (unsigned i = 0; i != NumElts; ++i) {
11825 int Idx = SVN->getMaskElt(i);
11827 // Propagate Undef.
11828 Mask.push_back(Idx);
11832 SDValue CurrentVec;
11833 if (Idx < (int)NumElts) {
11834 // This shuffle index refers to the inner shuffle N0. Lookup the inner
11835 // shuffle mask to identify which vector is actually referenced.
11836 Idx = OtherSV->getMaskElt(Idx);
11838 // Propagate Undef.
11839 Mask.push_back(Idx);
11843 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
11844 : OtherSV->getOperand(1);
11846 // This shuffle index references an element within N1.
11850 // Simple case where 'CurrentVec' is UNDEF.
11851 if (CurrentVec.getOpcode() == ISD::UNDEF) {
11852 Mask.push_back(-1);
11856 // Canonicalize the shuffle index. We don't know yet if CurrentVec
11857 // will be the first or second operand of the combined shuffle.
11858 Idx = Idx % NumElts;
11859 if (!SV0.getNode() || SV0 == CurrentVec) {
11860 // Ok. CurrentVec is the left hand side.
11861 // Update the mask accordingly.
11863 Mask.push_back(Idx);
11867 // Bail out if we cannot convert the shuffle pair into a single shuffle.
11868 if (SV1.getNode() && SV1 != CurrentVec)
11871 // Ok. CurrentVec is the right hand side.
11872 // Update the mask accordingly.
11874 Mask.push_back(Idx + NumElts);
11877 // Check if all indices in Mask are Undef. In case, propagate Undef.
11878 bool isUndefMask = true;
11879 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11880 isUndefMask &= Mask[i] < 0;
11883 return DAG.getUNDEF(VT);
11885 if (!SV0.getNode())
11886 SV0 = DAG.getUNDEF(VT);
11887 if (!SV1.getNode())
11888 SV1 = DAG.getUNDEF(VT);
11890 // Avoid introducing shuffles with illegal mask.
11891 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
11892 // Compute the commuted shuffle mask and test again.
11893 for (unsigned i = 0; i != NumElts; ++i) {
11897 else if (idx < (int)NumElts)
11898 Mask[i] = idx + NumElts;
11900 Mask[i] = idx - NumElts;
11903 if (!TLI.isShuffleMaskLegal(Mask, VT))
11906 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
11907 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
11908 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
11909 std::swap(SV0, SV1);
11912 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11913 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11914 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11915 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
11921 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11922 SDValue N0 = N->getOperand(0);
11923 SDValue N2 = N->getOperand(2);
11925 // If the input vector is a concatenation, and the insert replaces
11926 // one of the halves, we can optimize into a single concat_vectors.
11927 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11928 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11929 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11930 EVT VT = N->getValueType(0);
11932 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11933 // (concat_vectors Z, Y)
11935 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11936 N->getOperand(1), N0.getOperand(1));
11938 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11939 // (concat_vectors X, Z)
11940 if (InsIdx == VT.getVectorNumElements()/2)
11941 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11942 N0.getOperand(0), N->getOperand(1));
11948 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11949 /// with the destination vector and a zero vector.
11950 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11951 /// vector_shuffle V, Zero, <0, 4, 2, 4>
11952 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11953 EVT VT = N->getValueType(0);
11955 SDValue LHS = N->getOperand(0);
11956 SDValue RHS = N->getOperand(1);
11957 if (N->getOpcode() == ISD::AND) {
11958 if (RHS.getOpcode() == ISD::BITCAST)
11959 RHS = RHS.getOperand(0);
11960 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11961 SmallVector<int, 8> Indices;
11962 unsigned NumElts = RHS.getNumOperands();
11963 for (unsigned i = 0; i != NumElts; ++i) {
11964 SDValue Elt = RHS.getOperand(i);
11965 if (!isa<ConstantSDNode>(Elt))
11968 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11969 Indices.push_back(i);
11970 else if (cast<ConstantSDNode>(Elt)->isNullValue())
11971 Indices.push_back(NumElts+i);
11976 // Let's see if the target supports this vector_shuffle and make sure
11977 // we're not running after operation legalization where it may have
11978 // custom lowered the vector shuffles.
11979 EVT RVT = RHS.getValueType();
11980 if (LegalOperations || !TLI.isVectorClearMaskLegal(Indices, RVT))
11983 // Return the new VECTOR_SHUFFLE node.
11984 EVT EltVT = RVT.getVectorElementType();
11985 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11986 DAG.getConstant(0, EltVT));
11987 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11988 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11989 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11990 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11997 /// Visit a binary vector operation, like ADD.
11998 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11999 assert(N->getValueType(0).isVector() &&
12000 "SimplifyVBinOp only works on vectors!");
12002 SDValue LHS = N->getOperand(0);
12003 SDValue RHS = N->getOperand(1);
12004 SDValue Shuffle = XformToShuffleWithZero(N);
12005 if (Shuffle.getNode()) return Shuffle;
12007 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12009 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12010 RHS.getOpcode() == ISD::BUILD_VECTOR) {
12011 // Check if both vectors are constants. If not bail out.
12012 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12013 cast<BuildVectorSDNode>(RHS)->isConstant()))
12016 SmallVector<SDValue, 8> Ops;
12017 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12018 SDValue LHSOp = LHS.getOperand(i);
12019 SDValue RHSOp = RHS.getOperand(i);
12021 // Can't fold divide by zero.
12022 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12023 N->getOpcode() == ISD::FDIV) {
12024 if ((RHSOp.getOpcode() == ISD::Constant &&
12025 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
12026 (RHSOp.getOpcode() == ISD::ConstantFP &&
12027 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12031 EVT VT = LHSOp.getValueType();
12032 EVT RVT = RHSOp.getValueType();
12034 // Integer BUILD_VECTOR operands may have types larger than the element
12035 // size (e.g., when the element type is not legal). Prior to type
12036 // legalization, the types may not match between the two BUILD_VECTORS.
12037 // Truncate one of the operands to make them match.
12038 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12039 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12041 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12045 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12047 if (FoldOp.getOpcode() != ISD::UNDEF &&
12048 FoldOp.getOpcode() != ISD::Constant &&
12049 FoldOp.getOpcode() != ISD::ConstantFP)
12051 Ops.push_back(FoldOp);
12052 AddToWorklist(FoldOp.getNode());
12055 if (Ops.size() == LHS.getNumOperands())
12056 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12059 // Type legalization might introduce new shuffles in the DAG.
12060 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12061 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
12062 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12063 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12064 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12065 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12066 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12067 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12069 if (SVN0->getMask().equals(SVN1->getMask())) {
12070 EVT VT = N->getValueType(0);
12071 SDValue UndefVector = LHS.getOperand(1);
12072 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12073 LHS.getOperand(0), RHS.getOperand(0));
12074 AddUsersToWorklist(N);
12075 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
12076 &SVN0->getMask()[0]);
12083 /// Visit a binary vector operation, like FABS/FNEG.
12084 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
12085 assert(N->getValueType(0).isVector() &&
12086 "SimplifyVUnaryOp only works on vectors!");
12088 SDValue N0 = N->getOperand(0);
12090 if (N0.getOpcode() != ISD::BUILD_VECTOR)
12093 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
12094 SmallVector<SDValue, 8> Ops;
12095 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
12096 SDValue Op = N0.getOperand(i);
12097 if (Op.getOpcode() != ISD::UNDEF &&
12098 Op.getOpcode() != ISD::ConstantFP)
12100 EVT EltVT = Op.getValueType();
12101 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
12102 if (FoldOp.getOpcode() != ISD::UNDEF &&
12103 FoldOp.getOpcode() != ISD::ConstantFP)
12105 Ops.push_back(FoldOp);
12106 AddToWorklist(FoldOp.getNode());
12109 if (Ops.size() != N0.getNumOperands())
12112 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
12115 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
12116 SDValue N1, SDValue N2){
12117 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
12119 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
12120 cast<CondCodeSDNode>(N0.getOperand(2))->get());
12122 // If we got a simplified select_cc node back from SimplifySelectCC, then
12123 // break it down into a new SETCC node, and a new SELECT node, and then return
12124 // the SELECT node, since we were called with a SELECT node.
12125 if (SCC.getNode()) {
12126 // Check to see if we got a select_cc back (to turn into setcc/select).
12127 // Otherwise, just return whatever node we got back, like fabs.
12128 if (SCC.getOpcode() == ISD::SELECT_CC) {
12129 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
12131 SCC.getOperand(0), SCC.getOperand(1),
12132 SCC.getOperand(4));
12133 AddToWorklist(SETCC.getNode());
12134 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
12135 SCC.getOperand(2), SCC.getOperand(3));
12143 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
12144 /// being selected between, see if we can simplify the select. Callers of this
12145 /// should assume that TheSelect is deleted if this returns true. As such, they
12146 /// should return the appropriate thing (e.g. the node) back to the top-level of
12147 /// the DAG combiner loop to avoid it being looked at.
12148 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
12151 // Cannot simplify select with vector condition
12152 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
12154 // If this is a select from two identical things, try to pull the operation
12155 // through the select.
12156 if (LHS.getOpcode() != RHS.getOpcode() ||
12157 !LHS.hasOneUse() || !RHS.hasOneUse())
12160 // If this is a load and the token chain is identical, replace the select
12161 // of two loads with a load through a select of the address to load from.
12162 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
12163 // constants have been dropped into the constant pool.
12164 if (LHS.getOpcode() == ISD::LOAD) {
12165 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
12166 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
12168 // Token chains must be identical.
12169 if (LHS.getOperand(0) != RHS.getOperand(0) ||
12170 // Do not let this transformation reduce the number of volatile loads.
12171 LLD->isVolatile() || RLD->isVolatile() ||
12172 // If this is an EXTLOAD, the VT's must match.
12173 LLD->getMemoryVT() != RLD->getMemoryVT() ||
12174 // If this is an EXTLOAD, the kind of extension must match.
12175 (LLD->getExtensionType() != RLD->getExtensionType() &&
12176 // The only exception is if one of the extensions is anyext.
12177 LLD->getExtensionType() != ISD::EXTLOAD &&
12178 RLD->getExtensionType() != ISD::EXTLOAD) ||
12179 // FIXME: this discards src value information. This is
12180 // over-conservative. It would be beneficial to be able to remember
12181 // both potential memory locations. Since we are discarding
12182 // src value info, don't do the transformation if the memory
12183 // locations are not in the default address space.
12184 LLD->getPointerInfo().getAddrSpace() != 0 ||
12185 RLD->getPointerInfo().getAddrSpace() != 0 ||
12186 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
12187 LLD->getBasePtr().getValueType()))
12190 // Check that the select condition doesn't reach either load. If so,
12191 // folding this will induce a cycle into the DAG. If not, this is safe to
12192 // xform, so create a select of the addresses.
12194 if (TheSelect->getOpcode() == ISD::SELECT) {
12195 SDNode *CondNode = TheSelect->getOperand(0).getNode();
12196 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
12197 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
12199 // The loads must not depend on one another.
12200 if (LLD->isPredecessorOf(RLD) ||
12201 RLD->isPredecessorOf(LLD))
12203 Addr = DAG.getSelect(SDLoc(TheSelect),
12204 LLD->getBasePtr().getValueType(),
12205 TheSelect->getOperand(0), LLD->getBasePtr(),
12206 RLD->getBasePtr());
12207 } else { // Otherwise SELECT_CC
12208 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
12209 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
12211 if ((LLD->hasAnyUseOfValue(1) &&
12212 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
12213 (RLD->hasAnyUseOfValue(1) &&
12214 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
12217 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
12218 LLD->getBasePtr().getValueType(),
12219 TheSelect->getOperand(0),
12220 TheSelect->getOperand(1),
12221 LLD->getBasePtr(), RLD->getBasePtr(),
12222 TheSelect->getOperand(4));
12226 // It is safe to replace the two loads if they have different alignments,
12227 // but the new load must be the minimum (most restrictive) alignment of the
12229 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
12230 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
12231 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
12232 Load = DAG.getLoad(TheSelect->getValueType(0),
12234 // FIXME: Discards pointer and AA info.
12235 LLD->getChain(), Addr, MachinePointerInfo(),
12236 LLD->isVolatile(), LLD->isNonTemporal(),
12237 isInvariant, Alignment);
12239 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
12240 RLD->getExtensionType() : LLD->getExtensionType(),
12242 TheSelect->getValueType(0),
12243 // FIXME: Discards pointer and AA info.
12244 LLD->getChain(), Addr, MachinePointerInfo(),
12245 LLD->getMemoryVT(), LLD->isVolatile(),
12246 LLD->isNonTemporal(), isInvariant, Alignment);
12249 // Users of the select now use the result of the load.
12250 CombineTo(TheSelect, Load);
12252 // Users of the old loads now use the new load's chain. We know the
12253 // old-load value is dead now.
12254 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
12255 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
12262 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
12263 /// where 'cond' is the comparison specified by CC.
12264 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
12265 SDValue N2, SDValue N3,
12266 ISD::CondCode CC, bool NotExtCompare) {
12267 // (x ? y : y) -> y.
12268 if (N2 == N3) return N2;
12270 EVT VT = N2.getValueType();
12271 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
12272 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
12273 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
12275 // Determine if the condition we're dealing with is constant
12276 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
12277 N0, N1, CC, DL, false);
12278 if (SCC.getNode()) AddToWorklist(SCC.getNode());
12279 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
12281 // fold select_cc true, x, y -> x
12282 if (SCCC && !SCCC->isNullValue())
12284 // fold select_cc false, x, y -> y
12285 if (SCCC && SCCC->isNullValue())
12288 // Check to see if we can simplify the select into an fabs node
12289 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
12290 // Allow either -0.0 or 0.0
12291 if (CFP->getValueAPF().isZero()) {
12292 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
12293 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
12294 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
12295 N2 == N3.getOperand(0))
12296 return DAG.getNode(ISD::FABS, DL, VT, N0);
12298 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
12299 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
12300 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
12301 N2.getOperand(0) == N3)
12302 return DAG.getNode(ISD::FABS, DL, VT, N3);
12306 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
12307 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
12308 // in it. This is a win when the constant is not otherwise available because
12309 // it replaces two constant pool loads with one. We only do this if the FP
12310 // type is known to be legal, because if it isn't, then we are before legalize
12311 // types an we want the other legalization to happen first (e.g. to avoid
12312 // messing with soft float) and if the ConstantFP is not legal, because if
12313 // it is legal, we may not need to store the FP constant in a constant pool.
12314 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
12315 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
12316 if (TLI.isTypeLegal(N2.getValueType()) &&
12317 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
12318 TargetLowering::Legal &&
12319 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
12320 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
12321 // If both constants have multiple uses, then we won't need to do an
12322 // extra load, they are likely around in registers for other users.
12323 (TV->hasOneUse() || FV->hasOneUse())) {
12324 Constant *Elts[] = {
12325 const_cast<ConstantFP*>(FV->getConstantFPValue()),
12326 const_cast<ConstantFP*>(TV->getConstantFPValue())
12328 Type *FPTy = Elts[0]->getType();
12329 const DataLayout &TD = *TLI.getDataLayout();
12331 // Create a ConstantArray of the two constants.
12332 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
12333 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
12334 TD.getPrefTypeAlignment(FPTy));
12335 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12337 // Get the offsets to the 0 and 1 element of the array so that we can
12338 // select between them.
12339 SDValue Zero = DAG.getIntPtrConstant(0);
12340 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
12341 SDValue One = DAG.getIntPtrConstant(EltSize);
12343 SDValue Cond = DAG.getSetCC(DL,
12344 getSetCCResultType(N0.getValueType()),
12346 AddToWorklist(Cond.getNode());
12347 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
12349 AddToWorklist(CstOffset.getNode());
12350 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
12352 AddToWorklist(CPIdx.getNode());
12353 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
12354 MachinePointerInfo::getConstantPool(), false,
12355 false, false, Alignment);
12360 // Check to see if we can perform the "gzip trick", transforming
12361 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
12362 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
12363 (N1C->isNullValue() || // (a < 0) ? b : 0
12364 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
12365 EVT XType = N0.getValueType();
12366 EVT AType = N2.getValueType();
12367 if (XType.bitsGE(AType)) {
12368 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
12369 // single-bit constant.
12370 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
12371 unsigned ShCtV = N2C->getAPIntValue().logBase2();
12372 ShCtV = XType.getSizeInBits()-ShCtV-1;
12373 SDValue ShCt = DAG.getConstant(ShCtV,
12374 getShiftAmountTy(N0.getValueType()));
12375 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
12377 AddToWorklist(Shift.getNode());
12379 if (XType.bitsGT(AType)) {
12380 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12381 AddToWorklist(Shift.getNode());
12384 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12387 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
12389 DAG.getConstant(XType.getSizeInBits()-1,
12390 getShiftAmountTy(N0.getValueType())));
12391 AddToWorklist(Shift.getNode());
12393 if (XType.bitsGT(AType)) {
12394 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12395 AddToWorklist(Shift.getNode());
12398 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12402 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
12403 // where y is has a single bit set.
12404 // A plaintext description would be, we can turn the SELECT_CC into an AND
12405 // when the condition can be materialized as an all-ones register. Any
12406 // single bit-test can be materialized as an all-ones register with
12407 // shift-left and shift-right-arith.
12408 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
12409 N0->getValueType(0) == VT &&
12410 N1C && N1C->isNullValue() &&
12411 N2C && N2C->isNullValue()) {
12412 SDValue AndLHS = N0->getOperand(0);
12413 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12414 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
12415 // Shift the tested bit over the sign bit.
12416 APInt AndMask = ConstAndRHS->getAPIntValue();
12418 DAG.getConstant(AndMask.countLeadingZeros(),
12419 getShiftAmountTy(AndLHS.getValueType()));
12420 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
12422 // Now arithmetic right shift it all the way over, so the result is either
12423 // all-ones, or zero.
12425 DAG.getConstant(AndMask.getBitWidth()-1,
12426 getShiftAmountTy(Shl.getValueType()));
12427 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
12429 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
12433 // fold select C, 16, 0 -> shl C, 4
12434 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
12435 TLI.getBooleanContents(N0.getValueType()) ==
12436 TargetLowering::ZeroOrOneBooleanContent) {
12438 // If the caller doesn't want us to simplify this into a zext of a compare,
12440 if (NotExtCompare && N2C->getAPIntValue() == 1)
12443 // Get a SetCC of the condition
12444 // NOTE: Don't create a SETCC if it's not legal on this target.
12445 if (!LegalOperations ||
12446 TLI.isOperationLegal(ISD::SETCC,
12447 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
12449 // cast from setcc result type to select result type
12451 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
12453 if (N2.getValueType().bitsLT(SCC.getValueType()))
12454 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
12455 N2.getValueType());
12457 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12458 N2.getValueType(), SCC);
12460 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
12461 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12462 N2.getValueType(), SCC);
12465 AddToWorklist(SCC.getNode());
12466 AddToWorklist(Temp.getNode());
12468 if (N2C->getAPIntValue() == 1)
12471 // shl setcc result by log2 n2c
12472 return DAG.getNode(
12473 ISD::SHL, DL, N2.getValueType(), Temp,
12474 DAG.getConstant(N2C->getAPIntValue().logBase2(),
12475 getShiftAmountTy(Temp.getValueType())));
12479 // Check to see if this is the equivalent of setcc
12480 // FIXME: Turn all of these into setcc if setcc if setcc is legal
12481 // otherwise, go ahead with the folds.
12482 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
12483 EVT XType = N0.getValueType();
12484 if (!LegalOperations ||
12485 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
12486 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
12487 if (Res.getValueType() != VT)
12488 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
12492 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
12493 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
12494 (!LegalOperations ||
12495 TLI.isOperationLegal(ISD::CTLZ, XType))) {
12496 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
12497 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
12498 DAG.getConstant(Log2_32(XType.getSizeInBits()),
12499 getShiftAmountTy(Ctlz.getValueType())));
12501 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
12502 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
12503 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
12504 XType, DAG.getConstant(0, XType), N0);
12505 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
12506 return DAG.getNode(ISD::SRL, DL, XType,
12507 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
12508 DAG.getConstant(XType.getSizeInBits()-1,
12509 getShiftAmountTy(XType)));
12511 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
12512 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
12513 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
12514 DAG.getConstant(XType.getSizeInBits()-1,
12515 getShiftAmountTy(N0.getValueType())));
12516 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
12520 // Check to see if this is an integer abs.
12521 // select_cc setg[te] X, 0, X, -X ->
12522 // select_cc setgt X, -1, X, -X ->
12523 // select_cc setl[te] X, 0, -X, X ->
12524 // select_cc setlt X, 1, -X, X ->
12525 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
12527 ConstantSDNode *SubC = nullptr;
12528 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
12529 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
12530 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
12531 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
12532 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
12533 (N1C->isOne() && CC == ISD::SETLT)) &&
12534 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
12535 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
12537 EVT XType = N0.getValueType();
12538 if (SubC && SubC->isNullValue() && XType.isInteger()) {
12539 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
12541 DAG.getConstant(XType.getSizeInBits()-1,
12542 getShiftAmountTy(N0.getValueType())));
12543 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
12545 AddToWorklist(Shift.getNode());
12546 AddToWorklist(Add.getNode());
12547 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
12554 /// This is a stub for TargetLowering::SimplifySetCC.
12555 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
12556 SDValue N1, ISD::CondCode Cond,
12557 SDLoc DL, bool foldBooleans) {
12558 TargetLowering::DAGCombinerInfo
12559 DagCombineInfo(DAG, Level, false, this);
12560 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
12563 /// Given an ISD::SDIV node expressing a divide by constant, return
12564 /// a DAG expression to select that will generate the same value by multiplying
12565 /// by a magic number.
12566 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12567 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
12568 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12572 // Avoid division by zero.
12573 if (!C->getAPIntValue())
12576 std::vector<SDNode*> Built;
12578 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12580 for (SDNode *N : Built)
12585 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
12586 /// DAG expression that will generate the same value by right shifting.
12587 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
12588 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12592 // Avoid division by zero.
12593 if (!C->getAPIntValue())
12596 std::vector<SDNode *> Built;
12597 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
12599 for (SDNode *N : Built)
12604 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
12605 /// expression that will generate the same value by multiplying by a magic
12607 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12608 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
12609 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12613 // Avoid division by zero.
12614 if (!C->getAPIntValue())
12617 std::vector<SDNode*> Built;
12619 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12621 for (SDNode *N : Built)
12626 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
12627 if (Level >= AfterLegalizeDAG)
12630 // Expose the DAG combiner to the target combiner implementations.
12631 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12633 unsigned Iterations = 0;
12634 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
12636 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12637 // For the reciprocal, we need to find the zero of the function:
12638 // F(X) = A X - 1 [which has a zero at X = 1/A]
12640 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
12641 // does not require additional intermediate precision]
12642 EVT VT = Op.getValueType();
12644 SDValue FPOne = DAG.getConstantFP(1.0, VT);
12646 AddToWorklist(Est.getNode());
12648 // Newton iterations: Est = Est + Est (1 - Arg * Est)
12649 for (unsigned i = 0; i < Iterations; ++i) {
12650 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
12651 AddToWorklist(NewEst.getNode());
12653 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
12654 AddToWorklist(NewEst.getNode());
12656 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12657 AddToWorklist(NewEst.getNode());
12659 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
12660 AddToWorklist(Est.getNode());
12669 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12670 /// For the reciprocal sqrt, we need to find the zero of the function:
12671 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12673 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12674 /// As a result, we precompute A/2 prior to the iteration loop.
12675 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
12676 unsigned Iterations) {
12677 EVT VT = Arg.getValueType();
12679 SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
12681 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12682 // this entire sequence requires only one FP constant.
12683 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12684 AddToWorklist(HalfArg.getNode());
12686 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12687 AddToWorklist(HalfArg.getNode());
12689 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12690 for (unsigned i = 0; i < Iterations; ++i) {
12691 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12692 AddToWorklist(NewEst.getNode());
12694 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12695 AddToWorklist(NewEst.getNode());
12697 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
12698 AddToWorklist(NewEst.getNode());
12700 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12701 AddToWorklist(Est.getNode());
12706 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12707 /// For the reciprocal sqrt, we need to find the zero of the function:
12708 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12710 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
12711 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
12712 unsigned Iterations) {
12713 EVT VT = Arg.getValueType();
12715 SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
12716 SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
12718 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
12719 for (unsigned i = 0; i < Iterations; ++i) {
12720 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
12721 AddToWorklist(HalfEst.getNode());
12723 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12724 AddToWorklist(Est.getNode());
12726 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
12727 AddToWorklist(Est.getNode());
12729 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
12730 AddToWorklist(Est.getNode());
12732 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
12733 AddToWorklist(Est.getNode());
12738 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
12739 if (Level >= AfterLegalizeDAG)
12742 // Expose the DAG combiner to the target combiner implementations.
12743 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12744 unsigned Iterations = 0;
12745 bool UseOneConstNR = false;
12746 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
12747 AddToWorklist(Est.getNode());
12749 Est = UseOneConstNR ?
12750 BuildRsqrtNROneConst(Op, Est, Iterations) :
12751 BuildRsqrtNRTwoConst(Op, Est, Iterations);
12759 /// Return true if base is a frame index, which is known not to alias with
12760 /// anything but itself. Provides base object and offset as results.
12761 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
12762 const GlobalValue *&GV, const void *&CV) {
12763 // Assume it is a primitive operation.
12764 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
12766 // If it's an adding a simple constant then integrate the offset.
12767 if (Base.getOpcode() == ISD::ADD) {
12768 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
12769 Base = Base.getOperand(0);
12770 Offset += C->getZExtValue();
12774 // Return the underlying GlobalValue, and update the Offset. Return false
12775 // for GlobalAddressSDNode since the same GlobalAddress may be represented
12776 // by multiple nodes with different offsets.
12777 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
12778 GV = G->getGlobal();
12779 Offset += G->getOffset();
12783 // Return the underlying Constant value, and update the Offset. Return false
12784 // for ConstantSDNodes since the same constant pool entry may be represented
12785 // by multiple nodes with different offsets.
12786 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
12787 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
12788 : (const void *)C->getConstVal();
12789 Offset += C->getOffset();
12792 // If it's any of the following then it can't alias with anything but itself.
12793 return isa<FrameIndexSDNode>(Base);
12796 /// Return true if there is any possibility that the two addresses overlap.
12797 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
12798 // If they are the same then they must be aliases.
12799 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
12801 // If they are both volatile then they cannot be reordered.
12802 if (Op0->isVolatile() && Op1->isVolatile()) return true;
12804 // Gather base node and offset information.
12805 SDValue Base1, Base2;
12806 int64_t Offset1, Offset2;
12807 const GlobalValue *GV1, *GV2;
12808 const void *CV1, *CV2;
12809 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
12810 Base1, Offset1, GV1, CV1);
12811 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
12812 Base2, Offset2, GV2, CV2);
12814 // If they have a same base address then check to see if they overlap.
12815 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
12816 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12817 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12819 // It is possible for different frame indices to alias each other, mostly
12820 // when tail call optimization reuses return address slots for arguments.
12821 // To catch this case, look up the actual index of frame indices to compute
12822 // the real alias relationship.
12823 if (isFrameIndex1 && isFrameIndex2) {
12824 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12825 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
12826 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
12827 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12828 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12831 // Otherwise, if we know what the bases are, and they aren't identical, then
12832 // we know they cannot alias.
12833 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
12836 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
12837 // compared to the size and offset of the access, we may be able to prove they
12838 // do not alias. This check is conservative for now to catch cases created by
12839 // splitting vector types.
12840 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
12841 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
12842 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
12843 Op1->getMemoryVT().getSizeInBits() >> 3) &&
12844 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
12845 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
12846 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
12848 // There is no overlap between these relatively aligned accesses of similar
12849 // size, return no alias.
12850 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
12851 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
12855 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
12857 : DAG.getSubtarget().useAA();
12859 if (CombinerAAOnlyFunc.getNumOccurrences() &&
12860 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12864 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
12865 // Use alias analysis information.
12866 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
12867 Op1->getSrcValueOffset());
12868 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
12869 Op0->getSrcValueOffset() - MinOffset;
12870 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
12871 Op1->getSrcValueOffset() - MinOffset;
12872 AliasAnalysis::AliasResult AAResult =
12873 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
12875 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
12876 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
12878 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
12879 if (AAResult == AliasAnalysis::NoAlias)
12883 // Otherwise we have to assume they alias.
12887 /// Walk up chain skipping non-aliasing memory nodes,
12888 /// looking for aliasing nodes and adding them to the Aliases vector.
12889 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
12890 SmallVectorImpl<SDValue> &Aliases) {
12891 SmallVector<SDValue, 8> Chains; // List of chains to visit.
12892 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
12894 // Get alias information for node.
12895 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
12898 Chains.push_back(OriginalChain);
12899 unsigned Depth = 0;
12901 // Look at each chain and determine if it is an alias. If so, add it to the
12902 // aliases list. If not, then continue up the chain looking for the next
12904 while (!Chains.empty()) {
12905 SDValue Chain = Chains.back();
12908 // For TokenFactor nodes, look at each operand and only continue up the
12909 // chain until we find two aliases. If we've seen two aliases, assume we'll
12910 // find more and revert to original chain since the xform is unlikely to be
12913 // FIXME: The depth check could be made to return the last non-aliasing
12914 // chain we found before we hit a tokenfactor rather than the original
12916 if (Depth > 6 || Aliases.size() == 2) {
12918 Aliases.push_back(OriginalChain);
12922 // Don't bother if we've been before.
12923 if (!Visited.insert(Chain.getNode()).second)
12926 switch (Chain.getOpcode()) {
12927 case ISD::EntryToken:
12928 // Entry token is ideal chain operand, but handled in FindBetterChain.
12933 // Get alias information for Chain.
12934 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
12935 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
12937 // If chain is alias then stop here.
12938 if (!(IsLoad && IsOpLoad) &&
12939 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
12940 Aliases.push_back(Chain);
12942 // Look further up the chain.
12943 Chains.push_back(Chain.getOperand(0));
12949 case ISD::TokenFactor:
12950 // We have to check each of the operands of the token factor for "small"
12951 // token factors, so we queue them up. Adding the operands to the queue
12952 // (stack) in reverse order maintains the original order and increases the
12953 // likelihood that getNode will find a matching token factor (CSE.)
12954 if (Chain.getNumOperands() > 16) {
12955 Aliases.push_back(Chain);
12958 for (unsigned n = Chain.getNumOperands(); n;)
12959 Chains.push_back(Chain.getOperand(--n));
12964 // For all other instructions we will just have to take what we can get.
12965 Aliases.push_back(Chain);
12970 // We need to be careful here to also search for aliases through the
12971 // value operand of a store, etc. Consider the following situation:
12973 // L1 = load Token1, %52
12974 // S1 = store Token1, L1, %51
12975 // L2 = load Token1, %52+8
12976 // S2 = store Token1, L2, %51+8
12977 // Token2 = Token(S1, S2)
12978 // L3 = load Token2, %53
12979 // S3 = store Token2, L3, %52
12980 // L4 = load Token2, %53+8
12981 // S4 = store Token2, L4, %52+8
12982 // If we search for aliases of S3 (which loads address %52), and we look
12983 // only through the chain, then we'll miss the trivial dependence on L1
12984 // (which also loads from %52). We then might change all loads and
12985 // stores to use Token1 as their chain operand, which could result in
12986 // copying %53 into %52 before copying %52 into %51 (which should
12989 // The problem is, however, that searching for such data dependencies
12990 // can become expensive, and the cost is not directly related to the
12991 // chain depth. Instead, we'll rule out such configurations here by
12992 // insisting that we've visited all chain users (except for users
12993 // of the original chain, which is not necessary). When doing this,
12994 // we need to look through nodes we don't care about (otherwise, things
12995 // like register copies will interfere with trivial cases).
12997 SmallVector<const SDNode *, 16> Worklist;
12998 for (const SDNode *N : Visited)
12999 if (N != OriginalChain.getNode())
13000 Worklist.push_back(N);
13002 while (!Worklist.empty()) {
13003 const SDNode *M = Worklist.pop_back_val();
13005 // We have already visited M, and want to make sure we've visited any uses
13006 // of M that we care about. For uses that we've not visisted, and don't
13007 // care about, queue them to the worklist.
13009 for (SDNode::use_iterator UI = M->use_begin(),
13010 UIE = M->use_end(); UI != UIE; ++UI)
13011 if (UI.getUse().getValueType() == MVT::Other &&
13012 Visited.insert(*UI).second) {
13013 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13014 // We've not visited this use, and we care about it (it could have an
13015 // ordering dependency with the original node).
13017 Aliases.push_back(OriginalChain);
13021 // We've not visited this use, but we don't care about it. Mark it as
13022 // visited and enqueue it to the worklist.
13023 Worklist.push_back(*UI);
13028 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13029 /// (aliasing node.)
13030 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13031 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
13033 // Accumulate all the aliases to this node.
13034 GatherAllAliases(N, OldChain, Aliases);
13036 // If no operands then chain to entry token.
13037 if (Aliases.size() == 0)
13038 return DAG.getEntryNode();
13040 // If a single operand then chain to it. We don't need to revisit it.
13041 if (Aliases.size() == 1)
13044 // Construct a custom tailored token factor.
13045 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13048 /// This is the entry point for the file.
13049 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13050 CodeGenOpt::Level OptLevel) {
13051 /// This is the main entry point to this class.
13052 DAGCombiner(*this, AA, OptLevel).Run(Level);