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 visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
250 SDValue visitOR(SDNode *N);
251 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
252 SDValue visitXOR(SDNode *N);
253 SDValue SimplifyVBinOp(SDNode *N);
254 SDValue visitSHL(SDNode *N);
255 SDValue visitSRA(SDNode *N);
256 SDValue visitSRL(SDNode *N);
257 SDValue visitRotate(SDNode *N);
258 SDValue visitBSWAP(SDNode *N);
259 SDValue visitCTLZ(SDNode *N);
260 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
261 SDValue visitCTTZ(SDNode *N);
262 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
263 SDValue visitCTPOP(SDNode *N);
264 SDValue visitSELECT(SDNode *N);
265 SDValue visitVSELECT(SDNode *N);
266 SDValue visitSELECT_CC(SDNode *N);
267 SDValue visitSETCC(SDNode *N);
268 SDValue visitSIGN_EXTEND(SDNode *N);
269 SDValue visitZERO_EXTEND(SDNode *N);
270 SDValue visitANY_EXTEND(SDNode *N);
271 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
272 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
273 SDValue visitTRUNCATE(SDNode *N);
274 SDValue visitBITCAST(SDNode *N);
275 SDValue visitBUILD_PAIR(SDNode *N);
276 SDValue visitFADD(SDNode *N);
277 SDValue visitFSUB(SDNode *N);
278 SDValue visitFMUL(SDNode *N);
279 SDValue visitFMA(SDNode *N);
280 SDValue visitFDIV(SDNode *N);
281 SDValue visitFREM(SDNode *N);
282 SDValue visitFSQRT(SDNode *N);
283 SDValue visitFCOPYSIGN(SDNode *N);
284 SDValue visitSINT_TO_FP(SDNode *N);
285 SDValue visitUINT_TO_FP(SDNode *N);
286 SDValue visitFP_TO_SINT(SDNode *N);
287 SDValue visitFP_TO_UINT(SDNode *N);
288 SDValue visitFP_ROUND(SDNode *N);
289 SDValue visitFP_ROUND_INREG(SDNode *N);
290 SDValue visitFP_EXTEND(SDNode *N);
291 SDValue visitFNEG(SDNode *N);
292 SDValue visitFABS(SDNode *N);
293 SDValue visitFCEIL(SDNode *N);
294 SDValue visitFTRUNC(SDNode *N);
295 SDValue visitFFLOOR(SDNode *N);
296 SDValue visitFMINNUM(SDNode *N);
297 SDValue visitFMAXNUM(SDNode *N);
298 SDValue visitBRCOND(SDNode *N);
299 SDValue visitBR_CC(SDNode *N);
300 SDValue visitLOAD(SDNode *N);
301 SDValue visitSTORE(SDNode *N);
302 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
303 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
304 SDValue visitBUILD_VECTOR(SDNode *N);
305 SDValue visitCONCAT_VECTORS(SDNode *N);
306 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
307 SDValue visitVECTOR_SHUFFLE(SDNode *N);
308 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
309 SDValue visitINSERT_SUBVECTOR(SDNode *N);
310 SDValue visitMLOAD(SDNode *N);
311 SDValue visitMSTORE(SDNode *N);
312 SDValue visitMGATHER(SDNode *N);
313 SDValue visitMSCATTER(SDNode *N);
314 SDValue visitFP_TO_FP16(SDNode *N);
316 SDValue visitFADDForFMACombine(SDNode *N);
317 SDValue visitFSUBForFMACombine(SDNode *N);
319 SDValue XformToShuffleWithZero(SDNode *N);
320 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
322 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
324 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
325 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
326 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
327 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
328 SDValue N3, ISD::CondCode CC,
329 bool NotExtCompare = false);
330 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
331 SDLoc DL, bool foldBooleans = true);
333 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
335 bool isOneUseSetCC(SDValue N) const;
337 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
339 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
340 SDValue CombineExtLoad(SDNode *N);
341 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
342 SDValue BuildSDIV(SDNode *N);
343 SDValue BuildSDIVPow2(SDNode *N);
344 SDValue BuildUDIV(SDNode *N);
345 SDValue BuildReciprocalEstimate(SDValue Op);
346 SDValue BuildRsqrtEstimate(SDValue Op);
347 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
348 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
349 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
350 bool DemandHighBits = true);
351 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
352 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
353 SDValue InnerPos, SDValue InnerNeg,
354 unsigned PosOpcode, unsigned NegOpcode,
356 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
357 SDValue ReduceLoadWidth(SDNode *N);
358 SDValue ReduceLoadOpStoreWidth(SDNode *N);
359 SDValue TransformFPLoadStorePair(SDNode *N);
360 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
361 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
363 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
365 /// Walk up chain skipping non-aliasing memory nodes,
366 /// looking for aliasing nodes and adding them to the Aliases vector.
367 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
368 SmallVectorImpl<SDValue> &Aliases);
370 /// Return true if there is any possibility that the two addresses overlap.
371 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
373 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
374 /// chain (aliasing node.)
375 SDValue FindBetterChain(SDNode *N, SDValue Chain);
377 /// Holds a pointer to an LSBaseSDNode as well as information on where it
378 /// is located in a sequence of memory operations connected by a chain.
380 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
381 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
382 // Ptr to the mem node.
383 LSBaseSDNode *MemNode;
384 // Offset from the base ptr.
385 int64_t OffsetFromBase;
386 // What is the sequence number of this mem node.
387 // Lowest mem operand in the DAG starts at zero.
388 unsigned SequenceNum;
391 /// This is a helper function for MergeConsecutiveStores. When the source
392 /// elements of the consecutive stores are all constants or all extracted
393 /// vector elements, try to merge them into one larger store.
394 /// \return True if a merged store was created.
395 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
396 EVT MemVT, unsigned NumElem,
397 bool IsConstantSrc, bool UseVector);
399 /// Merge consecutive store operations into a wide store.
400 /// This optimization uses wide integers or vectors when possible.
401 /// \return True if some memory operations were changed.
402 bool MergeConsecutiveStores(StoreSDNode *N);
404 /// \brief Try to transform a truncation where C is a constant:
405 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
407 /// \p N needs to be a truncation and its first operand an AND. Other
408 /// requirements are checked by the function (e.g. that trunc is
409 /// single-use) and if missed an empty SDValue is returned.
410 SDValue distributeTruncateThroughAnd(SDNode *N);
413 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
414 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
415 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
416 auto *F = DAG.getMachineFunction().getFunction();
417 ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
418 F->hasFnAttribute(Attribute::MinSize);
421 /// Runs the dag combiner on all nodes in the work list
422 void Run(CombineLevel AtLevel);
424 SelectionDAG &getDAG() const { return DAG; }
426 /// Returns a type large enough to hold any valid shift amount - before type
427 /// legalization these can be huge.
428 EVT getShiftAmountTy(EVT LHSTy) {
429 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
430 if (LHSTy.isVector())
432 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
433 : TLI.getPointerTy();
436 /// This method returns true if we are running before type legalization or
437 /// if the specified VT is legal.
438 bool isTypeLegal(const EVT &VT) {
439 if (!LegalTypes) return true;
440 return TLI.isTypeLegal(VT);
443 /// Convenience wrapper around TargetLowering::getSetCCResultType
444 EVT getSetCCResultType(EVT VT) const {
445 return TLI.getSetCCResultType(*DAG.getContext(), VT);
452 /// This class is a DAGUpdateListener that removes any deleted
453 /// nodes from the worklist.
454 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
457 explicit WorklistRemover(DAGCombiner &dc)
458 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
460 void NodeDeleted(SDNode *N, SDNode *E) override {
461 DC.removeFromWorklist(N);
466 //===----------------------------------------------------------------------===//
467 // TargetLowering::DAGCombinerInfo implementation
468 //===----------------------------------------------------------------------===//
470 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
471 ((DAGCombiner*)DC)->AddToWorklist(N);
474 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
475 ((DAGCombiner*)DC)->removeFromWorklist(N);
478 SDValue TargetLowering::DAGCombinerInfo::
479 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
480 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
483 SDValue TargetLowering::DAGCombinerInfo::
484 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
485 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
489 SDValue TargetLowering::DAGCombinerInfo::
490 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
491 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
494 void TargetLowering::DAGCombinerInfo::
495 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
496 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
499 //===----------------------------------------------------------------------===//
501 //===----------------------------------------------------------------------===//
503 void DAGCombiner::deleteAndRecombine(SDNode *N) {
504 removeFromWorklist(N);
506 // If the operands of this node are only used by the node, they will now be
507 // dead. Make sure to re-visit them and recursively delete dead nodes.
508 for (const SDValue &Op : N->ops())
509 // For an operand generating multiple values, one of the values may
510 // become dead allowing further simplification (e.g. split index
511 // arithmetic from an indexed load).
512 if (Op->hasOneUse() || Op->getNumValues() > 1)
513 AddToWorklist(Op.getNode());
518 /// Return 1 if we can compute the negated form of the specified expression for
519 /// the same cost as the expression itself, or 2 if we can compute the negated
520 /// form more cheaply than the expression itself.
521 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
522 const TargetLowering &TLI,
523 const TargetOptions *Options,
524 unsigned Depth = 0) {
525 // fneg is removable even if it has multiple uses.
526 if (Op.getOpcode() == ISD::FNEG) return 2;
528 // Don't allow anything with multiple uses.
529 if (!Op.hasOneUse()) return 0;
531 // Don't recurse exponentially.
532 if (Depth > 6) return 0;
534 switch (Op.getOpcode()) {
535 default: return false;
536 case ISD::ConstantFP:
537 // Don't invert constant FP values after legalize. The negated constant
538 // isn't necessarily legal.
539 return LegalOperations ? 0 : 1;
541 // FIXME: determine better conditions for this xform.
542 if (!Options->UnsafeFPMath) return 0;
544 // After operation legalization, it might not be legal to create new FSUBs.
545 if (LegalOperations &&
546 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
549 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
550 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
553 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
554 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
557 // We can't turn -(A-B) into B-A when we honor signed zeros.
558 if (!Options->UnsafeFPMath) return 0;
560 // fold (fneg (fsub A, B)) -> (fsub B, A)
565 if (Options->HonorSignDependentRoundingFPMath()) return 0;
567 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
568 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
572 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
578 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
583 /// If isNegatibleForFree returns true, return the newly negated expression.
584 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
585 bool LegalOperations, unsigned Depth = 0) {
586 const TargetOptions &Options = DAG.getTarget().Options;
587 // fneg is removable even if it has multiple uses.
588 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
590 // Don't allow anything with multiple uses.
591 assert(Op.hasOneUse() && "Unknown reuse!");
593 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
594 switch (Op.getOpcode()) {
595 default: llvm_unreachable("Unknown code");
596 case ISD::ConstantFP: {
597 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
599 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
602 // FIXME: determine better conditions for this xform.
603 assert(Options.UnsafeFPMath);
605 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
606 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
607 DAG.getTargetLoweringInfo(), &Options, Depth+1))
608 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
609 GetNegatedExpression(Op.getOperand(0), DAG,
610 LegalOperations, Depth+1),
612 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
613 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
614 GetNegatedExpression(Op.getOperand(1), DAG,
615 LegalOperations, Depth+1),
618 // We can't turn -(A-B) into B-A when we honor signed zeros.
619 assert(Options.UnsafeFPMath);
621 // fold (fneg (fsub 0, B)) -> B
622 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
624 return Op.getOperand(1);
626 // fold (fneg (fsub A, B)) -> (fsub B, A)
627 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
628 Op.getOperand(1), Op.getOperand(0));
632 assert(!Options.HonorSignDependentRoundingFPMath());
634 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
635 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
636 DAG.getTargetLoweringInfo(), &Options, Depth+1))
637 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
638 GetNegatedExpression(Op.getOperand(0), DAG,
639 LegalOperations, Depth+1),
642 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
643 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
645 GetNegatedExpression(Op.getOperand(1), DAG,
646 LegalOperations, Depth+1));
650 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
651 GetNegatedExpression(Op.getOperand(0), DAG,
652 LegalOperations, Depth+1));
654 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
655 GetNegatedExpression(Op.getOperand(0), DAG,
656 LegalOperations, Depth+1),
661 // Return true if this node is a setcc, or is a select_cc
662 // that selects between the target values used for true and false, making it
663 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
664 // the appropriate nodes based on the type of node we are checking. This
665 // simplifies life a bit for the callers.
666 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
668 if (N.getOpcode() == ISD::SETCC) {
669 LHS = N.getOperand(0);
670 RHS = N.getOperand(1);
671 CC = N.getOperand(2);
675 if (N.getOpcode() != ISD::SELECT_CC ||
676 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
677 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
680 if (TLI.getBooleanContents(N.getValueType()) ==
681 TargetLowering::UndefinedBooleanContent)
684 LHS = N.getOperand(0);
685 RHS = N.getOperand(1);
686 CC = N.getOperand(4);
690 /// Return true if this is a SetCC-equivalent operation with only one use.
691 /// If this is true, it allows the users to invert the operation for free when
692 /// it is profitable to do so.
693 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
695 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
700 /// Returns true if N is a BUILD_VECTOR node whose
701 /// elements are all the same constant or undefined.
702 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
703 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
708 unsigned SplatBitSize;
710 EVT EltVT = N->getValueType(0).getVectorElementType();
711 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
713 EltVT.getSizeInBits() >= SplatBitSize);
716 // \brief Returns the SDNode if it is a constant integer BuildVector
717 // or constant integer.
718 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
719 if (isa<ConstantSDNode>(N))
721 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
726 // \brief Returns the SDNode if it is a constant float BuildVector
727 // or constant float.
728 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
729 if (isa<ConstantFPSDNode>(N))
731 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
736 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
738 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
739 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
742 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
743 BitVector UndefElements;
744 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
746 // BuildVectors can truncate their operands. Ignore that case here.
747 // FIXME: We blindly ignore splats which include undef which is overly
749 if (CN && UndefElements.none() &&
750 CN->getValueType(0) == N.getValueType().getScalarType())
757 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
759 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
760 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
763 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
764 BitVector UndefElements;
765 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
767 if (CN && UndefElements.none())
774 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
775 SDValue N0, SDValue N1) {
776 EVT VT = N0.getValueType();
777 if (N0.getOpcode() == Opc) {
778 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
779 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
780 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
781 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
782 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
785 if (N0.hasOneUse()) {
786 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
788 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
789 if (!OpNode.getNode())
791 AddToWorklist(OpNode.getNode());
792 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
797 if (N1.getOpcode() == Opc) {
798 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
799 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
800 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
801 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
802 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
805 if (N1.hasOneUse()) {
806 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
808 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
809 if (!OpNode.getNode())
811 AddToWorklist(OpNode.getNode());
812 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
820 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
822 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
824 DEBUG(dbgs() << "\nReplacing.1 ";
826 dbgs() << "\nWith: ";
827 To[0].getNode()->dump(&DAG);
828 dbgs() << " and " << NumTo-1 << " other values\n");
829 for (unsigned i = 0, e = NumTo; i != e; ++i)
830 assert((!To[i].getNode() ||
831 N->getValueType(i) == To[i].getValueType()) &&
832 "Cannot combine value to value of different type!");
834 WorklistRemover DeadNodes(*this);
835 DAG.ReplaceAllUsesWith(N, To);
837 // Push the new nodes and any users onto the worklist
838 for (unsigned i = 0, e = NumTo; i != e; ++i) {
839 if (To[i].getNode()) {
840 AddToWorklist(To[i].getNode());
841 AddUsersToWorklist(To[i].getNode());
846 // Finally, if the node is now dead, remove it from the graph. The node
847 // may not be dead if the replacement process recursively simplified to
848 // something else needing this node.
850 deleteAndRecombine(N);
851 return SDValue(N, 0);
855 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
856 // Replace all uses. If any nodes become isomorphic to other nodes and
857 // are deleted, make sure to remove them from our worklist.
858 WorklistRemover DeadNodes(*this);
859 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
861 // Push the new node and any (possibly new) users onto the worklist.
862 AddToWorklist(TLO.New.getNode());
863 AddUsersToWorklist(TLO.New.getNode());
865 // Finally, if the node is now dead, remove it from the graph. The node
866 // may not be dead if the replacement process recursively simplified to
867 // something else needing this node.
868 if (TLO.Old.getNode()->use_empty())
869 deleteAndRecombine(TLO.Old.getNode());
872 /// Check the specified integer node value to see if it can be simplified or if
873 /// things it uses can be simplified by bit propagation. If so, return true.
874 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
875 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
876 APInt KnownZero, KnownOne;
877 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
881 AddToWorklist(Op.getNode());
883 // Replace the old value with the new one.
885 DEBUG(dbgs() << "\nReplacing.2 ";
886 TLO.Old.getNode()->dump(&DAG);
887 dbgs() << "\nWith: ";
888 TLO.New.getNode()->dump(&DAG);
891 CommitTargetLoweringOpt(TLO);
895 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
897 EVT VT = Load->getValueType(0);
898 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
900 DEBUG(dbgs() << "\nReplacing.9 ";
902 dbgs() << "\nWith: ";
903 Trunc.getNode()->dump(&DAG);
905 WorklistRemover DeadNodes(*this);
906 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
907 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
908 deleteAndRecombine(Load);
909 AddToWorklist(Trunc.getNode());
912 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
915 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
916 EVT MemVT = LD->getMemoryVT();
917 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
918 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
920 : LD->getExtensionType();
922 return DAG.getExtLoad(ExtType, dl, PVT,
923 LD->getChain(), LD->getBasePtr(),
924 MemVT, LD->getMemOperand());
927 unsigned Opc = Op.getOpcode();
930 case ISD::AssertSext:
931 return DAG.getNode(ISD::AssertSext, dl, PVT,
932 SExtPromoteOperand(Op.getOperand(0), PVT),
934 case ISD::AssertZext:
935 return DAG.getNode(ISD::AssertZext, dl, PVT,
936 ZExtPromoteOperand(Op.getOperand(0), PVT),
938 case ISD::Constant: {
940 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
941 return DAG.getNode(ExtOpc, dl, PVT, Op);
945 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
947 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
950 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
951 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
953 EVT OldVT = Op.getValueType();
955 bool Replace = false;
956 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
957 if (!NewOp.getNode())
959 AddToWorklist(NewOp.getNode());
962 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
963 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
964 DAG.getValueType(OldVT));
967 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
968 EVT OldVT = Op.getValueType();
970 bool Replace = false;
971 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
972 if (!NewOp.getNode())
974 AddToWorklist(NewOp.getNode());
977 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
978 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
981 /// Promote the specified integer binary operation if the target indicates it is
982 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
983 /// i32 since i16 instructions are longer.
984 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
985 if (!LegalOperations)
988 EVT VT = Op.getValueType();
989 if (VT.isVector() || !VT.isInteger())
992 // If operation type is 'undesirable', e.g. i16 on x86, consider
994 unsigned Opc = Op.getOpcode();
995 if (TLI.isTypeDesirableForOp(Opc, VT))
999 // Consult target whether it is a good idea to promote this operation and
1000 // what's the right type to promote it to.
1001 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1002 assert(PVT != VT && "Don't know what type to promote to!");
1004 bool Replace0 = false;
1005 SDValue N0 = Op.getOperand(0);
1006 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1010 bool Replace1 = false;
1011 SDValue N1 = Op.getOperand(1);
1016 NN1 = PromoteOperand(N1, PVT, Replace1);
1021 AddToWorklist(NN0.getNode());
1023 AddToWorklist(NN1.getNode());
1026 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1028 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1030 DEBUG(dbgs() << "\nPromoting ";
1031 Op.getNode()->dump(&DAG));
1033 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1034 DAG.getNode(Opc, dl, PVT, NN0, NN1));
1039 /// Promote the specified integer shift operation if the target indicates it is
1040 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1041 /// i32 since i16 instructions are longer.
1042 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1043 if (!LegalOperations)
1046 EVT VT = Op.getValueType();
1047 if (VT.isVector() || !VT.isInteger())
1050 // If operation type is 'undesirable', e.g. i16 on x86, consider
1052 unsigned Opc = Op.getOpcode();
1053 if (TLI.isTypeDesirableForOp(Opc, VT))
1057 // Consult target whether it is a good idea to promote this operation and
1058 // what's the right type to promote it to.
1059 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1060 assert(PVT != VT && "Don't know what type to promote to!");
1062 bool Replace = false;
1063 SDValue N0 = Op.getOperand(0);
1064 if (Opc == ISD::SRA)
1065 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1066 else if (Opc == ISD::SRL)
1067 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1069 N0 = PromoteOperand(N0, PVT, Replace);
1073 AddToWorklist(N0.getNode());
1075 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1077 DEBUG(dbgs() << "\nPromoting ";
1078 Op.getNode()->dump(&DAG));
1080 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1081 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1086 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1087 if (!LegalOperations)
1090 EVT VT = Op.getValueType();
1091 if (VT.isVector() || !VT.isInteger())
1094 // If operation type is 'undesirable', e.g. i16 on x86, consider
1096 unsigned Opc = Op.getOpcode();
1097 if (TLI.isTypeDesirableForOp(Opc, VT))
1101 // Consult target whether it is a good idea to promote this operation and
1102 // what's the right type to promote it to.
1103 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1104 assert(PVT != VT && "Don't know what type to promote to!");
1105 // fold (aext (aext x)) -> (aext x)
1106 // fold (aext (zext x)) -> (zext x)
1107 // fold (aext (sext x)) -> (sext x)
1108 DEBUG(dbgs() << "\nPromoting ";
1109 Op.getNode()->dump(&DAG));
1110 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1115 bool DAGCombiner::PromoteLoad(SDValue Op) {
1116 if (!LegalOperations)
1119 EVT VT = Op.getValueType();
1120 if (VT.isVector() || !VT.isInteger())
1123 // If operation type is 'undesirable', e.g. i16 on x86, consider
1125 unsigned Opc = Op.getOpcode();
1126 if (TLI.isTypeDesirableForOp(Opc, VT))
1130 // Consult target whether it is a good idea to promote this operation and
1131 // what's the right type to promote it to.
1132 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1133 assert(PVT != VT && "Don't know what type to promote to!");
1136 SDNode *N = Op.getNode();
1137 LoadSDNode *LD = cast<LoadSDNode>(N);
1138 EVT MemVT = LD->getMemoryVT();
1139 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1140 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1142 : LD->getExtensionType();
1143 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1144 LD->getChain(), LD->getBasePtr(),
1145 MemVT, LD->getMemOperand());
1146 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1148 DEBUG(dbgs() << "\nPromoting ";
1151 Result.getNode()->dump(&DAG);
1153 WorklistRemover DeadNodes(*this);
1154 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1155 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1156 deleteAndRecombine(N);
1157 AddToWorklist(Result.getNode());
1163 /// \brief Recursively delete a node which has no uses and any operands for
1164 /// which it is the only use.
1166 /// Note that this both deletes the nodes and removes them from the worklist.
1167 /// It also adds any nodes who have had a user deleted to the worklist as they
1168 /// may now have only one use and subject to other combines.
1169 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1170 if (!N->use_empty())
1173 SmallSetVector<SDNode *, 16> Nodes;
1176 N = Nodes.pop_back_val();
1180 if (N->use_empty()) {
1181 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1182 Nodes.insert(N->getOperand(i).getNode());
1184 removeFromWorklist(N);
1189 } while (!Nodes.empty());
1193 //===----------------------------------------------------------------------===//
1194 // Main DAG Combiner implementation
1195 //===----------------------------------------------------------------------===//
1197 void DAGCombiner::Run(CombineLevel AtLevel) {
1198 // set the instance variables, so that the various visit routines may use it.
1200 LegalOperations = Level >= AfterLegalizeVectorOps;
1201 LegalTypes = Level >= AfterLegalizeTypes;
1203 // Add all the dag nodes to the worklist.
1204 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1205 E = DAG.allnodes_end(); I != E; ++I)
1208 // Create a dummy node (which is not added to allnodes), that adds a reference
1209 // to the root node, preventing it from being deleted, and tracking any
1210 // changes of the root.
1211 HandleSDNode Dummy(DAG.getRoot());
1213 // while the worklist isn't empty, find a node and
1214 // try and combine it.
1215 while (!WorklistMap.empty()) {
1217 // The Worklist holds the SDNodes in order, but it may contain null entries.
1219 N = Worklist.pop_back_val();
1222 bool GoodWorklistEntry = WorklistMap.erase(N);
1223 (void)GoodWorklistEntry;
1224 assert(GoodWorklistEntry &&
1225 "Found a worklist entry without a corresponding map entry!");
1227 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1228 // N is deleted from the DAG, since they too may now be dead or may have a
1229 // reduced number of uses, allowing other xforms.
1230 if (recursivelyDeleteUnusedNodes(N))
1233 WorklistRemover DeadNodes(*this);
1235 // If this combine is running after legalizing the DAG, re-legalize any
1236 // nodes pulled off the worklist.
1237 if (Level == AfterLegalizeDAG) {
1238 SmallSetVector<SDNode *, 16> UpdatedNodes;
1239 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1241 for (SDNode *LN : UpdatedNodes) {
1243 AddUsersToWorklist(LN);
1249 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1251 // Add any operands of the new node which have not yet been combined to the
1252 // worklist as well. Because the worklist uniques things already, this
1253 // won't repeatedly process the same operand.
1254 CombinedNodes.insert(N);
1255 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1256 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1257 AddToWorklist(N->getOperand(i).getNode());
1259 SDValue RV = combine(N);
1266 // If we get back the same node we passed in, rather than a new node or
1267 // zero, we know that the node must have defined multiple values and
1268 // CombineTo was used. Since CombineTo takes care of the worklist
1269 // mechanics for us, we have no work to do in this case.
1270 if (RV.getNode() == N)
1273 assert(N->getOpcode() != ISD::DELETED_NODE &&
1274 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1275 "Node was deleted but visit returned new node!");
1277 DEBUG(dbgs() << " ... into: ";
1278 RV.getNode()->dump(&DAG));
1280 // Transfer debug value.
1281 DAG.TransferDbgValues(SDValue(N, 0), RV);
1282 if (N->getNumValues() == RV.getNode()->getNumValues())
1283 DAG.ReplaceAllUsesWith(N, RV.getNode());
1285 assert(N->getValueType(0) == RV.getValueType() &&
1286 N->getNumValues() == 1 && "Type mismatch");
1288 DAG.ReplaceAllUsesWith(N, &OpV);
1291 // Push the new node and any users onto the worklist
1292 AddToWorklist(RV.getNode());
1293 AddUsersToWorklist(RV.getNode());
1295 // Finally, if the node is now dead, remove it from the graph. The node
1296 // may not be dead if the replacement process recursively simplified to
1297 // something else needing this node. This will also take care of adding any
1298 // operands which have lost a user to the worklist.
1299 recursivelyDeleteUnusedNodes(N);
1302 // If the root changed (e.g. it was a dead load, update the root).
1303 DAG.setRoot(Dummy.getValue());
1304 DAG.RemoveDeadNodes();
1307 SDValue DAGCombiner::visit(SDNode *N) {
1308 switch (N->getOpcode()) {
1310 case ISD::TokenFactor: return visitTokenFactor(N);
1311 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1312 case ISD::ADD: return visitADD(N);
1313 case ISD::SUB: return visitSUB(N);
1314 case ISD::ADDC: return visitADDC(N);
1315 case ISD::SUBC: return visitSUBC(N);
1316 case ISD::ADDE: return visitADDE(N);
1317 case ISD::SUBE: return visitSUBE(N);
1318 case ISD::MUL: return visitMUL(N);
1319 case ISD::SDIV: return visitSDIV(N);
1320 case ISD::UDIV: return visitUDIV(N);
1321 case ISD::SREM: return visitSREM(N);
1322 case ISD::UREM: return visitUREM(N);
1323 case ISD::MULHU: return visitMULHU(N);
1324 case ISD::MULHS: return visitMULHS(N);
1325 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1326 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1327 case ISD::SMULO: return visitSMULO(N);
1328 case ISD::UMULO: return visitUMULO(N);
1329 case ISD::SDIVREM: return visitSDIVREM(N);
1330 case ISD::UDIVREM: return visitUDIVREM(N);
1331 case ISD::AND: return visitAND(N);
1332 case ISD::OR: return visitOR(N);
1333 case ISD::XOR: return visitXOR(N);
1334 case ISD::SHL: return visitSHL(N);
1335 case ISD::SRA: return visitSRA(N);
1336 case ISD::SRL: return visitSRL(N);
1338 case ISD::ROTL: return visitRotate(N);
1339 case ISD::BSWAP: return visitBSWAP(N);
1340 case ISD::CTLZ: return visitCTLZ(N);
1341 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1342 case ISD::CTTZ: return visitCTTZ(N);
1343 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1344 case ISD::CTPOP: return visitCTPOP(N);
1345 case ISD::SELECT: return visitSELECT(N);
1346 case ISD::VSELECT: return visitVSELECT(N);
1347 case ISD::SELECT_CC: return visitSELECT_CC(N);
1348 case ISD::SETCC: return visitSETCC(N);
1349 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1350 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1351 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1352 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1353 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1354 case ISD::TRUNCATE: return visitTRUNCATE(N);
1355 case ISD::BITCAST: return visitBITCAST(N);
1356 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1357 case ISD::FADD: return visitFADD(N);
1358 case ISD::FSUB: return visitFSUB(N);
1359 case ISD::FMUL: return visitFMUL(N);
1360 case ISD::FMA: return visitFMA(N);
1361 case ISD::FDIV: return visitFDIV(N);
1362 case ISD::FREM: return visitFREM(N);
1363 case ISD::FSQRT: return visitFSQRT(N);
1364 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1365 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1366 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1367 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1368 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1369 case ISD::FP_ROUND: return visitFP_ROUND(N);
1370 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1371 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1372 case ISD::FNEG: return visitFNEG(N);
1373 case ISD::FABS: return visitFABS(N);
1374 case ISD::FFLOOR: return visitFFLOOR(N);
1375 case ISD::FMINNUM: return visitFMINNUM(N);
1376 case ISD::FMAXNUM: return visitFMAXNUM(N);
1377 case ISD::FCEIL: return visitFCEIL(N);
1378 case ISD::FTRUNC: return visitFTRUNC(N);
1379 case ISD::BRCOND: return visitBRCOND(N);
1380 case ISD::BR_CC: return visitBR_CC(N);
1381 case ISD::LOAD: return visitLOAD(N);
1382 case ISD::STORE: return visitSTORE(N);
1383 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1384 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1385 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1386 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1387 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1388 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1389 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1390 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1391 case ISD::MGATHER: return visitMGATHER(N);
1392 case ISD::MLOAD: return visitMLOAD(N);
1393 case ISD::MSCATTER: return visitMSCATTER(N);
1394 case ISD::MSTORE: return visitMSTORE(N);
1395 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
1400 SDValue DAGCombiner::combine(SDNode *N) {
1401 SDValue RV = visit(N);
1403 // If nothing happened, try a target-specific DAG combine.
1404 if (!RV.getNode()) {
1405 assert(N->getOpcode() != ISD::DELETED_NODE &&
1406 "Node was deleted but visit returned NULL!");
1408 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1409 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1411 // Expose the DAG combiner to the target combiner impls.
1412 TargetLowering::DAGCombinerInfo
1413 DagCombineInfo(DAG, Level, false, this);
1415 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1419 // If nothing happened still, try promoting the operation.
1420 if (!RV.getNode()) {
1421 switch (N->getOpcode()) {
1429 RV = PromoteIntBinOp(SDValue(N, 0));
1434 RV = PromoteIntShiftOp(SDValue(N, 0));
1436 case ISD::SIGN_EXTEND:
1437 case ISD::ZERO_EXTEND:
1438 case ISD::ANY_EXTEND:
1439 RV = PromoteExtend(SDValue(N, 0));
1442 if (PromoteLoad(SDValue(N, 0)))
1448 // If N is a commutative binary node, try commuting it to enable more
1450 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1451 N->getNumValues() == 1) {
1452 SDValue N0 = N->getOperand(0);
1453 SDValue N1 = N->getOperand(1);
1455 // Constant operands are canonicalized to RHS.
1456 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1457 SDValue Ops[] = {N1, N0};
1459 if (const BinaryWithFlagsSDNode *BinNode =
1460 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1461 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1462 BinNode->Flags.hasNoUnsignedWrap(),
1463 BinNode->Flags.hasNoSignedWrap(),
1464 BinNode->Flags.hasExact());
1466 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1469 return SDValue(CSENode, 0);
1476 /// Given a node, return its input chain if it has one, otherwise return a null
1478 static SDValue getInputChainForNode(SDNode *N) {
1479 if (unsigned NumOps = N->getNumOperands()) {
1480 if (N->getOperand(0).getValueType() == MVT::Other)
1481 return N->getOperand(0);
1482 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1483 return N->getOperand(NumOps-1);
1484 for (unsigned i = 1; i < NumOps-1; ++i)
1485 if (N->getOperand(i).getValueType() == MVT::Other)
1486 return N->getOperand(i);
1491 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1492 // If N has two operands, where one has an input chain equal to the other,
1493 // the 'other' chain is redundant.
1494 if (N->getNumOperands() == 2) {
1495 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1496 return N->getOperand(0);
1497 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1498 return N->getOperand(1);
1501 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1502 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1503 SmallPtrSet<SDNode*, 16> SeenOps;
1504 bool Changed = false; // If we should replace this token factor.
1506 // Start out with this token factor.
1509 // Iterate through token factors. The TFs grows when new token factors are
1511 for (unsigned i = 0; i < TFs.size(); ++i) {
1512 SDNode *TF = TFs[i];
1514 // Check each of the operands.
1515 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1516 SDValue Op = TF->getOperand(i);
1518 switch (Op.getOpcode()) {
1519 case ISD::EntryToken:
1520 // Entry tokens don't need to be added to the list. They are
1525 case ISD::TokenFactor:
1526 if (Op.hasOneUse() &&
1527 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1528 // Queue up for processing.
1529 TFs.push_back(Op.getNode());
1530 // Clean up in case the token factor is removed.
1531 AddToWorklist(Op.getNode());
1538 // Only add if it isn't already in the list.
1539 if (SeenOps.insert(Op.getNode()).second)
1550 // If we've changed things around then replace token factor.
1553 // The entry token is the only possible outcome.
1554 Result = DAG.getEntryNode();
1556 // New and improved token factor.
1557 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1560 // Add users to worklist if AA is enabled, since it may introduce
1561 // a lot of new chained token factors while removing memory deps.
1562 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1563 : DAG.getSubtarget().useAA();
1564 return CombineTo(N, Result, UseAA /*add to worklist*/);
1570 /// MERGE_VALUES can always be eliminated.
1571 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1572 WorklistRemover DeadNodes(*this);
1573 // Replacing results may cause a different MERGE_VALUES to suddenly
1574 // be CSE'd with N, and carry its uses with it. Iterate until no
1575 // uses remain, to ensure that the node can be safely deleted.
1576 // First add the users of this node to the work list so that they
1577 // can be tried again once they have new operands.
1578 AddUsersToWorklist(N);
1580 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1581 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1582 } while (!N->use_empty());
1583 deleteAndRecombine(N);
1584 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1587 static bool isNullConstant(SDValue V) {
1588 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1589 return Const != nullptr && Const->isNullValue();
1592 static bool isNullFPConstant(SDValue V) {
1593 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1594 return Const != nullptr && Const->isZero() && !Const->isNegative();
1597 static bool isAllOnesConstant(SDValue V) {
1598 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1599 return Const != nullptr && Const->isAllOnesValue();
1602 static bool isOneConstant(SDValue V) {
1603 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1604 return Const != nullptr && Const->isOne();
1607 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1608 /// ContantSDNode pointer else nullptr.
1609 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1610 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1611 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1614 SDValue DAGCombiner::visitADD(SDNode *N) {
1615 SDValue N0 = N->getOperand(0);
1616 SDValue N1 = N->getOperand(1);
1617 EVT VT = N0.getValueType();
1620 if (VT.isVector()) {
1621 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1624 // fold (add x, 0) -> x, vector edition
1625 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1627 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1631 // fold (add x, undef) -> undef
1632 if (N0.getOpcode() == ISD::UNDEF)
1634 if (N1.getOpcode() == ISD::UNDEF)
1636 // fold (add c1, c2) -> c1+c2
1637 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1638 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1640 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1641 // canonicalize constant to RHS
1642 if (isConstantIntBuildVectorOrConstantInt(N0) &&
1643 !isConstantIntBuildVectorOrConstantInt(N1))
1644 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1645 // fold (add x, 0) -> x
1646 if (isNullConstant(N1))
1648 // fold (add Sym, c) -> Sym+c
1649 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1650 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1651 GA->getOpcode() == ISD::GlobalAddress)
1652 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1654 (uint64_t)N1C->getSExtValue());
1655 // fold ((c1-A)+c2) -> (c1+c2)-A
1656 if (N1C && N0.getOpcode() == ISD::SUB)
1657 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1659 return DAG.getNode(ISD::SUB, DL, VT,
1660 DAG.getConstant(N1C->getAPIntValue()+
1661 N0C->getAPIntValue(), DL, VT),
1665 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1667 // fold ((0-A) + B) -> B-A
1668 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1669 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1670 // fold (A + (0-B)) -> A-B
1671 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1672 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1673 // fold (A+(B-A)) -> B
1674 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1675 return N1.getOperand(0);
1676 // fold ((B-A)+A) -> B
1677 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1678 return N0.getOperand(0);
1679 // fold (A+(B-(A+C))) to (B-C)
1680 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1681 N0 == N1.getOperand(1).getOperand(0))
1682 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1683 N1.getOperand(1).getOperand(1));
1684 // fold (A+(B-(C+A))) to (B-C)
1685 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1686 N0 == N1.getOperand(1).getOperand(1))
1687 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1688 N1.getOperand(1).getOperand(0));
1689 // fold (A+((B-A)+or-C)) to (B+or-C)
1690 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1691 N1.getOperand(0).getOpcode() == ISD::SUB &&
1692 N0 == N1.getOperand(0).getOperand(1))
1693 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1694 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1696 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1697 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1698 SDValue N00 = N0.getOperand(0);
1699 SDValue N01 = N0.getOperand(1);
1700 SDValue N10 = N1.getOperand(0);
1701 SDValue N11 = N1.getOperand(1);
1703 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1704 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1705 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1706 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1709 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1710 return SDValue(N, 0);
1712 // fold (a+b) -> (a|b) iff a and b share no bits.
1713 if (VT.isInteger() && !VT.isVector()) {
1714 APInt LHSZero, LHSOne;
1715 APInt RHSZero, RHSOne;
1716 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1718 if (LHSZero.getBoolValue()) {
1719 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1721 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1722 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1723 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1724 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1725 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1730 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1731 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1732 isNullConstant(N1.getOperand(0).getOperand(0)))
1733 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1734 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1735 N1.getOperand(0).getOperand(1),
1737 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1738 isNullConstant(N0.getOperand(0).getOperand(0)))
1739 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1740 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1741 N0.getOperand(0).getOperand(1),
1744 if (N1.getOpcode() == ISD::AND) {
1745 SDValue AndOp0 = N1.getOperand(0);
1746 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1747 unsigned DestBits = VT.getScalarType().getSizeInBits();
1749 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1750 // and similar xforms where the inner op is either ~0 or 0.
1751 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1753 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1757 // add (sext i1), X -> sub X, (zext i1)
1758 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1759 N0.getOperand(0).getValueType() == MVT::i1 &&
1760 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1762 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1763 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1766 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1767 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1768 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1769 if (TN->getVT() == MVT::i1) {
1771 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1772 DAG.getConstant(1, DL, VT));
1773 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1780 SDValue DAGCombiner::visitADDC(SDNode *N) {
1781 SDValue N0 = N->getOperand(0);
1782 SDValue N1 = N->getOperand(1);
1783 EVT VT = N0.getValueType();
1785 // If the flag result is dead, turn this into an ADD.
1786 if (!N->hasAnyUseOfValue(1))
1787 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1788 DAG.getNode(ISD::CARRY_FALSE,
1789 SDLoc(N), MVT::Glue));
1791 // canonicalize constant to RHS.
1792 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1793 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1795 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1797 // fold (addc x, 0) -> x + no carry out
1798 if (isNullConstant(N1))
1799 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1800 SDLoc(N), MVT::Glue));
1802 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1803 APInt LHSZero, LHSOne;
1804 APInt RHSZero, RHSOne;
1805 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1807 if (LHSZero.getBoolValue()) {
1808 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1810 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1811 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1812 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1813 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1814 DAG.getNode(ISD::CARRY_FALSE,
1815 SDLoc(N), MVT::Glue));
1821 SDValue DAGCombiner::visitADDE(SDNode *N) {
1822 SDValue N0 = N->getOperand(0);
1823 SDValue N1 = N->getOperand(1);
1824 SDValue CarryIn = N->getOperand(2);
1826 // canonicalize constant to RHS
1827 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1828 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1830 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1833 // fold (adde x, y, false) -> (addc x, y)
1834 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1835 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1840 // Since it may not be valid to emit a fold to zero for vector initializers
1841 // check if we can before folding.
1842 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1844 bool LegalOperations, bool LegalTypes) {
1846 return DAG.getConstant(0, DL, VT);
1847 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1848 return DAG.getConstant(0, DL, VT);
1852 SDValue DAGCombiner::visitSUB(SDNode *N) {
1853 SDValue N0 = N->getOperand(0);
1854 SDValue N1 = N->getOperand(1);
1855 EVT VT = N0.getValueType();
1858 if (VT.isVector()) {
1859 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1862 // fold (sub x, 0) -> x, vector edition
1863 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1867 // fold (sub x, x) -> 0
1868 // FIXME: Refactor this and xor and other similar operations together.
1870 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1871 // fold (sub c1, c2) -> c1-c2
1872 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1873 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1875 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1876 // fold (sub x, c) -> (add x, -c)
1879 return DAG.getNode(ISD::ADD, DL, VT, N0,
1880 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1882 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1883 if (isAllOnesConstant(N0))
1884 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1885 // fold A-(A-B) -> B
1886 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1887 return N1.getOperand(1);
1888 // fold (A+B)-A -> B
1889 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1890 return N0.getOperand(1);
1891 // fold (A+B)-B -> A
1892 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1893 return N0.getOperand(0);
1894 // fold C2-(A+C1) -> (C2-C1)-A
1895 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1896 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1897 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1899 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1901 return DAG.getNode(ISD::SUB, DL, VT, NewC,
1904 // fold ((A+(B+or-C))-B) -> A+or-C
1905 if (N0.getOpcode() == ISD::ADD &&
1906 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1907 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1908 N0.getOperand(1).getOperand(0) == N1)
1909 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1910 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1911 // fold ((A+(C+B))-B) -> A+C
1912 if (N0.getOpcode() == ISD::ADD &&
1913 N0.getOperand(1).getOpcode() == ISD::ADD &&
1914 N0.getOperand(1).getOperand(1) == N1)
1915 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1916 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1917 // fold ((A-(B-C))-C) -> A-B
1918 if (N0.getOpcode() == ISD::SUB &&
1919 N0.getOperand(1).getOpcode() == ISD::SUB &&
1920 N0.getOperand(1).getOperand(1) == N1)
1921 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1922 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1924 // If either operand of a sub is undef, the result is undef
1925 if (N0.getOpcode() == ISD::UNDEF)
1927 if (N1.getOpcode() == ISD::UNDEF)
1930 // If the relocation model supports it, consider symbol offsets.
1931 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1932 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1933 // fold (sub Sym, c) -> Sym-c
1934 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1935 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1937 (uint64_t)N1C->getSExtValue());
1938 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1939 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1940 if (GA->getGlobal() == GB->getGlobal())
1941 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1945 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1946 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1947 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1948 if (TN->getVT() == MVT::i1) {
1950 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1951 DAG.getConstant(1, DL, VT));
1952 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1959 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1960 SDValue N0 = N->getOperand(0);
1961 SDValue N1 = N->getOperand(1);
1962 EVT VT = N0.getValueType();
1964 // If the flag result is dead, turn this into an SUB.
1965 if (!N->hasAnyUseOfValue(1))
1966 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1967 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1970 // fold (subc x, x) -> 0 + no borrow
1973 return CombineTo(N, DAG.getConstant(0, DL, VT),
1974 DAG.getNode(ISD::CARRY_FALSE, DL,
1978 // fold (subc x, 0) -> x + no borrow
1979 if (isNullConstant(N1))
1980 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1983 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1984 if (isAllOnesConstant(N0))
1985 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1986 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1992 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1993 SDValue N0 = N->getOperand(0);
1994 SDValue N1 = N->getOperand(1);
1995 SDValue CarryIn = N->getOperand(2);
1997 // fold (sube x, y, false) -> (subc x, y)
1998 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1999 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2004 SDValue DAGCombiner::visitMUL(SDNode *N) {
2005 SDValue N0 = N->getOperand(0);
2006 SDValue N1 = N->getOperand(1);
2007 EVT VT = N0.getValueType();
2009 // fold (mul x, undef) -> 0
2010 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2011 return DAG.getConstant(0, SDLoc(N), VT);
2013 bool N0IsConst = false;
2014 bool N1IsConst = false;
2015 bool N1IsOpaqueConst = false;
2016 bool N0IsOpaqueConst = false;
2017 APInt ConstValue0, ConstValue1;
2019 if (VT.isVector()) {
2020 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2023 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2024 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2026 N0IsConst = isa<ConstantSDNode>(N0);
2028 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2029 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2031 N1IsConst = isa<ConstantSDNode>(N1);
2033 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2034 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2038 // fold (mul c1, c2) -> c1*c2
2039 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2040 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2041 N0.getNode(), N1.getNode());
2043 // canonicalize constant to RHS (vector doesn't have to splat)
2044 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2045 !isConstantIntBuildVectorOrConstantInt(N1))
2046 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2047 // fold (mul x, 0) -> 0
2048 if (N1IsConst && ConstValue1 == 0)
2050 // We require a splat of the entire scalar bit width for non-contiguous
2053 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2054 // fold (mul x, 1) -> x
2055 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2057 // fold (mul x, -1) -> 0-x
2058 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2060 return DAG.getNode(ISD::SUB, DL, VT,
2061 DAG.getConstant(0, DL, VT), N0);
2063 // fold (mul x, (1 << c)) -> x << c
2064 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2067 return DAG.getNode(ISD::SHL, DL, VT, N0,
2068 DAG.getConstant(ConstValue1.logBase2(), DL,
2069 getShiftAmountTy(N0.getValueType())));
2071 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2072 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2074 unsigned Log2Val = (-ConstValue1).logBase2();
2076 // FIXME: If the input is something that is easily negated (e.g. a
2077 // single-use add), we should put the negate there.
2078 return DAG.getNode(ISD::SUB, DL, VT,
2079 DAG.getConstant(0, DL, VT),
2080 DAG.getNode(ISD::SHL, DL, VT, N0,
2081 DAG.getConstant(Log2Val, DL,
2082 getShiftAmountTy(N0.getValueType()))));
2086 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2087 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2088 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2089 isa<ConstantSDNode>(N0.getOperand(1)))) {
2090 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2091 N1, N0.getOperand(1));
2092 AddToWorklist(C3.getNode());
2093 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2094 N0.getOperand(0), C3);
2097 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2100 SDValue Sh(nullptr,0), Y(nullptr,0);
2101 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2102 if (N0.getOpcode() == ISD::SHL &&
2103 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2104 isa<ConstantSDNode>(N0.getOperand(1))) &&
2105 N0.getNode()->hasOneUse()) {
2107 } else if (N1.getOpcode() == ISD::SHL &&
2108 isa<ConstantSDNode>(N1.getOperand(1)) &&
2109 N1.getNode()->hasOneUse()) {
2114 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2115 Sh.getOperand(0), Y);
2116 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2117 Mul, Sh.getOperand(1));
2121 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2122 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2123 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2124 isa<ConstantSDNode>(N0.getOperand(1))))
2125 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2126 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2127 N0.getOperand(0), N1),
2128 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2129 N0.getOperand(1), N1));
2132 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2138 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2139 SDValue N0 = N->getOperand(0);
2140 SDValue N1 = N->getOperand(1);
2141 EVT VT = N->getValueType(0);
2145 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2148 // fold (sdiv c1, c2) -> c1/c2
2149 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2150 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2151 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2152 return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2153 // fold (sdiv X, 1) -> X
2154 if (N1C && N1C->isOne())
2156 // fold (sdiv X, -1) -> 0-X
2157 if (N1C && N1C->isAllOnesValue()) {
2159 return DAG.getNode(ISD::SUB, DL, VT,
2160 DAG.getConstant(0, DL, VT), N0);
2162 // If we know the sign bits of both operands are zero, strength reduce to a
2163 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2164 if (!VT.isVector()) {
2165 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2166 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2170 // fold (sdiv X, pow2) -> simple ops after legalize
2171 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2172 (N1C->getAPIntValue().isPowerOf2() ||
2173 (-N1C->getAPIntValue()).isPowerOf2())) {
2174 // If dividing by powers of two is cheap, then don't perform the following
2176 if (TLI.isPow2SDivCheap())
2179 // Target-specific implementation of sdiv x, pow2.
2180 SDValue Res = BuildSDIVPow2(N);
2184 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2187 // Splat the sign bit into the register
2189 DAG.getNode(ISD::SRA, DL, VT, N0,
2190 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2191 getShiftAmountTy(N0.getValueType())));
2192 AddToWorklist(SGN.getNode());
2194 // Add (N0 < 0) ? abs2 - 1 : 0;
2196 DAG.getNode(ISD::SRL, DL, VT, SGN,
2197 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2198 getShiftAmountTy(SGN.getValueType())));
2199 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2200 AddToWorklist(SRL.getNode());
2201 AddToWorklist(ADD.getNode()); // Divide by pow2
2202 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2203 DAG.getConstant(lg2, DL,
2204 getShiftAmountTy(ADD.getValueType())));
2206 // If we're dividing by a positive value, we're done. Otherwise, we must
2207 // negate the result.
2208 if (N1C->getAPIntValue().isNonNegative())
2211 AddToWorklist(SRA.getNode());
2212 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2215 // If integer divide is expensive and we satisfy the requirements, emit an
2216 // alternate sequence.
2217 if (N1C && !TLI.isIntDivCheap()) {
2218 SDValue Op = BuildSDIV(N);
2219 if (Op.getNode()) return Op;
2223 if (N0.getOpcode() == ISD::UNDEF)
2224 return DAG.getConstant(0, SDLoc(N), VT);
2225 // X / undef -> undef
2226 if (N1.getOpcode() == ISD::UNDEF)
2232 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2233 SDValue N0 = N->getOperand(0);
2234 SDValue N1 = N->getOperand(1);
2235 EVT VT = N->getValueType(0);
2239 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2242 // fold (udiv c1, c2) -> c1/c2
2243 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2244 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2246 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT,
2249 // fold (udiv x, (1 << c)) -> x >>u c
2250 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) {
2252 return DAG.getNode(ISD::SRL, DL, VT, N0,
2253 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2254 getShiftAmountTy(N0.getValueType())));
2256 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2257 if (N1.getOpcode() == ISD::SHL) {
2258 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2259 if (SHC->getAPIntValue().isPowerOf2()) {
2260 EVT ADDVT = N1.getOperand(1).getValueType();
2262 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2264 DAG.getConstant(SHC->getAPIntValue()
2267 AddToWorklist(Add.getNode());
2268 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2272 // fold (udiv x, c) -> alternate
2273 if (N1C && !TLI.isIntDivCheap()) {
2274 SDValue Op = BuildUDIV(N);
2275 if (Op.getNode()) return Op;
2279 if (N0.getOpcode() == ISD::UNDEF)
2280 return DAG.getConstant(0, SDLoc(N), VT);
2281 // X / undef -> undef
2282 if (N1.getOpcode() == ISD::UNDEF)
2288 SDValue DAGCombiner::visitSREM(SDNode *N) {
2289 SDValue N0 = N->getOperand(0);
2290 SDValue N1 = N->getOperand(1);
2291 EVT VT = N->getValueType(0);
2293 // fold (srem c1, c2) -> c1%c2
2294 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2295 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2297 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT,
2300 // If we know the sign bits of both operands are zero, strength reduce to a
2301 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2302 if (!VT.isVector()) {
2303 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2304 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2307 // If X/C can be simplified by the division-by-constant logic, lower
2308 // X%C to the equivalent of X-X/C*C.
2309 if (N1C && !N1C->isNullValue()) {
2310 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2311 AddToWorklist(Div.getNode());
2312 SDValue OptimizedDiv = combine(Div.getNode());
2313 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2314 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2316 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2317 AddToWorklist(Mul.getNode());
2323 if (N0.getOpcode() == ISD::UNDEF)
2324 return DAG.getConstant(0, SDLoc(N), VT);
2325 // X % undef -> undef
2326 if (N1.getOpcode() == ISD::UNDEF)
2332 SDValue DAGCombiner::visitUREM(SDNode *N) {
2333 SDValue N0 = N->getOperand(0);
2334 SDValue N1 = N->getOperand(1);
2335 EVT VT = N->getValueType(0);
2337 // fold (urem c1, c2) -> c1%c2
2338 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2339 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2341 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT,
2344 // fold (urem x, pow2) -> (and x, pow2-1)
2345 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2346 N1C->getAPIntValue().isPowerOf2()) {
2348 return DAG.getNode(ISD::AND, DL, VT, N0,
2349 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2351 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2352 if (N1.getOpcode() == ISD::SHL) {
2353 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2354 if (SHC->getAPIntValue().isPowerOf2()) {
2357 DAG.getNode(ISD::ADD, DL, VT, N1,
2358 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2360 AddToWorklist(Add.getNode());
2361 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2366 // If X/C can be simplified by the division-by-constant logic, lower
2367 // X%C to the equivalent of X-X/C*C.
2368 if (N1C && !N1C->isNullValue()) {
2369 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2370 AddToWorklist(Div.getNode());
2371 SDValue OptimizedDiv = combine(Div.getNode());
2372 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2373 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2375 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2376 AddToWorklist(Mul.getNode());
2382 if (N0.getOpcode() == ISD::UNDEF)
2383 return DAG.getConstant(0, SDLoc(N), VT);
2384 // X % undef -> undef
2385 if (N1.getOpcode() == ISD::UNDEF)
2391 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2392 SDValue N0 = N->getOperand(0);
2393 SDValue N1 = N->getOperand(1);
2394 EVT VT = N->getValueType(0);
2397 // fold (mulhs x, 0) -> 0
2398 if (isNullConstant(N1))
2400 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2401 if (isOneConstant(N1)) {
2403 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2404 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2406 getShiftAmountTy(N0.getValueType())));
2408 // fold (mulhs x, undef) -> 0
2409 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2410 return DAG.getConstant(0, SDLoc(N), VT);
2412 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2414 if (VT.isSimple() && !VT.isVector()) {
2415 MVT Simple = VT.getSimpleVT();
2416 unsigned SimpleSize = Simple.getSizeInBits();
2417 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2418 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2419 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2420 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2421 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2422 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2423 DAG.getConstant(SimpleSize, DL,
2424 getShiftAmountTy(N1.getValueType())));
2425 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2432 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2433 SDValue N0 = N->getOperand(0);
2434 SDValue N1 = N->getOperand(1);
2435 EVT VT = N->getValueType(0);
2438 // fold (mulhu x, 0) -> 0
2439 if (isNullConstant(N1))
2441 // fold (mulhu x, 1) -> 0
2442 if (isOneConstant(N1))
2443 return DAG.getConstant(0, DL, N0.getValueType());
2444 // fold (mulhu x, undef) -> 0
2445 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2446 return DAG.getConstant(0, DL, VT);
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 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2456 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2457 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2458 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2459 DAG.getConstant(SimpleSize, DL,
2460 getShiftAmountTy(N1.getValueType())));
2461 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2468 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2469 /// give the opcodes for the two computations that are being performed. Return
2470 /// true if a simplification was made.
2471 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2473 // If the high half is not needed, just compute the low half.
2474 bool HiExists = N->hasAnyUseOfValue(1);
2476 (!LegalOperations ||
2477 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2478 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2479 return CombineTo(N, Res, Res);
2482 // If the low half is not needed, just compute the high half.
2483 bool LoExists = N->hasAnyUseOfValue(0);
2485 (!LegalOperations ||
2486 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2487 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2488 return CombineTo(N, Res, Res);
2491 // If both halves are used, return as it is.
2492 if (LoExists && HiExists)
2495 // If the two computed results can be simplified separately, separate them.
2497 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2498 AddToWorklist(Lo.getNode());
2499 SDValue LoOpt = combine(Lo.getNode());
2500 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2501 (!LegalOperations ||
2502 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2503 return CombineTo(N, LoOpt, LoOpt);
2507 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2508 AddToWorklist(Hi.getNode());
2509 SDValue HiOpt = combine(Hi.getNode());
2510 if (HiOpt.getNode() && HiOpt != Hi &&
2511 (!LegalOperations ||
2512 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2513 return CombineTo(N, HiOpt, HiOpt);
2519 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2520 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2521 if (Res.getNode()) return Res;
2523 EVT VT = N->getValueType(0);
2526 // If the type is twice as wide is legal, transform the mulhu to a wider
2527 // multiply plus a shift.
2528 if (VT.isSimple() && !VT.isVector()) {
2529 MVT Simple = VT.getSimpleVT();
2530 unsigned SimpleSize = Simple.getSizeInBits();
2531 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2532 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2533 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2534 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2535 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2536 // Compute the high part as N1.
2537 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2538 DAG.getConstant(SimpleSize, DL,
2539 getShiftAmountTy(Lo.getValueType())));
2540 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2541 // Compute the low part as N0.
2542 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2543 return CombineTo(N, Lo, Hi);
2550 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2551 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2552 if (Res.getNode()) return Res;
2554 EVT VT = N->getValueType(0);
2557 // If the type is twice as wide is legal, transform the mulhu to a wider
2558 // multiply plus a shift.
2559 if (VT.isSimple() && !VT.isVector()) {
2560 MVT Simple = VT.getSimpleVT();
2561 unsigned SimpleSize = Simple.getSizeInBits();
2562 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2563 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2564 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2565 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2566 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2567 // Compute the high part as N1.
2568 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2569 DAG.getConstant(SimpleSize, DL,
2570 getShiftAmountTy(Lo.getValueType())));
2571 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2572 // Compute the low part as N0.
2573 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2574 return CombineTo(N, Lo, Hi);
2581 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2582 // (smulo x, 2) -> (saddo x, x)
2583 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2584 if (C2->getAPIntValue() == 2)
2585 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2586 N->getOperand(0), N->getOperand(0));
2591 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2592 // (umulo x, 2) -> (uaddo x, x)
2593 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2594 if (C2->getAPIntValue() == 2)
2595 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2596 N->getOperand(0), N->getOperand(0));
2601 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2602 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2603 if (Res.getNode()) return Res;
2608 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2609 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2610 if (Res.getNode()) return Res;
2615 /// If this is a binary operator with two operands of the same opcode, try to
2617 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2618 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2619 EVT VT = N0.getValueType();
2620 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2622 // Bail early if none of these transforms apply.
2623 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2625 // For each of OP in AND/OR/XOR:
2626 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2627 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2628 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2629 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2630 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2632 // do not sink logical op inside of a vector extend, since it may combine
2634 EVT Op0VT = N0.getOperand(0).getValueType();
2635 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2636 N0.getOpcode() == ISD::SIGN_EXTEND ||
2637 N0.getOpcode() == ISD::BSWAP ||
2638 // Avoid infinite looping with PromoteIntBinOp.
2639 (N0.getOpcode() == ISD::ANY_EXTEND &&
2640 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2641 (N0.getOpcode() == ISD::TRUNCATE &&
2642 (!TLI.isZExtFree(VT, Op0VT) ||
2643 !TLI.isTruncateFree(Op0VT, VT)) &&
2644 TLI.isTypeLegal(Op0VT))) &&
2646 Op0VT == N1.getOperand(0).getValueType() &&
2647 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2648 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2649 N0.getOperand(0).getValueType(),
2650 N0.getOperand(0), N1.getOperand(0));
2651 AddToWorklist(ORNode.getNode());
2652 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2655 // For each of OP in SHL/SRL/SRA/AND...
2656 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2657 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2658 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2659 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2660 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2661 N0.getOperand(1) == N1.getOperand(1)) {
2662 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2663 N0.getOperand(0).getValueType(),
2664 N0.getOperand(0), N1.getOperand(0));
2665 AddToWorklist(ORNode.getNode());
2666 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2667 ORNode, N0.getOperand(1));
2670 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2671 // Only perform this optimization after type legalization and before
2672 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2673 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2674 // we don't want to undo this promotion.
2675 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2677 if ((N0.getOpcode() == ISD::BITCAST ||
2678 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2679 Level == AfterLegalizeTypes) {
2680 SDValue In0 = N0.getOperand(0);
2681 SDValue In1 = N1.getOperand(0);
2682 EVT In0Ty = In0.getValueType();
2683 EVT In1Ty = In1.getValueType();
2685 // If both incoming values are integers, and the original types are the
2687 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2688 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2689 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2690 AddToWorklist(Op.getNode());
2695 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2696 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2697 // If both shuffles use the same mask, and both shuffle within a single
2698 // vector, then it is worthwhile to move the swizzle after the operation.
2699 // The type-legalizer generates this pattern when loading illegal
2700 // vector types from memory. In many cases this allows additional shuffle
2702 // There are other cases where moving the shuffle after the xor/and/or
2703 // is profitable even if shuffles don't perform a swizzle.
2704 // If both shuffles use the same mask, and both shuffles have the same first
2705 // or second operand, then it might still be profitable to move the shuffle
2706 // after the xor/and/or operation.
2707 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2708 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2709 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2711 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2712 "Inputs to shuffles are not the same type");
2714 // Check that both shuffles use the same mask. The masks are known to be of
2715 // the same length because the result vector type is the same.
2716 // Check also that shuffles have only one use to avoid introducing extra
2718 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2719 SVN0->getMask().equals(SVN1->getMask())) {
2720 SDValue ShOp = N0->getOperand(1);
2722 // Don't try to fold this node if it requires introducing a
2723 // build vector of all zeros that might be illegal at this stage.
2724 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2726 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2731 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2732 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2733 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2734 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2735 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2736 N0->getOperand(0), N1->getOperand(0));
2737 AddToWorklist(NewNode.getNode());
2738 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2739 &SVN0->getMask()[0]);
2742 // Don't try to fold this node if it requires introducing a
2743 // build vector of all zeros that might be illegal at this stage.
2744 ShOp = N0->getOperand(0);
2745 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2747 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2752 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2753 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2754 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2755 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2756 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2757 N0->getOperand(1), N1->getOperand(1));
2758 AddToWorklist(NewNode.getNode());
2759 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2760 &SVN0->getMask()[0]);
2768 /// This contains all DAGCombine rules which reduce two values combined by
2769 /// an And operation to a single value. This makes them reusable in the context
2770 /// of visitSELECT(). Rules involving constants are not included as
2771 /// visitSELECT() already handles those cases.
2772 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2773 SDNode *LocReference) {
2774 EVT VT = N1.getValueType();
2776 // fold (and x, undef) -> 0
2777 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2778 return DAG.getConstant(0, SDLoc(LocReference), VT);
2779 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2780 SDValue LL, LR, RL, RR, CC0, CC1;
2781 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2782 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2783 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2785 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2786 LL.getValueType().isInteger()) {
2787 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2788 if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2789 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2790 LR.getValueType(), LL, RL);
2791 AddToWorklist(ORNode.getNode());
2792 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2794 if (isAllOnesConstant(LR)) {
2795 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2796 if (Op1 == ISD::SETEQ) {
2797 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2798 LR.getValueType(), LL, RL);
2799 AddToWorklist(ANDNode.getNode());
2800 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2802 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2803 if (Op1 == ISD::SETGT) {
2804 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2805 LR.getValueType(), LL, RL);
2806 AddToWorklist(ORNode.getNode());
2807 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2811 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2812 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2813 Op0 == Op1 && LL.getValueType().isInteger() &&
2814 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2815 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2817 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2818 LL, DAG.getConstant(1, DL,
2819 LL.getValueType()));
2820 AddToWorklist(ADDNode.getNode());
2821 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2822 DAG.getConstant(2, DL, LL.getValueType()),
2825 // canonicalize equivalent to ll == rl
2826 if (LL == RR && LR == RL) {
2827 Op1 = ISD::getSetCCSwappedOperands(Op1);
2830 if (LL == RL && LR == RR) {
2831 bool isInteger = LL.getValueType().isInteger();
2832 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2833 if (Result != ISD::SETCC_INVALID &&
2834 (!LegalOperations ||
2835 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2836 TLI.isOperationLegal(ISD::SETCC,
2837 getSetCCResultType(N0.getSimpleValueType())))))
2838 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2843 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2844 VT.getSizeInBits() <= 64) {
2845 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2846 APInt ADDC = ADDI->getAPIntValue();
2847 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2848 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2849 // immediate for an add, but it is legal if its top c2 bits are set,
2850 // transform the ADD so the immediate doesn't need to be materialized
2852 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2853 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2854 SRLI->getZExtValue());
2855 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2857 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2860 DAG.getNode(ISD::ADD, DL, VT,
2861 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2862 CombineTo(N0.getNode(), NewAdd);
2863 // Return N so it doesn't get rechecked!
2864 return SDValue(LocReference, 0);
2875 SDValue DAGCombiner::visitAND(SDNode *N) {
2876 SDValue N0 = N->getOperand(0);
2877 SDValue N1 = N->getOperand(1);
2878 EVT VT = N1.getValueType();
2881 if (VT.isVector()) {
2882 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2885 // fold (and x, 0) -> 0, vector edition
2886 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2887 // do not return N0, because undef node may exist in N0
2888 return DAG.getConstant(
2889 APInt::getNullValue(
2890 N0.getValueType().getScalarType().getSizeInBits()),
2891 SDLoc(N), N0.getValueType());
2892 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2893 // do not return N1, because undef node may exist in N1
2894 return DAG.getConstant(
2895 APInt::getNullValue(
2896 N1.getValueType().getScalarType().getSizeInBits()),
2897 SDLoc(N), N1.getValueType());
2899 // fold (and x, -1) -> x, vector edition
2900 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2902 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2906 // fold (and c1, c2) -> c1&c2
2907 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2908 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2909 if (N0C && N1C && !N1C->isOpaque())
2910 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2911 // canonicalize constant to RHS
2912 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2913 !isConstantIntBuildVectorOrConstantInt(N1))
2914 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2915 // fold (and x, -1) -> x
2916 if (isAllOnesConstant(N1))
2918 // if (and x, c) is known to be zero, return 0
2919 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2920 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2921 APInt::getAllOnesValue(BitWidth)))
2922 return DAG.getConstant(0, SDLoc(N), VT);
2924 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2926 // fold (and (or x, C), D) -> D if (C & D) == D
2927 if (N1C && N0.getOpcode() == ISD::OR)
2928 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2929 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2931 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2932 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2933 SDValue N0Op0 = N0.getOperand(0);
2934 APInt Mask = ~N1C->getAPIntValue();
2935 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2936 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2937 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2938 N0.getValueType(), N0Op0);
2940 // Replace uses of the AND with uses of the Zero extend node.
2943 // We actually want to replace all uses of the any_extend with the
2944 // zero_extend, to avoid duplicating things. This will later cause this
2945 // AND to be folded.
2946 CombineTo(N0.getNode(), Zext);
2947 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2950 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2951 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2952 // already be zero by virtue of the width of the base type of the load.
2954 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2956 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2957 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2958 N0.getOpcode() == ISD::LOAD) {
2959 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2960 N0 : N0.getOperand(0) );
2962 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2963 // This can be a pure constant or a vector splat, in which case we treat the
2964 // vector as a scalar and use the splat value.
2965 APInt Constant = APInt::getNullValue(1);
2966 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2967 Constant = C->getAPIntValue();
2968 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2969 APInt SplatValue, SplatUndef;
2970 unsigned SplatBitSize;
2972 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2973 SplatBitSize, HasAnyUndefs);
2975 // Undef bits can contribute to a possible optimisation if set, so
2977 SplatValue |= SplatUndef;
2979 // The splat value may be something like "0x00FFFFFF", which means 0 for
2980 // the first vector value and FF for the rest, repeating. We need a mask
2981 // that will apply equally to all members of the vector, so AND all the
2982 // lanes of the constant together.
2983 EVT VT = Vector->getValueType(0);
2984 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2986 // If the splat value has been compressed to a bitlength lower
2987 // than the size of the vector lane, we need to re-expand it to
2989 if (BitWidth > SplatBitSize)
2990 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2991 SplatBitSize < BitWidth;
2992 SplatBitSize = SplatBitSize * 2)
2993 SplatValue |= SplatValue.shl(SplatBitSize);
2995 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2996 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2997 if (SplatBitSize % BitWidth == 0) {
2998 Constant = APInt::getAllOnesValue(BitWidth);
2999 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3000 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3005 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3006 // actually legal and isn't going to get expanded, else this is a false
3008 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3009 Load->getValueType(0),
3010 Load->getMemoryVT());
3012 // Resize the constant to the same size as the original memory access before
3013 // extension. If it is still the AllOnesValue then this AND is completely
3016 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3019 switch (Load->getExtensionType()) {
3020 default: B = false; break;
3021 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3023 case ISD::NON_EXTLOAD: B = true; break;
3026 if (B && Constant.isAllOnesValue()) {
3027 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3028 // preserve semantics once we get rid of the AND.
3029 SDValue NewLoad(Load, 0);
3030 if (Load->getExtensionType() == ISD::EXTLOAD) {
3031 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3032 Load->getValueType(0), SDLoc(Load),
3033 Load->getChain(), Load->getBasePtr(),
3034 Load->getOffset(), Load->getMemoryVT(),
3035 Load->getMemOperand());
3036 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3037 if (Load->getNumValues() == 3) {
3038 // PRE/POST_INC loads have 3 values.
3039 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3040 NewLoad.getValue(2) };
3041 CombineTo(Load, To, 3, true);
3043 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3047 // Fold the AND away, taking care not to fold to the old load node if we
3049 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3051 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3055 // fold (and (load x), 255) -> (zextload x, i8)
3056 // fold (and (extload x, i16), 255) -> (zextload x, i8)
3057 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3058 if (N1C && (N0.getOpcode() == ISD::LOAD ||
3059 (N0.getOpcode() == ISD::ANY_EXTEND &&
3060 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3061 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3062 LoadSDNode *LN0 = HasAnyExt
3063 ? cast<LoadSDNode>(N0.getOperand(0))
3064 : cast<LoadSDNode>(N0);
3065 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3066 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3067 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3068 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3069 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3070 EVT LoadedVT = LN0->getMemoryVT();
3071 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3073 if (ExtVT == LoadedVT &&
3074 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3078 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3079 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3080 LN0->getMemOperand());
3082 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3083 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3086 // Do not change the width of a volatile load.
3087 // Do not generate loads of non-round integer types since these can
3088 // be expensive (and would be wrong if the type is not byte sized).
3089 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3090 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3092 EVT PtrType = LN0->getOperand(1).getValueType();
3094 unsigned Alignment = LN0->getAlignment();
3095 SDValue NewPtr = LN0->getBasePtr();
3097 // For big endian targets, we need to add an offset to the pointer
3098 // to load the correct bytes. For little endian systems, we merely
3099 // need to read fewer bytes from the same pointer.
3100 if (TLI.isBigEndian()) {
3101 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3102 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3103 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3105 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3106 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3107 Alignment = MinAlign(Alignment, PtrOff);
3110 AddToWorklist(NewPtr.getNode());
3113 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3114 LN0->getChain(), NewPtr,
3115 LN0->getPointerInfo(),
3116 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3117 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3119 CombineTo(LN0, Load, Load.getValue(1));
3120 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3126 if (SDValue Combined = visitANDLike(N0, N1, N))
3129 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3130 if (N0.getOpcode() == N1.getOpcode()) {
3131 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3132 if (Tmp.getNode()) return Tmp;
3135 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3136 // fold (and (sra)) -> (and (srl)) when possible.
3137 if (!VT.isVector() &&
3138 SimplifyDemandedBits(SDValue(N, 0)))
3139 return SDValue(N, 0);
3141 // fold (zext_inreg (extload x)) -> (zextload x)
3142 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3143 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3144 EVT MemVT = LN0->getMemoryVT();
3145 // If we zero all the possible extended bits, then we can turn this into
3146 // a zextload if we are running before legalize or the operation is legal.
3147 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3148 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3149 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3150 ((!LegalOperations && !LN0->isVolatile()) ||
3151 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3152 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3153 LN0->getChain(), LN0->getBasePtr(),
3154 MemVT, LN0->getMemOperand());
3156 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3157 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3160 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3161 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3163 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3164 EVT MemVT = LN0->getMemoryVT();
3165 // If we zero all the possible extended bits, then we can turn this into
3166 // a zextload if we are running before legalize or the operation is legal.
3167 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3168 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3169 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3170 ((!LegalOperations && !LN0->isVolatile()) ||
3171 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3172 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3173 LN0->getChain(), LN0->getBasePtr(),
3174 MemVT, LN0->getMemOperand());
3176 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3177 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3180 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3181 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3182 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3183 N0.getOperand(1), false);
3184 if (BSwap.getNode())
3191 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3192 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3193 bool DemandHighBits) {
3194 if (!LegalOperations)
3197 EVT VT = N->getValueType(0);
3198 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3200 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3203 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3204 bool LookPassAnd0 = false;
3205 bool LookPassAnd1 = false;
3206 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3208 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3210 if (N0.getOpcode() == ISD::AND) {
3211 if (!N0.getNode()->hasOneUse())
3213 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3214 if (!N01C || N01C->getZExtValue() != 0xFF00)
3216 N0 = N0.getOperand(0);
3217 LookPassAnd0 = true;
3220 if (N1.getOpcode() == ISD::AND) {
3221 if (!N1.getNode()->hasOneUse())
3223 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3224 if (!N11C || N11C->getZExtValue() != 0xFF)
3226 N1 = N1.getOperand(0);
3227 LookPassAnd1 = true;
3230 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3232 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3234 if (!N0.getNode()->hasOneUse() ||
3235 !N1.getNode()->hasOneUse())
3238 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3239 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3242 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3245 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3246 SDValue N00 = N0->getOperand(0);
3247 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3248 if (!N00.getNode()->hasOneUse())
3250 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3251 if (!N001C || N001C->getZExtValue() != 0xFF)
3253 N00 = N00.getOperand(0);
3254 LookPassAnd0 = true;
3257 SDValue N10 = N1->getOperand(0);
3258 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3259 if (!N10.getNode()->hasOneUse())
3261 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3262 if (!N101C || N101C->getZExtValue() != 0xFF00)
3264 N10 = N10.getOperand(0);
3265 LookPassAnd1 = true;
3271 // Make sure everything beyond the low halfword gets set to zero since the SRL
3272 // 16 will clear the top bits.
3273 unsigned OpSizeInBits = VT.getSizeInBits();
3274 if (DemandHighBits && OpSizeInBits > 16) {
3275 // If the left-shift isn't masked out then the only way this is a bswap is
3276 // if all bits beyond the low 8 are 0. In that case the entire pattern
3277 // reduces to a left shift anyway: leave it for other parts of the combiner.
3281 // However, if the right shift isn't masked out then it might be because
3282 // it's not needed. See if we can spot that too.
3283 if (!LookPassAnd1 &&
3284 !DAG.MaskedValueIsZero(
3285 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3289 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3290 if (OpSizeInBits > 16) {
3292 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3293 DAG.getConstant(OpSizeInBits - 16, DL,
3294 getShiftAmountTy(VT)));
3299 /// Return true if the specified node is an element that makes up a 32-bit
3300 /// packed halfword byteswap.
3301 /// ((x & 0x000000ff) << 8) |
3302 /// ((x & 0x0000ff00) >> 8) |
3303 /// ((x & 0x00ff0000) << 8) |
3304 /// ((x & 0xff000000) >> 8)
3305 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3306 if (!N.getNode()->hasOneUse())
3309 unsigned Opc = N.getOpcode();
3310 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3313 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3318 switch (N1C->getZExtValue()) {
3321 case 0xFF: Num = 0; break;
3322 case 0xFF00: Num = 1; break;
3323 case 0xFF0000: Num = 2; break;
3324 case 0xFF000000: Num = 3; break;
3327 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3328 SDValue N0 = N.getOperand(0);
3329 if (Opc == ISD::AND) {
3330 if (Num == 0 || Num == 2) {
3332 // (x >> 8) & 0xff0000
3333 if (N0.getOpcode() != ISD::SRL)
3335 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3336 if (!C || C->getZExtValue() != 8)
3339 // (x << 8) & 0xff00
3340 // (x << 8) & 0xff000000
3341 if (N0.getOpcode() != ISD::SHL)
3343 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3344 if (!C || C->getZExtValue() != 8)
3347 } else if (Opc == ISD::SHL) {
3349 // (x & 0xff0000) << 8
3350 if (Num != 0 && Num != 2)
3352 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3353 if (!C || C->getZExtValue() != 8)
3355 } else { // Opc == ISD::SRL
3356 // (x & 0xff00) >> 8
3357 // (x & 0xff000000) >> 8
3358 if (Num != 1 && Num != 3)
3360 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3361 if (!C || C->getZExtValue() != 8)
3368 Parts[Num] = N0.getOperand(0).getNode();
3372 /// Match a 32-bit packed halfword bswap. That is
3373 /// ((x & 0x000000ff) << 8) |
3374 /// ((x & 0x0000ff00) >> 8) |
3375 /// ((x & 0x00ff0000) << 8) |
3376 /// ((x & 0xff000000) >> 8)
3377 /// => (rotl (bswap x), 16)
3378 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3379 if (!LegalOperations)
3382 EVT VT = N->getValueType(0);
3385 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3389 // (or (or (and), (and)), (or (and), (and)))
3390 // (or (or (or (and), (and)), (and)), (and))
3391 if (N0.getOpcode() != ISD::OR)
3393 SDValue N00 = N0.getOperand(0);
3394 SDValue N01 = N0.getOperand(1);
3395 SDNode *Parts[4] = {};
3397 if (N1.getOpcode() == ISD::OR &&
3398 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3399 // (or (or (and), (and)), (or (and), (and)))
3400 SDValue N000 = N00.getOperand(0);
3401 if (!isBSwapHWordElement(N000, Parts))
3404 SDValue N001 = N00.getOperand(1);
3405 if (!isBSwapHWordElement(N001, Parts))
3407 SDValue N010 = N01.getOperand(0);
3408 if (!isBSwapHWordElement(N010, Parts))
3410 SDValue N011 = N01.getOperand(1);
3411 if (!isBSwapHWordElement(N011, Parts))
3414 // (or (or (or (and), (and)), (and)), (and))
3415 if (!isBSwapHWordElement(N1, Parts))
3417 if (!isBSwapHWordElement(N01, Parts))
3419 if (N00.getOpcode() != ISD::OR)
3421 SDValue N000 = N00.getOperand(0);
3422 if (!isBSwapHWordElement(N000, Parts))
3424 SDValue N001 = N00.getOperand(1);
3425 if (!isBSwapHWordElement(N001, Parts))
3429 // Make sure the parts are all coming from the same node.
3430 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3434 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3435 SDValue(Parts[0], 0));
3437 // Result of the bswap should be rotated by 16. If it's not legal, then
3438 // do (x << 16) | (x >> 16).
3439 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3440 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3441 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3442 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3443 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3444 return DAG.getNode(ISD::OR, DL, VT,
3445 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3446 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3449 /// This contains all DAGCombine rules which reduce two values combined by
3450 /// an Or operation to a single value \see visitANDLike().
3451 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3452 EVT VT = N1.getValueType();
3453 // fold (or x, undef) -> -1
3454 if (!LegalOperations &&
3455 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3456 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3457 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3458 SDLoc(LocReference), VT);
3460 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3461 SDValue LL, LR, RL, RR, CC0, CC1;
3462 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3463 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3464 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3466 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3467 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3468 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3469 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3470 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3471 LR.getValueType(), LL, RL);
3472 AddToWorklist(ORNode.getNode());
3473 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3475 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3476 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3477 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3478 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3479 LR.getValueType(), LL, RL);
3480 AddToWorklist(ANDNode.getNode());
3481 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3484 // canonicalize equivalent to ll == rl
3485 if (LL == RR && LR == RL) {
3486 Op1 = ISD::getSetCCSwappedOperands(Op1);
3489 if (LL == RL && LR == RR) {
3490 bool isInteger = LL.getValueType().isInteger();
3491 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3492 if (Result != ISD::SETCC_INVALID &&
3493 (!LegalOperations ||
3494 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3495 TLI.isOperationLegal(ISD::SETCC,
3496 getSetCCResultType(N0.getValueType())))))
3497 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3502 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3503 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3504 // Don't increase # computations.
3505 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3506 // We can only do this xform if we know that bits from X that are set in C2
3507 // but not in C1 are already zero. Likewise for Y.
3508 if (const ConstantSDNode *N0O1C =
3509 getAsNonOpaqueConstant(N0.getOperand(1))) {
3510 if (const ConstantSDNode *N1O1C =
3511 getAsNonOpaqueConstant(N1.getOperand(1))) {
3512 // We can only do this xform if we know that bits from X that are set in
3513 // C2 but not in C1 are already zero. Likewise for Y.
3514 const APInt &LHSMask = N0O1C->getAPIntValue();
3515 const APInt &RHSMask = N1O1C->getAPIntValue();
3517 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3518 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3519 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3520 N0.getOperand(0), N1.getOperand(0));
3521 SDLoc DL(LocReference);
3522 return DAG.getNode(ISD::AND, DL, VT, X,
3523 DAG.getConstant(LHSMask | RHSMask, DL, VT));
3529 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3530 if (N0.getOpcode() == ISD::AND &&
3531 N1.getOpcode() == ISD::AND &&
3532 N0.getOperand(0) == N1.getOperand(0) &&
3533 // Don't increase # computations.
3534 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3535 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3536 N0.getOperand(1), N1.getOperand(1));
3537 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3543 SDValue DAGCombiner::visitOR(SDNode *N) {
3544 SDValue N0 = N->getOperand(0);
3545 SDValue N1 = N->getOperand(1);
3546 EVT VT = N1.getValueType();
3549 if (VT.isVector()) {
3550 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3553 // fold (or x, 0) -> x, vector edition
3554 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3556 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3559 // fold (or x, -1) -> -1, vector edition
3560 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3561 // do not return N0, because undef node may exist in N0
3562 return DAG.getConstant(
3563 APInt::getAllOnesValue(
3564 N0.getValueType().getScalarType().getSizeInBits()),
3565 SDLoc(N), N0.getValueType());
3566 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3567 // do not return N1, because undef node may exist in N1
3568 return DAG.getConstant(
3569 APInt::getAllOnesValue(
3570 N1.getValueType().getScalarType().getSizeInBits()),
3571 SDLoc(N), N1.getValueType());
3573 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3574 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3575 // Do this only if the resulting shuffle is legal.
3576 if (isa<ShuffleVectorSDNode>(N0) &&
3577 isa<ShuffleVectorSDNode>(N1) &&
3578 // Avoid folding a node with illegal type.
3579 TLI.isTypeLegal(VT) &&
3580 N0->getOperand(1) == N1->getOperand(1) &&
3581 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3582 bool CanFold = true;
3583 unsigned NumElts = VT.getVectorNumElements();
3584 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3585 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3586 // We construct two shuffle masks:
3587 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3588 // and N1 as the second operand.
3589 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3590 // and N0 as the second operand.
3591 // We do this because OR is commutable and therefore there might be
3592 // two ways to fold this node into a shuffle.
3593 SmallVector<int,4> Mask1;
3594 SmallVector<int,4> Mask2;
3596 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3597 int M0 = SV0->getMaskElt(i);
3598 int M1 = SV1->getMaskElt(i);
3600 // Both shuffle indexes are undef. Propagate Undef.
3601 if (M0 < 0 && M1 < 0) {
3602 Mask1.push_back(M0);
3603 Mask2.push_back(M0);
3607 if (M0 < 0 || M1 < 0 ||
3608 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3609 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3614 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3615 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3619 // Fold this sequence only if the resulting shuffle is 'legal'.
3620 if (TLI.isShuffleMaskLegal(Mask1, VT))
3621 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3622 N1->getOperand(0), &Mask1[0]);
3623 if (TLI.isShuffleMaskLegal(Mask2, VT))
3624 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3625 N0->getOperand(0), &Mask2[0]);
3630 // fold (or c1, c2) -> c1|c2
3631 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3632 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3633 if (N0C && N1C && !N1C->isOpaque())
3634 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3635 // canonicalize constant to RHS
3636 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3637 !isConstantIntBuildVectorOrConstantInt(N1))
3638 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3639 // fold (or x, 0) -> x
3640 if (isNullConstant(N1))
3642 // fold (or x, -1) -> -1
3643 if (isAllOnesConstant(N1))
3645 // fold (or x, c) -> c iff (x & ~c) == 0
3646 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3649 if (SDValue Combined = visitORLike(N0, N1, N))
3652 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3653 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3654 if (BSwap.getNode())
3656 BSwap = MatchBSwapHWordLow(N, N0, N1);
3657 if (BSwap.getNode())
3661 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3663 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3664 // iff (c1 & c2) == 0.
3665 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3666 isa<ConstantSDNode>(N0.getOperand(1))) {
3667 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3668 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3669 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3672 ISD::AND, SDLoc(N), VT,
3673 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3677 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3678 if (N0.getOpcode() == N1.getOpcode()) {
3679 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3680 if (Tmp.getNode()) return Tmp;
3683 // See if this is some rotate idiom.
3684 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3685 return SDValue(Rot, 0);
3687 // Simplify the operands using demanded-bits information.
3688 if (!VT.isVector() &&
3689 SimplifyDemandedBits(SDValue(N, 0)))
3690 return SDValue(N, 0);
3695 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3696 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3697 if (Op.getOpcode() == ISD::AND) {
3698 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3699 Mask = Op.getOperand(1);
3700 Op = Op.getOperand(0);
3706 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3714 // Return true if we can prove that, whenever Neg and Pos are both in the
3715 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3716 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3718 // (or (shift1 X, Neg), (shift2 X, Pos))
3720 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3721 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3722 // to consider shift amounts with defined behavior.
3723 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3724 // If OpSize is a power of 2 then:
3726 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3727 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3729 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3730 // for the stronger condition:
3732 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3734 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3735 // we can just replace Neg with Neg' for the rest of the function.
3737 // In other cases we check for the even stronger condition:
3739 // Neg == OpSize - Pos [B]
3741 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3742 // behavior if Pos == 0 (and consequently Neg == OpSize).
3744 // We could actually use [A] whenever OpSize is a power of 2, but the
3745 // only extra cases that it would match are those uninteresting ones
3746 // where Neg and Pos are never in range at the same time. E.g. for
3747 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3748 // as well as (sub 32, Pos), but:
3750 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3752 // always invokes undefined behavior for 32-bit X.
3754 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3755 unsigned MaskLoBits = 0;
3756 if (Neg.getOpcode() == ISD::AND &&
3757 isPowerOf2_64(OpSize) &&
3758 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3759 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3760 Neg = Neg.getOperand(0);
3761 MaskLoBits = Log2_64(OpSize);
3764 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3765 if (Neg.getOpcode() != ISD::SUB)
3767 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3770 SDValue NegOp1 = Neg.getOperand(1);
3772 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3773 // Pos'. The truncation is redundant for the purpose of the equality.
3775 Pos.getOpcode() == ISD::AND &&
3776 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3777 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3778 Pos = Pos.getOperand(0);
3780 // The condition we need is now:
3782 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3784 // If NegOp1 == Pos then we need:
3786 // OpSize & Mask == NegC & Mask
3788 // (because "x & Mask" is a truncation and distributes through subtraction).
3791 Width = NegC->getAPIntValue();
3792 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3793 // Then the condition we want to prove becomes:
3795 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3797 // which, again because "x & Mask" is a truncation, becomes:
3799 // NegC & Mask == (OpSize - PosC) & Mask
3800 // OpSize & Mask == (NegC + PosC) & Mask
3801 else if (Pos.getOpcode() == ISD::ADD &&
3802 Pos.getOperand(0) == NegOp1 &&
3803 Pos.getOperand(1).getOpcode() == ISD::Constant)
3804 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3805 NegC->getAPIntValue());
3809 // Now we just need to check that OpSize & Mask == Width & Mask.
3811 // Opsize & Mask is 0 since Mask is Opsize - 1.
3812 return Width.getLoBits(MaskLoBits) == 0;
3813 return Width == OpSize;
3816 // A subroutine of MatchRotate used once we have found an OR of two opposite
3817 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3818 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3819 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3820 // Neg with outer conversions stripped away.
3821 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3822 SDValue Neg, SDValue InnerPos,
3823 SDValue InnerNeg, unsigned PosOpcode,
3824 unsigned NegOpcode, SDLoc DL) {
3825 // fold (or (shl x, (*ext y)),
3826 // (srl x, (*ext (sub 32, y)))) ->
3827 // (rotl x, y) or (rotr x, (sub 32, y))
3829 // fold (or (shl x, (*ext (sub 32, y))),
3830 // (srl x, (*ext y))) ->
3831 // (rotr x, y) or (rotl x, (sub 32, y))
3832 EVT VT = Shifted.getValueType();
3833 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3834 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3835 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3836 HasPos ? Pos : Neg).getNode();
3842 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3843 // idioms for rotate, and if the target supports rotation instructions, generate
3845 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3846 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3847 EVT VT = LHS.getValueType();
3848 if (!TLI.isTypeLegal(VT)) return nullptr;
3850 // The target must have at least one rotate flavor.
3851 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3852 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3853 if (!HasROTL && !HasROTR) return nullptr;
3855 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3856 SDValue LHSShift; // The shift.
3857 SDValue LHSMask; // AND value if any.
3858 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3859 return nullptr; // Not part of a rotate.
3861 SDValue RHSShift; // The shift.
3862 SDValue RHSMask; // AND value if any.
3863 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3864 return nullptr; // Not part of a rotate.
3866 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3867 return nullptr; // Not shifting the same value.
3869 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3870 return nullptr; // Shifts must disagree.
3872 // Canonicalize shl to left side in a shl/srl pair.
3873 if (RHSShift.getOpcode() == ISD::SHL) {
3874 std::swap(LHS, RHS);
3875 std::swap(LHSShift, RHSShift);
3876 std::swap(LHSMask , RHSMask );
3879 unsigned OpSizeInBits = VT.getSizeInBits();
3880 SDValue LHSShiftArg = LHSShift.getOperand(0);
3881 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3882 SDValue RHSShiftArg = RHSShift.getOperand(0);
3883 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3885 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3886 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3887 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3888 RHSShiftAmt.getOpcode() == ISD::Constant) {
3889 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3890 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3891 if ((LShVal + RShVal) != OpSizeInBits)
3894 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3895 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3897 // If there is an AND of either shifted operand, apply it to the result.
3898 if (LHSMask.getNode() || RHSMask.getNode()) {
3899 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3901 if (LHSMask.getNode()) {
3902 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3903 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3905 if (RHSMask.getNode()) {
3906 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3907 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3910 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3913 return Rot.getNode();
3916 // If there is a mask here, and we have a variable shift, we can't be sure
3917 // that we're masking out the right stuff.
3918 if (LHSMask.getNode() || RHSMask.getNode())
3921 // If the shift amount is sign/zext/any-extended just peel it off.
3922 SDValue LExtOp0 = LHSShiftAmt;
3923 SDValue RExtOp0 = RHSShiftAmt;
3924 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3925 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3926 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3927 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3928 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3929 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3930 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3931 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3932 LExtOp0 = LHSShiftAmt.getOperand(0);
3933 RExtOp0 = RHSShiftAmt.getOperand(0);
3936 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3937 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3941 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3942 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3949 SDValue DAGCombiner::visitXOR(SDNode *N) {
3950 SDValue N0 = N->getOperand(0);
3951 SDValue N1 = N->getOperand(1);
3952 EVT VT = N0.getValueType();
3955 if (VT.isVector()) {
3956 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3959 // fold (xor x, 0) -> x, vector edition
3960 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3962 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3966 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3967 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3968 return DAG.getConstant(0, SDLoc(N), VT);
3969 // fold (xor x, undef) -> undef
3970 if (N0.getOpcode() == ISD::UNDEF)
3972 if (N1.getOpcode() == ISD::UNDEF)
3974 // fold (xor c1, c2) -> c1^c2
3975 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3976 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3978 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3979 // canonicalize constant to RHS
3980 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3981 !isConstantIntBuildVectorOrConstantInt(N1))
3982 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3983 // fold (xor x, 0) -> x
3984 if (isNullConstant(N1))
3987 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
3990 // fold !(x cc y) -> (x !cc y)
3991 SDValue LHS, RHS, CC;
3992 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3993 bool isInt = LHS.getValueType().isInteger();
3994 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3997 if (!LegalOperations ||
3998 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3999 switch (N0.getOpcode()) {
4001 llvm_unreachable("Unhandled SetCC Equivalent!");
4003 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4004 case ISD::SELECT_CC:
4005 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4006 N0.getOperand(3), NotCC);
4011 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4012 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4013 N0.getNode()->hasOneUse() &&
4014 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4015 SDValue V = N0.getOperand(0);
4017 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4018 DAG.getConstant(1, DL, V.getValueType()));
4019 AddToWorklist(V.getNode());
4020 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4023 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4024 if (isOneConstant(N1) && VT == MVT::i1 &&
4025 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4026 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4027 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4028 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4029 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4030 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4031 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4032 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4035 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4036 if (isAllOnesConstant(N1) &&
4037 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4038 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4039 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4040 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4041 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4042 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4043 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4044 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4047 // fold (xor (and x, y), y) -> (and (not x), y)
4048 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4049 N0->getOperand(1) == N1) {
4050 SDValue X = N0->getOperand(0);
4051 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4052 AddToWorklist(NotX.getNode());
4053 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4055 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4056 if (N1C && N0.getOpcode() == ISD::XOR) {
4057 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4059 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4060 DAG.getConstant(N1C->getAPIntValue() ^
4061 N00C->getAPIntValue(), DL, VT));
4063 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4065 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4066 DAG.getConstant(N1C->getAPIntValue() ^
4067 N01C->getAPIntValue(), DL, VT));
4070 // fold (xor x, x) -> 0
4072 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4074 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4075 // Here is a concrete example of this equivalence:
4077 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
4078 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4082 // i16 ~1 == 0b1111111111111110
4083 // i16 rol(~1, 14) == 0b1011111111111111
4085 // Some additional tips to help conceptualize this transform:
4086 // - Try to see the operation as placing a single zero in a value of all ones.
4087 // - There exists no value for x which would allow the result to contain zero.
4088 // - Values of x larger than the bitwidth are undefined and do not require a
4089 // consistent result.
4090 // - Pushing the zero left requires shifting one bits in from the right.
4091 // A rotate left of ~1 is a nice way of achieving the desired result.
4092 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4093 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4095 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4099 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4100 if (N0.getOpcode() == N1.getOpcode()) {
4101 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4102 if (Tmp.getNode()) return Tmp;
4105 // Simplify the expression using non-local knowledge.
4106 if (!VT.isVector() &&
4107 SimplifyDemandedBits(SDValue(N, 0)))
4108 return SDValue(N, 0);
4113 /// Handle transforms common to the three shifts, when the shift amount is a
4115 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4116 SDNode *LHS = N->getOperand(0).getNode();
4117 if (!LHS->hasOneUse()) return SDValue();
4119 // We want to pull some binops through shifts, so that we have (and (shift))
4120 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4121 // thing happens with address calculations, so it's important to canonicalize
4123 bool HighBitSet = false; // Can we transform this if the high bit is set?
4125 switch (LHS->getOpcode()) {
4126 default: return SDValue();
4129 HighBitSet = false; // We can only transform sra if the high bit is clear.
4132 HighBitSet = true; // We can only transform sra if the high bit is set.
4135 if (N->getOpcode() != ISD::SHL)
4136 return SDValue(); // only shl(add) not sr[al](add).
4137 HighBitSet = false; // We can only transform sra if the high bit is clear.
4141 // We require the RHS of the binop to be a constant and not opaque as well.
4142 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4143 if (!BinOpCst) return SDValue();
4145 // FIXME: disable this unless the input to the binop is a shift by a constant.
4146 // If it is not a shift, it pessimizes some common cases like:
4148 // void foo(int *X, int i) { X[i & 1235] = 1; }
4149 // int bar(int *X, int i) { return X[i & 255]; }
4150 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4151 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4152 BinOpLHSVal->getOpcode() != ISD::SRA &&
4153 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4154 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4157 EVT VT = N->getValueType(0);
4159 // If this is a signed shift right, and the high bit is modified by the
4160 // logical operation, do not perform the transformation. The highBitSet
4161 // boolean indicates the value of the high bit of the constant which would
4162 // cause it to be modified for this operation.
4163 if (N->getOpcode() == ISD::SRA) {
4164 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4165 if (BinOpRHSSignSet != HighBitSet)
4169 if (!TLI.isDesirableToCommuteWithShift(LHS))
4172 // Fold the constants, shifting the binop RHS by the shift amount.
4173 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4175 LHS->getOperand(1), N->getOperand(1));
4176 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4178 // Create the new shift.
4179 SDValue NewShift = DAG.getNode(N->getOpcode(),
4180 SDLoc(LHS->getOperand(0)),
4181 VT, LHS->getOperand(0), N->getOperand(1));
4183 // Create the new binop.
4184 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4187 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4188 assert(N->getOpcode() == ISD::TRUNCATE);
4189 assert(N->getOperand(0).getOpcode() == ISD::AND);
4191 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4192 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4193 SDValue N01 = N->getOperand(0).getOperand(1);
4195 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4196 if (!N01C->isOpaque()) {
4197 EVT TruncVT = N->getValueType(0);
4198 SDValue N00 = N->getOperand(0).getOperand(0);
4199 APInt TruncC = N01C->getAPIntValue();
4200 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4203 return DAG.getNode(ISD::AND, DL, TruncVT,
4204 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4205 DAG.getConstant(TruncC, DL, TruncVT));
4213 SDValue DAGCombiner::visitRotate(SDNode *N) {
4214 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4215 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4216 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4217 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4218 if (NewOp1.getNode())
4219 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4220 N->getOperand(0), NewOp1);
4225 SDValue DAGCombiner::visitSHL(SDNode *N) {
4226 SDValue N0 = N->getOperand(0);
4227 SDValue N1 = N->getOperand(1);
4228 EVT VT = N0.getValueType();
4229 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4232 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4233 if (VT.isVector()) {
4234 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4237 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4238 // If setcc produces all-one true value then:
4239 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4240 if (N1CV && N1CV->isConstant()) {
4241 if (N0.getOpcode() == ISD::AND) {
4242 SDValue N00 = N0->getOperand(0);
4243 SDValue N01 = N0->getOperand(1);
4244 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4246 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4247 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4248 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4249 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4251 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4254 N1C = isConstOrConstSplat(N1);
4259 // fold (shl c1, c2) -> c1<<c2
4260 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4261 if (N0C && N1C && !N1C->isOpaque())
4262 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4263 // fold (shl 0, x) -> 0
4264 if (isNullConstant(N0))
4266 // fold (shl x, c >= size(x)) -> undef
4267 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4268 return DAG.getUNDEF(VT);
4269 // fold (shl x, 0) -> x
4270 if (N1C && N1C->isNullValue())
4272 // fold (shl undef, x) -> 0
4273 if (N0.getOpcode() == ISD::UNDEF)
4274 return DAG.getConstant(0, SDLoc(N), VT);
4275 // if (shl x, c) is known to be zero, return 0
4276 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4277 APInt::getAllOnesValue(OpSizeInBits)))
4278 return DAG.getConstant(0, SDLoc(N), VT);
4279 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4280 if (N1.getOpcode() == ISD::TRUNCATE &&
4281 N1.getOperand(0).getOpcode() == ISD::AND) {
4282 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4283 if (NewOp1.getNode())
4284 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4287 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4288 return SDValue(N, 0);
4290 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4291 if (N1C && N0.getOpcode() == ISD::SHL) {
4292 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4293 uint64_t c1 = N0C1->getZExtValue();
4294 uint64_t c2 = N1C->getZExtValue();
4296 if (c1 + c2 >= OpSizeInBits)
4297 return DAG.getConstant(0, DL, VT);
4298 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4299 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4303 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4304 // For this to be valid, the second form must not preserve any of the bits
4305 // that are shifted out by the inner shift in the first form. This means
4306 // the outer shift size must be >= the number of bits added by the ext.
4307 // As a corollary, we don't care what kind of ext it is.
4308 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4309 N0.getOpcode() == ISD::ANY_EXTEND ||
4310 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4311 N0.getOperand(0).getOpcode() == ISD::SHL) {
4312 SDValue N0Op0 = N0.getOperand(0);
4313 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4314 uint64_t c1 = N0Op0C1->getZExtValue();
4315 uint64_t c2 = N1C->getZExtValue();
4316 EVT InnerShiftVT = N0Op0.getValueType();
4317 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4318 if (c2 >= OpSizeInBits - InnerShiftSize) {
4320 if (c1 + c2 >= OpSizeInBits)
4321 return DAG.getConstant(0, DL, VT);
4322 return DAG.getNode(ISD::SHL, DL, VT,
4323 DAG.getNode(N0.getOpcode(), DL, VT,
4324 N0Op0->getOperand(0)),
4325 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4330 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4331 // Only fold this if the inner zext has no other uses to avoid increasing
4332 // the total number of instructions.
4333 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4334 N0.getOperand(0).getOpcode() == ISD::SRL) {
4335 SDValue N0Op0 = N0.getOperand(0);
4336 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4337 uint64_t c1 = N0Op0C1->getZExtValue();
4338 if (c1 < VT.getScalarSizeInBits()) {
4339 uint64_t c2 = N1C->getZExtValue();
4341 SDValue NewOp0 = N0.getOperand(0);
4342 EVT CountVT = NewOp0.getOperand(1).getValueType();
4344 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4346 DAG.getConstant(c2, DL, CountVT));
4347 AddToWorklist(NewSHL.getNode());
4348 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4354 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4355 // (and (srl x, (sub c1, c2), MASK)
4356 // Only fold this if the inner shift has no other uses -- if it does, folding
4357 // this will increase the total number of instructions.
4358 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4359 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4360 uint64_t c1 = N0C1->getZExtValue();
4361 if (c1 < OpSizeInBits) {
4362 uint64_t c2 = N1C->getZExtValue();
4363 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4366 Mask = Mask.shl(c2 - c1);
4368 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4369 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4371 Mask = Mask.lshr(c1 - c2);
4373 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4374 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4377 return DAG.getNode(ISD::AND, DL, VT, Shift,
4378 DAG.getConstant(Mask, DL, VT));
4382 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4383 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4384 unsigned BitSize = VT.getScalarSizeInBits();
4386 SDValue HiBitsMask =
4387 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4388 BitSize - N1C->getZExtValue()),
4390 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4394 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4395 // Variant of version done on multiply, except mul by a power of 2 is turned
4398 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4399 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4400 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4401 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4402 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4403 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4406 if (N1C && !N1C->isOpaque()) {
4407 SDValue NewSHL = visitShiftByConstant(N, N1C);
4408 if (NewSHL.getNode())
4415 SDValue DAGCombiner::visitSRA(SDNode *N) {
4416 SDValue N0 = N->getOperand(0);
4417 SDValue N1 = N->getOperand(1);
4418 EVT VT = N0.getValueType();
4419 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4422 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4423 if (VT.isVector()) {
4424 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4427 N1C = isConstOrConstSplat(N1);
4430 // fold (sra c1, c2) -> (sra c1, c2)
4431 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4432 if (N0C && N1C && !N1C->isOpaque())
4433 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4434 // fold (sra 0, x) -> 0
4435 if (isNullConstant(N0))
4437 // fold (sra -1, x) -> -1
4438 if (isAllOnesConstant(N0))
4440 // fold (sra x, (setge c, size(x))) -> undef
4441 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4442 return DAG.getUNDEF(VT);
4443 // fold (sra x, 0) -> x
4444 if (N1C && N1C->isNullValue())
4446 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4448 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4449 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4450 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4452 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4453 ExtVT, VT.getVectorNumElements());
4454 if ((!LegalOperations ||
4455 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4456 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4457 N0.getOperand(0), DAG.getValueType(ExtVT));
4460 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4461 if (N1C && N0.getOpcode() == ISD::SRA) {
4462 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4463 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4464 if (Sum >= OpSizeInBits)
4465 Sum = OpSizeInBits - 1;
4467 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4468 DAG.getConstant(Sum, DL, N1.getValueType()));
4472 // fold (sra (shl X, m), (sub result_size, n))
4473 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4474 // result_size - n != m.
4475 // If truncate is free for the target sext(shl) is likely to result in better
4477 if (N0.getOpcode() == ISD::SHL && N1C) {
4478 // Get the two constanst of the shifts, CN0 = m, CN = n.
4479 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4481 LLVMContext &Ctx = *DAG.getContext();
4482 // Determine what the truncate's result bitsize and type would be.
4483 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4486 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4488 // Determine the residual right-shift amount.
4489 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4491 // If the shift is not a no-op (in which case this should be just a sign
4492 // extend already), the truncated to type is legal, sign_extend is legal
4493 // on that type, and the truncate to that type is both legal and free,
4494 // perform the transform.
4495 if ((ShiftAmt > 0) &&
4496 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4497 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4498 TLI.isTruncateFree(VT, TruncVT)) {
4501 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4502 getShiftAmountTy(N0.getOperand(0).getValueType()));
4503 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4504 N0.getOperand(0), Amt);
4505 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4507 return DAG.getNode(ISD::SIGN_EXTEND, DL,
4508 N->getValueType(0), Trunc);
4513 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4514 if (N1.getOpcode() == ISD::TRUNCATE &&
4515 N1.getOperand(0).getOpcode() == ISD::AND) {
4516 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4517 if (NewOp1.getNode())
4518 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4521 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4522 // if c1 is equal to the number of bits the trunc removes
4523 if (N0.getOpcode() == ISD::TRUNCATE &&
4524 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4525 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4526 N0.getOperand(0).hasOneUse() &&
4527 N0.getOperand(0).getOperand(1).hasOneUse() &&
4529 SDValue N0Op0 = N0.getOperand(0);
4530 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4531 unsigned LargeShiftVal = LargeShift->getZExtValue();
4532 EVT LargeVT = N0Op0.getValueType();
4534 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4537 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4538 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4539 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4540 N0Op0.getOperand(0), Amt);
4541 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4546 // Simplify, based on bits shifted out of the LHS.
4547 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4548 return SDValue(N, 0);
4551 // If the sign bit is known to be zero, switch this to a SRL.
4552 if (DAG.SignBitIsZero(N0))
4553 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4555 if (N1C && !N1C->isOpaque()) {
4556 SDValue NewSRA = visitShiftByConstant(N, N1C);
4557 if (NewSRA.getNode())
4564 SDValue DAGCombiner::visitSRL(SDNode *N) {
4565 SDValue N0 = N->getOperand(0);
4566 SDValue N1 = N->getOperand(1);
4567 EVT VT = N0.getValueType();
4568 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4571 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4572 if (VT.isVector()) {
4573 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4576 N1C = isConstOrConstSplat(N1);
4579 // fold (srl c1, c2) -> c1 >>u c2
4580 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4581 if (N0C && N1C && !N1C->isOpaque())
4582 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4583 // fold (srl 0, x) -> 0
4584 if (isNullConstant(N0))
4586 // fold (srl x, c >= size(x)) -> undef
4587 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4588 return DAG.getUNDEF(VT);
4589 // fold (srl x, 0) -> x
4590 if (N1C && N1C->isNullValue())
4592 // if (srl x, c) is known to be zero, return 0
4593 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4594 APInt::getAllOnesValue(OpSizeInBits)))
4595 return DAG.getConstant(0, SDLoc(N), VT);
4597 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4598 if (N1C && N0.getOpcode() == ISD::SRL) {
4599 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4600 uint64_t c1 = N01C->getZExtValue();
4601 uint64_t c2 = N1C->getZExtValue();
4603 if (c1 + c2 >= OpSizeInBits)
4604 return DAG.getConstant(0, DL, VT);
4605 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4606 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4610 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4611 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4612 N0.getOperand(0).getOpcode() == ISD::SRL &&
4613 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4615 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4616 uint64_t c2 = N1C->getZExtValue();
4617 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4618 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4619 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4620 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4621 if (c1 + OpSizeInBits == InnerShiftSize) {
4623 if (c1 + c2 >= InnerShiftSize)
4624 return DAG.getConstant(0, DL, VT);
4625 return DAG.getNode(ISD::TRUNCATE, DL, VT,
4626 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4627 N0.getOperand(0)->getOperand(0),
4628 DAG.getConstant(c1 + c2, DL,
4633 // fold (srl (shl x, c), c) -> (and x, cst2)
4634 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4635 unsigned BitSize = N0.getScalarValueSizeInBits();
4636 if (BitSize <= 64) {
4637 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4639 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4640 DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4644 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4645 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4646 // Shifting in all undef bits?
4647 EVT SmallVT = N0.getOperand(0).getValueType();
4648 unsigned BitSize = SmallVT.getScalarSizeInBits();
4649 if (N1C->getZExtValue() >= BitSize)
4650 return DAG.getUNDEF(VT);
4652 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4653 uint64_t ShiftAmt = N1C->getZExtValue();
4655 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4657 DAG.getConstant(ShiftAmt, DL0,
4658 getShiftAmountTy(SmallVT)));
4659 AddToWorklist(SmallShift.getNode());
4660 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4662 return DAG.getNode(ISD::AND, DL, VT,
4663 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4664 DAG.getConstant(Mask, DL, VT));
4668 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4669 // bit, which is unmodified by sra.
4670 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4671 if (N0.getOpcode() == ISD::SRA)
4672 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4675 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4676 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4677 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4678 APInt KnownZero, KnownOne;
4679 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4681 // If any of the input bits are KnownOne, then the input couldn't be all
4682 // zeros, thus the result of the srl will always be zero.
4683 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4685 // If all of the bits input the to ctlz node are known to be zero, then
4686 // the result of the ctlz is "32" and the result of the shift is one.
4687 APInt UnknownBits = ~KnownZero;
4688 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4690 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4691 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4692 // Okay, we know that only that the single bit specified by UnknownBits
4693 // could be set on input to the CTLZ node. If this bit is set, the SRL
4694 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4695 // to an SRL/XOR pair, which is likely to simplify more.
4696 unsigned ShAmt = UnknownBits.countTrailingZeros();
4697 SDValue Op = N0.getOperand(0);
4701 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4702 DAG.getConstant(ShAmt, DL,
4703 getShiftAmountTy(Op.getValueType())));
4704 AddToWorklist(Op.getNode());
4708 return DAG.getNode(ISD::XOR, DL, VT,
4709 Op, DAG.getConstant(1, DL, VT));
4713 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4714 if (N1.getOpcode() == ISD::TRUNCATE &&
4715 N1.getOperand(0).getOpcode() == ISD::AND) {
4716 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4717 if (NewOp1.getNode())
4718 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4721 // fold operands of srl based on knowledge that the low bits are not
4723 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4724 return SDValue(N, 0);
4726 if (N1C && !N1C->isOpaque()) {
4727 SDValue NewSRL = visitShiftByConstant(N, N1C);
4728 if (NewSRL.getNode())
4732 // Attempt to convert a srl of a load into a narrower zero-extending load.
4733 SDValue NarrowLoad = ReduceLoadWidth(N);
4734 if (NarrowLoad.getNode())
4737 // Here is a common situation. We want to optimize:
4740 // %b = and i32 %a, 2
4741 // %c = srl i32 %b, 1
4742 // brcond i32 %c ...
4748 // %c = setcc eq %b, 0
4751 // However when after the source operand of SRL is optimized into AND, the SRL
4752 // itself may not be optimized further. Look for it and add the BRCOND into
4754 if (N->hasOneUse()) {
4755 SDNode *Use = *N->use_begin();
4756 if (Use->getOpcode() == ISD::BRCOND)
4758 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4759 // Also look pass the truncate.
4760 Use = *Use->use_begin();
4761 if (Use->getOpcode() == ISD::BRCOND)
4769 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4770 SDValue N0 = N->getOperand(0);
4771 EVT VT = N->getValueType(0);
4773 // fold (bswap c1) -> c2
4774 if (isConstantIntBuildVectorOrConstantInt(N0))
4775 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4776 // fold (bswap (bswap x)) -> x
4777 if (N0.getOpcode() == ISD::BSWAP)
4778 return N0->getOperand(0);
4782 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4783 SDValue N0 = N->getOperand(0);
4784 EVT VT = N->getValueType(0);
4786 // fold (ctlz c1) -> c2
4787 if (isConstantIntBuildVectorOrConstantInt(N0))
4788 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4792 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4793 SDValue N0 = N->getOperand(0);
4794 EVT VT = N->getValueType(0);
4796 // fold (ctlz_zero_undef c1) -> c2
4797 if (isConstantIntBuildVectorOrConstantInt(N0))
4798 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4802 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4803 SDValue N0 = N->getOperand(0);
4804 EVT VT = N->getValueType(0);
4806 // fold (cttz c1) -> c2
4807 if (isConstantIntBuildVectorOrConstantInt(N0))
4808 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4812 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4813 SDValue N0 = N->getOperand(0);
4814 EVT VT = N->getValueType(0);
4816 // fold (cttz_zero_undef c1) -> c2
4817 if (isConstantIntBuildVectorOrConstantInt(N0))
4818 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4822 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4823 SDValue N0 = N->getOperand(0);
4824 EVT VT = N->getValueType(0);
4826 // fold (ctpop c1) -> c2
4827 if (isConstantIntBuildVectorOrConstantInt(N0))
4828 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4833 /// \brief Generate Min/Max node
4834 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4835 SDValue True, SDValue False,
4836 ISD::CondCode CC, const TargetLowering &TLI,
4837 SelectionDAG &DAG) {
4838 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4848 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4849 if (TLI.isOperationLegal(Opcode, VT))
4850 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4859 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4860 if (TLI.isOperationLegal(Opcode, VT))
4861 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4869 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4870 SDValue N0 = N->getOperand(0);
4871 SDValue N1 = N->getOperand(1);
4872 SDValue N2 = N->getOperand(2);
4873 EVT VT = N->getValueType(0);
4874 EVT VT0 = N0.getValueType();
4876 // fold (select C, X, X) -> X
4879 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4880 // fold (select true, X, Y) -> X
4881 // fold (select false, X, Y) -> Y
4882 return !N0C->isNullValue() ? N1 : N2;
4884 // fold (select C, 1, X) -> (or C, X)
4885 if (VT == MVT::i1 && isOneConstant(N1))
4886 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4887 // fold (select C, 0, 1) -> (xor C, 1)
4888 // We can't do this reliably if integer based booleans have different contents
4889 // to floating point based booleans. This is because we can't tell whether we
4890 // have an integer-based boolean or a floating-point-based boolean unless we
4891 // can find the SETCC that produced it and inspect its operands. This is
4892 // fairly easy if C is the SETCC node, but it can potentially be
4893 // undiscoverable (or not reasonably discoverable). For example, it could be
4894 // in another basic block or it could require searching a complicated
4896 if (VT.isInteger() &&
4897 (VT0 == MVT::i1 || (VT0.isInteger() &&
4898 TLI.getBooleanContents(false, false) ==
4899 TLI.getBooleanContents(false, true) &&
4900 TLI.getBooleanContents(false, false) ==
4901 TargetLowering::ZeroOrOneBooleanContent)) &&
4902 isNullConstant(N1) && isOneConstant(N2)) {
4906 return DAG.getNode(ISD::XOR, DL, VT0,
4907 N0, DAG.getConstant(1, DL, VT0));
4910 XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4911 N0, DAG.getConstant(1, DL0, VT0));
4912 AddToWorklist(XORNode.getNode());
4914 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4915 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4917 // fold (select C, 0, X) -> (and (not C), X)
4918 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4919 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4920 AddToWorklist(NOTNode.getNode());
4921 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4923 // fold (select C, X, 1) -> (or (not C), X)
4924 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
4925 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4926 AddToWorklist(NOTNode.getNode());
4927 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4929 // fold (select C, X, 0) -> (and C, X)
4930 if (VT == MVT::i1 && isNullConstant(N2))
4931 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4932 // fold (select X, X, Y) -> (or X, Y)
4933 // fold (select X, 1, Y) -> (or X, Y)
4934 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
4935 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4936 // fold (select X, Y, X) -> (and X, Y)
4937 // fold (select X, Y, 0) -> (and X, Y)
4938 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
4939 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4941 // If we can fold this based on the true/false value, do so.
4942 if (SimplifySelectOps(N, N1, N2))
4943 return SDValue(N, 0); // Don't revisit N.
4945 // fold selects based on a setcc into other things, such as min/max/abs
4946 if (N0.getOpcode() == ISD::SETCC) {
4947 // select x, y (fcmp lt x, y) -> fminnum x, y
4948 // select x, y (fcmp gt x, y) -> fmaxnum x, y
4950 // This is OK if we don't care about what happens if either operand is a
4954 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4955 // no signed zeros as well as no nans.
4956 const TargetOptions &Options = DAG.getTarget().Options;
4957 if (Options.UnsafeFPMath &&
4958 VT.isFloatingPoint() && N0.hasOneUse() &&
4959 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4960 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4963 combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4964 N1, N2, CC, TLI, DAG);
4969 if ((!LegalOperations &&
4970 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4971 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4972 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4973 N0.getOperand(0), N0.getOperand(1),
4974 N1, N2, N0.getOperand(2));
4975 return SimplifySelect(SDLoc(N), N0, N1, N2);
4978 if (VT0 == MVT::i1) {
4979 if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4980 // select (and Cond0, Cond1), X, Y
4981 // -> select Cond0, (select Cond1, X, Y), Y
4982 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4983 SDValue Cond0 = N0->getOperand(0);
4984 SDValue Cond1 = N0->getOperand(1);
4985 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4986 N1.getValueType(), Cond1, N1, N2);
4987 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4990 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4991 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4992 SDValue Cond0 = N0->getOperand(0);
4993 SDValue Cond1 = N0->getOperand(1);
4994 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4995 N1.getValueType(), Cond1, N1, N2);
4996 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5001 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5002 if (N1->getOpcode() == ISD::SELECT) {
5003 SDValue N1_0 = N1->getOperand(0);
5004 SDValue N1_1 = N1->getOperand(1);
5005 SDValue N1_2 = N1->getOperand(2);
5006 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5007 // Create the actual and node if we can generate good code for it.
5008 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
5009 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5011 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5014 // Otherwise see if we can optimize the "and" to a better pattern.
5015 if (SDValue Combined = visitANDLike(N0, N1_0, N))
5016 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5020 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5021 if (N2->getOpcode() == ISD::SELECT) {
5022 SDValue N2_0 = N2->getOperand(0);
5023 SDValue N2_1 = N2->getOperand(1);
5024 SDValue N2_2 = N2->getOperand(2);
5025 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5026 // Create the actual or node if we can generate good code for it.
5027 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
5028 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5030 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5033 // Otherwise see if we can optimize to a better pattern.
5034 if (SDValue Combined = visitORLike(N0, N2_0, N))
5035 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5045 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5048 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5050 // Split the inputs.
5051 SDValue Lo, Hi, LL, LH, RL, RH;
5052 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5053 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5055 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5056 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5058 return std::make_pair(Lo, Hi);
5061 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5062 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5063 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5065 SDValue Cond = N->getOperand(0);
5066 SDValue LHS = N->getOperand(1);
5067 SDValue RHS = N->getOperand(2);
5068 EVT VT = N->getValueType(0);
5069 int NumElems = VT.getVectorNumElements();
5070 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5071 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5072 Cond.getOpcode() == ISD::BUILD_VECTOR);
5074 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5075 // binary ones here.
5076 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5079 // We're sure we have an even number of elements due to the
5080 // concat_vectors we have as arguments to vselect.
5081 // Skip BV elements until we find one that's not an UNDEF
5082 // After we find an UNDEF element, keep looping until we get to half the
5083 // length of the BV and see if all the non-undef nodes are the same.
5084 ConstantSDNode *BottomHalf = nullptr;
5085 for (int i = 0; i < NumElems / 2; ++i) {
5086 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5089 if (BottomHalf == nullptr)
5090 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5091 else if (Cond->getOperand(i).getNode() != BottomHalf)
5095 // Do the same for the second half of the BuildVector
5096 ConstantSDNode *TopHalf = nullptr;
5097 for (int i = NumElems / 2; i < NumElems; ++i) {
5098 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5101 if (TopHalf == nullptr)
5102 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5103 else if (Cond->getOperand(i).getNode() != TopHalf)
5107 assert(TopHalf && BottomHalf &&
5108 "One half of the selector was all UNDEFs and the other was all the "
5109 "same value. This should have been addressed before this function.");
5111 ISD::CONCAT_VECTORS, dl, VT,
5112 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5113 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5116 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5118 if (Level >= AfterLegalizeTypes)
5121 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5122 SDValue Mask = MSC->getMask();
5123 SDValue Data = MSC->getValue();
5126 // If the MSCATTER data type requires splitting and the mask is provided by a
5127 // SETCC, then split both nodes and its operands before legalization. This
5128 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5129 // and enables future optimizations (e.g. min/max pattern matching on X86).
5130 if (Mask.getOpcode() != ISD::SETCC)
5133 // Check if any splitting is required.
5134 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5135 TargetLowering::TypeSplitVector)
5137 SDValue MaskLo, MaskHi, Lo, Hi;
5138 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5141 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5143 SDValue Chain = MSC->getChain();
5145 EVT MemoryVT = MSC->getMemoryVT();
5146 unsigned Alignment = MSC->getOriginalAlignment();
5148 EVT LoMemVT, HiMemVT;
5149 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5151 SDValue DataLo, DataHi;
5152 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5154 SDValue BasePtr = MSC->getBasePtr();
5155 SDValue IndexLo, IndexHi;
5156 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5158 MachineMemOperand *MMO = DAG.getMachineFunction().
5159 getMachineMemOperand(MSC->getPointerInfo(),
5160 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5161 Alignment, MSC->getAAInfo(), MSC->getRanges());
5163 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5164 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5167 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5168 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5171 AddToWorklist(Lo.getNode());
5172 AddToWorklist(Hi.getNode());
5174 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5177 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5179 if (Level >= AfterLegalizeTypes)
5182 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5183 SDValue Mask = MST->getMask();
5184 SDValue Data = MST->getValue();
5187 // If the MSTORE data type requires splitting and the mask is provided by a
5188 // SETCC, then split both nodes and its operands before legalization. This
5189 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5190 // and enables future optimizations (e.g. min/max pattern matching on X86).
5191 if (Mask.getOpcode() == ISD::SETCC) {
5193 // Check if any splitting is required.
5194 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5195 TargetLowering::TypeSplitVector)
5198 SDValue MaskLo, MaskHi, Lo, Hi;
5199 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5202 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5204 SDValue Chain = MST->getChain();
5205 SDValue Ptr = MST->getBasePtr();
5207 EVT MemoryVT = MST->getMemoryVT();
5208 unsigned Alignment = MST->getOriginalAlignment();
5210 // if Alignment is equal to the vector size,
5211 // take the half of it for the second part
5212 unsigned SecondHalfAlignment =
5213 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5214 Alignment/2 : Alignment;
5216 EVT LoMemVT, HiMemVT;
5217 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5219 SDValue DataLo, DataHi;
5220 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5222 MachineMemOperand *MMO = DAG.getMachineFunction().
5223 getMachineMemOperand(MST->getPointerInfo(),
5224 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5225 Alignment, MST->getAAInfo(), MST->getRanges());
5227 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5228 MST->isTruncatingStore());
5230 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5231 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5232 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5234 MMO = DAG.getMachineFunction().
5235 getMachineMemOperand(MST->getPointerInfo(),
5236 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5237 SecondHalfAlignment, MST->getAAInfo(),
5240 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5241 MST->isTruncatingStore());
5243 AddToWorklist(Lo.getNode());
5244 AddToWorklist(Hi.getNode());
5246 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5251 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5253 if (Level >= AfterLegalizeTypes)
5256 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5257 SDValue Mask = MGT->getMask();
5260 // If the MGATHER result requires splitting and the mask is provided by a
5261 // SETCC, then split both nodes and its operands before legalization. This
5262 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5263 // and enables future optimizations (e.g. min/max pattern matching on X86).
5265 if (Mask.getOpcode() != ISD::SETCC)
5268 EVT VT = N->getValueType(0);
5270 // Check if any splitting is required.
5271 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5272 TargetLowering::TypeSplitVector)
5275 SDValue MaskLo, MaskHi, Lo, Hi;
5276 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5278 SDValue Src0 = MGT->getValue();
5279 SDValue Src0Lo, Src0Hi;
5280 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5283 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5285 SDValue Chain = MGT->getChain();
5286 EVT MemoryVT = MGT->getMemoryVT();
5287 unsigned Alignment = MGT->getOriginalAlignment();
5289 EVT LoMemVT, HiMemVT;
5290 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5292 SDValue BasePtr = MGT->getBasePtr();
5293 SDValue Index = MGT->getIndex();
5294 SDValue IndexLo, IndexHi;
5295 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5297 MachineMemOperand *MMO = DAG.getMachineFunction().
5298 getMachineMemOperand(MGT->getPointerInfo(),
5299 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5300 Alignment, MGT->getAAInfo(), MGT->getRanges());
5302 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5303 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5306 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5307 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5310 AddToWorklist(Lo.getNode());
5311 AddToWorklist(Hi.getNode());
5313 // Build a factor node to remember that this load is independent of the
5315 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5318 // Legalized the chain result - switch anything that used the old chain to
5320 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5322 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5324 SDValue RetOps[] = { GatherRes, Chain };
5325 return DAG.getMergeValues(RetOps, DL);
5328 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5330 if (Level >= AfterLegalizeTypes)
5333 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5334 SDValue Mask = MLD->getMask();
5337 // If the MLOAD result requires splitting and the mask is provided by a
5338 // SETCC, then split both nodes and its operands before legalization. This
5339 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5340 // and enables future optimizations (e.g. min/max pattern matching on X86).
5342 if (Mask.getOpcode() == ISD::SETCC) {
5343 EVT VT = N->getValueType(0);
5345 // Check if any splitting is required.
5346 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5347 TargetLowering::TypeSplitVector)
5350 SDValue MaskLo, MaskHi, Lo, Hi;
5351 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5353 SDValue Src0 = MLD->getSrc0();
5354 SDValue Src0Lo, Src0Hi;
5355 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5358 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5360 SDValue Chain = MLD->getChain();
5361 SDValue Ptr = MLD->getBasePtr();
5362 EVT MemoryVT = MLD->getMemoryVT();
5363 unsigned Alignment = MLD->getOriginalAlignment();
5365 // if Alignment is equal to the vector size,
5366 // take the half of it for the second part
5367 unsigned SecondHalfAlignment =
5368 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5369 Alignment/2 : Alignment;
5371 EVT LoMemVT, HiMemVT;
5372 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5374 MachineMemOperand *MMO = DAG.getMachineFunction().
5375 getMachineMemOperand(MLD->getPointerInfo(),
5376 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5377 Alignment, MLD->getAAInfo(), MLD->getRanges());
5379 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5382 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5383 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5384 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5386 MMO = DAG.getMachineFunction().
5387 getMachineMemOperand(MLD->getPointerInfo(),
5388 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5389 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5391 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5394 AddToWorklist(Lo.getNode());
5395 AddToWorklist(Hi.getNode());
5397 // Build a factor node to remember that this load is independent of the
5399 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5402 // Legalized the chain result - switch anything that used the old chain to
5404 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5406 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5408 SDValue RetOps[] = { LoadRes, Chain };
5409 return DAG.getMergeValues(RetOps, DL);
5414 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5415 SDValue N0 = N->getOperand(0);
5416 SDValue N1 = N->getOperand(1);
5417 SDValue N2 = N->getOperand(2);
5420 // Canonicalize integer abs.
5421 // vselect (setg[te] X, 0), X, -X ->
5422 // vselect (setgt X, -1), X, -X ->
5423 // vselect (setl[te] X, 0), -X, X ->
5424 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5425 if (N0.getOpcode() == ISD::SETCC) {
5426 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5427 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5429 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5431 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5432 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5433 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5434 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5435 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5436 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5437 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5440 EVT VT = LHS.getValueType();
5441 SDValue Shift = DAG.getNode(
5442 ISD::SRA, DL, VT, LHS,
5443 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5444 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5445 AddToWorklist(Shift.getNode());
5446 AddToWorklist(Add.getNode());
5447 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5451 if (SimplifySelectOps(N, N1, N2))
5452 return SDValue(N, 0); // Don't revisit N.
5454 // If the VSELECT result requires splitting and the mask is provided by a
5455 // SETCC, then split both nodes and its operands before legalization. This
5456 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5457 // and enables future optimizations (e.g. min/max pattern matching on X86).
5458 if (N0.getOpcode() == ISD::SETCC) {
5459 EVT VT = N->getValueType(0);
5461 // Check if any splitting is required.
5462 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5463 TargetLowering::TypeSplitVector)
5466 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5467 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5468 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5469 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5471 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5472 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5474 // Add the new VSELECT nodes to the work list in case they need to be split
5476 AddToWorklist(Lo.getNode());
5477 AddToWorklist(Hi.getNode());
5479 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5482 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5483 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5485 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5486 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5489 // The ConvertSelectToConcatVector function is assuming both the above
5490 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5492 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5493 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5494 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5495 SDValue CV = ConvertSelectToConcatVector(N, DAG);
5503 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5504 SDValue N0 = N->getOperand(0);
5505 SDValue N1 = N->getOperand(1);
5506 SDValue N2 = N->getOperand(2);
5507 SDValue N3 = N->getOperand(3);
5508 SDValue N4 = N->getOperand(4);
5509 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5511 // fold select_cc lhs, rhs, x, x, cc -> x
5515 // Determine if the condition we're dealing with is constant
5516 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5517 N0, N1, CC, SDLoc(N), false);
5518 if (SCC.getNode()) {
5519 AddToWorklist(SCC.getNode());
5521 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5522 if (!SCCC->isNullValue())
5523 return N2; // cond always true -> true val
5525 return N3; // cond always false -> false val
5526 } else if (SCC->getOpcode() == ISD::UNDEF) {
5527 // When the condition is UNDEF, just return the first operand. This is
5528 // coherent the DAG creation, no setcc node is created in this case
5530 } else if (SCC.getOpcode() == ISD::SETCC) {
5531 // Fold to a simpler select_cc
5532 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5533 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5538 // If we can fold this based on the true/false value, do so.
5539 if (SimplifySelectOps(N, N2, N3))
5540 return SDValue(N, 0); // Don't revisit N.
5542 // fold select_cc into other things, such as min/max/abs
5543 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5546 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5547 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5548 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5552 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5553 // dag node into a ConstantSDNode or a build_vector of constants.
5554 // This function is called by the DAGCombiner when visiting sext/zext/aext
5555 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5556 // Vector extends are not folded if operations are legal; this is to
5557 // avoid introducing illegal build_vector dag nodes.
5558 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5559 SelectionDAG &DAG, bool LegalTypes,
5560 bool LegalOperations) {
5561 unsigned Opcode = N->getOpcode();
5562 SDValue N0 = N->getOperand(0);
5563 EVT VT = N->getValueType(0);
5565 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5566 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5567 && "Expected EXTEND dag node in input!");
5569 // fold (sext c1) -> c1
5570 // fold (zext c1) -> c1
5571 // fold (aext c1) -> c1
5572 if (isa<ConstantSDNode>(N0))
5573 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5575 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5576 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5577 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5578 EVT SVT = VT.getScalarType();
5579 if (!(VT.isVector() &&
5580 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5581 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5584 // We can fold this node into a build_vector.
5585 unsigned VTBits = SVT.getSizeInBits();
5586 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5587 unsigned ShAmt = VTBits - EVTBits;
5588 SmallVector<SDValue, 8> Elts;
5589 unsigned NumElts = VT.getVectorNumElements();
5592 for (unsigned i=0; i != NumElts; ++i) {
5593 SDValue Op = N0->getOperand(i);
5594 if (Op->getOpcode() == ISD::UNDEF) {
5595 Elts.push_back(DAG.getUNDEF(SVT));
5600 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5601 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5602 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5603 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5606 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5610 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5613 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5614 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5615 // transformation. Returns true if extension are possible and the above
5616 // mentioned transformation is profitable.
5617 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5619 SmallVectorImpl<SDNode *> &ExtendNodes,
5620 const TargetLowering &TLI) {
5621 bool HasCopyToRegUses = false;
5622 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5623 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5624 UE = N0.getNode()->use_end();
5629 if (UI.getUse().getResNo() != N0.getResNo())
5631 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5632 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5633 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5634 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5635 // Sign bits will be lost after a zext.
5638 for (unsigned i = 0; i != 2; ++i) {
5639 SDValue UseOp = User->getOperand(i);
5642 if (!isa<ConstantSDNode>(UseOp))
5647 ExtendNodes.push_back(User);
5650 // If truncates aren't free and there are users we can't
5651 // extend, it isn't worthwhile.
5654 // Remember if this value is live-out.
5655 if (User->getOpcode() == ISD::CopyToReg)
5656 HasCopyToRegUses = true;
5659 if (HasCopyToRegUses) {
5660 bool BothLiveOut = false;
5661 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5663 SDUse &Use = UI.getUse();
5664 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5670 // Both unextended and extended values are live out. There had better be
5671 // a good reason for the transformation.
5672 return ExtendNodes.size();
5677 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5678 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5679 ISD::NodeType ExtType) {
5680 // Extend SetCC uses if necessary.
5681 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5682 SDNode *SetCC = SetCCs[i];
5683 SmallVector<SDValue, 4> Ops;
5685 for (unsigned j = 0; j != 2; ++j) {
5686 SDValue SOp = SetCC->getOperand(j);
5688 Ops.push_back(ExtLoad);
5690 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5693 Ops.push_back(SetCC->getOperand(2));
5694 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5698 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5699 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5700 SDValue N0 = N->getOperand(0);
5701 EVT DstVT = N->getValueType(0);
5702 EVT SrcVT = N0.getValueType();
5704 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5705 N->getOpcode() == ISD::ZERO_EXTEND) &&
5706 "Unexpected node type (not an extend)!");
5708 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5709 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5710 // (v8i32 (sext (v8i16 (load x))))
5712 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5713 // (v4i32 (sextload (x + 16)))))
5714 // Where uses of the original load, i.e.:
5716 // are replaced with:
5718 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5719 // (v4i32 (sextload (x + 16)))))))
5721 // This combine is only applicable to illegal, but splittable, vectors.
5722 // All legal types, and illegal non-vector types, are handled elsewhere.
5723 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5725 if (N0->getOpcode() != ISD::LOAD)
5728 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5730 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5731 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5732 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5735 SmallVector<SDNode *, 4> SetCCs;
5736 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5739 ISD::LoadExtType ExtType =
5740 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5742 // Try to split the vector types to get down to legal types.
5743 EVT SplitSrcVT = SrcVT;
5744 EVT SplitDstVT = DstVT;
5745 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5746 SplitSrcVT.getVectorNumElements() > 1) {
5747 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5748 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5751 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5755 const unsigned NumSplits =
5756 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5757 const unsigned Stride = SplitSrcVT.getStoreSize();
5758 SmallVector<SDValue, 4> Loads;
5759 SmallVector<SDValue, 4> Chains;
5761 SDValue BasePtr = LN0->getBasePtr();
5762 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5763 const unsigned Offset = Idx * Stride;
5764 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5766 SDValue SplitLoad = DAG.getExtLoad(
5767 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5768 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5769 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5770 Align, LN0->getAAInfo());
5772 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5773 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5775 Loads.push_back(SplitLoad.getValue(0));
5776 Chains.push_back(SplitLoad.getValue(1));
5779 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5780 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5782 CombineTo(N, NewValue);
5784 // Replace uses of the original load (before extension)
5785 // with a truncate of the concatenated sextloaded vectors.
5787 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5788 CombineTo(N0.getNode(), Trunc, NewChain);
5789 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5790 (ISD::NodeType)N->getOpcode());
5791 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5794 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5795 SDValue N0 = N->getOperand(0);
5796 EVT VT = N->getValueType(0);
5798 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5800 return SDValue(Res, 0);
5802 // fold (sext (sext x)) -> (sext x)
5803 // fold (sext (aext x)) -> (sext x)
5804 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5805 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5808 if (N0.getOpcode() == ISD::TRUNCATE) {
5809 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5810 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5811 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5812 if (NarrowLoad.getNode()) {
5813 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5814 if (NarrowLoad.getNode() != N0.getNode()) {
5815 CombineTo(N0.getNode(), NarrowLoad);
5816 // CombineTo deleted the truncate, if needed, but not what's under it.
5819 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5822 // See if the value being truncated is already sign extended. If so, just
5823 // eliminate the trunc/sext pair.
5824 SDValue Op = N0.getOperand(0);
5825 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5826 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5827 unsigned DestBits = VT.getScalarType().getSizeInBits();
5828 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5830 if (OpBits == DestBits) {
5831 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5832 // bits, it is already ready.
5833 if (NumSignBits > DestBits-MidBits)
5835 } else if (OpBits < DestBits) {
5836 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5837 // bits, just sext from i32.
5838 if (NumSignBits > OpBits-MidBits)
5839 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5841 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5842 // bits, just truncate to i32.
5843 if (NumSignBits > OpBits-MidBits)
5844 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5847 // fold (sext (truncate x)) -> (sextinreg x).
5848 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5849 N0.getValueType())) {
5850 if (OpBits < DestBits)
5851 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5852 else if (OpBits > DestBits)
5853 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5854 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5855 DAG.getValueType(N0.getValueType()));
5859 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5860 // Only generate vector extloads when 1) they're legal, and 2) they are
5861 // deemed desirable by the target.
5862 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5863 ((!LegalOperations && !VT.isVector() &&
5864 !cast<LoadSDNode>(N0)->isVolatile()) ||
5865 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5866 bool DoXform = true;
5867 SmallVector<SDNode*, 4> SetCCs;
5868 if (!N0.hasOneUse())
5869 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5871 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5873 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5874 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5876 LN0->getBasePtr(), N0.getValueType(),
5877 LN0->getMemOperand());
5878 CombineTo(N, ExtLoad);
5879 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5880 N0.getValueType(), ExtLoad);
5881 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5882 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5884 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5888 // fold (sext (load x)) to multiple smaller sextloads.
5889 // Only on illegal but splittable vectors.
5890 if (SDValue ExtLoad = CombineExtLoad(N))
5893 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5894 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5895 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5896 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5897 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5898 EVT MemVT = LN0->getMemoryVT();
5899 if ((!LegalOperations && !LN0->isVolatile()) ||
5900 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5901 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5903 LN0->getBasePtr(), MemVT,
5904 LN0->getMemOperand());
5905 CombineTo(N, ExtLoad);
5906 CombineTo(N0.getNode(),
5907 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5908 N0.getValueType(), ExtLoad),
5909 ExtLoad.getValue(1));
5910 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5914 // fold (sext (and/or/xor (load x), cst)) ->
5915 // (and/or/xor (sextload x), (sext cst))
5916 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5917 N0.getOpcode() == ISD::XOR) &&
5918 isa<LoadSDNode>(N0.getOperand(0)) &&
5919 N0.getOperand(1).getOpcode() == ISD::Constant &&
5920 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5921 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5922 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5923 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5924 bool DoXform = true;
5925 SmallVector<SDNode*, 4> SetCCs;
5926 if (!N0.hasOneUse())
5927 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5930 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5931 LN0->getChain(), LN0->getBasePtr(),
5933 LN0->getMemOperand());
5934 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5935 Mask = Mask.sext(VT.getSizeInBits());
5937 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5938 ExtLoad, DAG.getConstant(Mask, DL, VT));
5939 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5940 SDLoc(N0.getOperand(0)),
5941 N0.getOperand(0).getValueType(), ExtLoad);
5943 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5944 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5946 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5951 if (N0.getOpcode() == ISD::SETCC) {
5952 EVT N0VT = N0.getOperand(0).getValueType();
5953 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5954 // Only do this before legalize for now.
5955 if (VT.isVector() && !LegalOperations &&
5956 TLI.getBooleanContents(N0VT) ==
5957 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5958 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5959 // of the same size as the compared operands. Only optimize sext(setcc())
5960 // if this is the case.
5961 EVT SVT = getSetCCResultType(N0VT);
5963 // We know that the # elements of the results is the same as the
5964 // # elements of the compare (and the # elements of the compare result
5965 // for that matter). Check to see that they are the same size. If so,
5966 // we know that the element size of the sext'd result matches the
5967 // element size of the compare operands.
5968 if (VT.getSizeInBits() == SVT.getSizeInBits())
5969 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5971 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5973 // If the desired elements are smaller or larger than the source
5974 // elements we can use a matching integer vector type and then
5975 // truncate/sign extend
5976 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5977 if (SVT == MatchingVectorType) {
5978 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5979 N0.getOperand(0), N0.getOperand(1),
5980 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5981 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5985 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5986 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5989 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
5991 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
5992 NegOne, DAG.getConstant(0, DL, VT),
5993 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5994 if (SCC.getNode()) return SCC;
5996 if (!VT.isVector()) {
5997 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5998 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
6000 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6001 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6002 N0.getOperand(0), N0.getOperand(1), CC);
6003 return DAG.getSelect(DL, VT, SetCC,
6004 NegOne, DAG.getConstant(0, DL, VT));
6009 // fold (sext x) -> (zext x) if the sign bit is known zero.
6010 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6011 DAG.SignBitIsZero(N0))
6012 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6017 // isTruncateOf - If N is a truncate of some other value, return true, record
6018 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6019 // This function computes KnownZero to avoid a duplicated call to
6020 // computeKnownBits in the caller.
6021 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6024 if (N->getOpcode() == ISD::TRUNCATE) {
6025 Op = N->getOperand(0);
6026 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6030 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6031 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6034 SDValue Op0 = N->getOperand(0);
6035 SDValue Op1 = N->getOperand(1);
6036 assert(Op0.getValueType() == Op1.getValueType());
6038 if (isNullConstant(Op0))
6040 else if (isNullConstant(Op1))
6045 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6047 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6053 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6054 SDValue N0 = N->getOperand(0);
6055 EVT VT = N->getValueType(0);
6057 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6059 return SDValue(Res, 0);
6061 // fold (zext (zext x)) -> (zext x)
6062 // fold (zext (aext x)) -> (zext x)
6063 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6064 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6067 // fold (zext (truncate x)) -> (zext x) or
6068 // (zext (truncate x)) -> (truncate x)
6069 // This is valid when the truncated bits of x are already zero.
6070 // FIXME: We should extend this to work for vectors too.
6073 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6074 APInt TruncatedBits =
6075 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6076 APInt(Op.getValueSizeInBits(), 0) :
6077 APInt::getBitsSet(Op.getValueSizeInBits(),
6078 N0.getValueSizeInBits(),
6079 std::min(Op.getValueSizeInBits(),
6080 VT.getSizeInBits()));
6081 if (TruncatedBits == (KnownZero & TruncatedBits)) {
6082 if (VT.bitsGT(Op.getValueType()))
6083 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6084 if (VT.bitsLT(Op.getValueType()))
6085 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6091 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6092 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6093 if (N0.getOpcode() == ISD::TRUNCATE) {
6094 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6095 if (NarrowLoad.getNode()) {
6096 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6097 if (NarrowLoad.getNode() != N0.getNode()) {
6098 CombineTo(N0.getNode(), NarrowLoad);
6099 // CombineTo deleted the truncate, if needed, but not what's under it.
6102 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6106 // fold (zext (truncate x)) -> (and x, mask)
6107 if (N0.getOpcode() == ISD::TRUNCATE &&
6108 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
6110 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6111 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6112 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6113 if (NarrowLoad.getNode()) {
6114 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6115 if (NarrowLoad.getNode() != N0.getNode()) {
6116 CombineTo(N0.getNode(), NarrowLoad);
6117 // CombineTo deleted the truncate, if needed, but not what's under it.
6120 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6123 SDValue Op = N0.getOperand(0);
6124 if (Op.getValueType().bitsLT(VT)) {
6125 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6126 AddToWorklist(Op.getNode());
6127 } else if (Op.getValueType().bitsGT(VT)) {
6128 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6129 AddToWorklist(Op.getNode());
6131 return DAG.getZeroExtendInReg(Op, SDLoc(N),
6132 N0.getValueType().getScalarType());
6135 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6136 // if either of the casts is not free.
6137 if (N0.getOpcode() == ISD::AND &&
6138 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6139 N0.getOperand(1).getOpcode() == ISD::Constant &&
6140 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6141 N0.getValueType()) ||
6142 !TLI.isZExtFree(N0.getValueType(), VT))) {
6143 SDValue X = N0.getOperand(0).getOperand(0);
6144 if (X.getValueType().bitsLT(VT)) {
6145 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6146 } else if (X.getValueType().bitsGT(VT)) {
6147 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6149 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6150 Mask = Mask.zext(VT.getSizeInBits());
6152 return DAG.getNode(ISD::AND, DL, VT,
6153 X, DAG.getConstant(Mask, DL, VT));
6156 // fold (zext (load x)) -> (zext (truncate (zextload x)))
6157 // Only generate vector extloads when 1) they're legal, and 2) they are
6158 // deemed desirable by the target.
6159 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6160 ((!LegalOperations && !VT.isVector() &&
6161 !cast<LoadSDNode>(N0)->isVolatile()) ||
6162 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6163 bool DoXform = true;
6164 SmallVector<SDNode*, 4> SetCCs;
6165 if (!N0.hasOneUse())
6166 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6168 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6170 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6171 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6173 LN0->getBasePtr(), N0.getValueType(),
6174 LN0->getMemOperand());
6175 CombineTo(N, ExtLoad);
6176 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6177 N0.getValueType(), ExtLoad);
6178 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6180 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6182 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6186 // fold (zext (load x)) to multiple smaller zextloads.
6187 // Only on illegal but splittable vectors.
6188 if (SDValue ExtLoad = CombineExtLoad(N))
6191 // fold (zext (and/or/xor (load x), cst)) ->
6192 // (and/or/xor (zextload x), (zext cst))
6193 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6194 N0.getOpcode() == ISD::XOR) &&
6195 isa<LoadSDNode>(N0.getOperand(0)) &&
6196 N0.getOperand(1).getOpcode() == ISD::Constant &&
6197 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6198 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6199 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6200 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6201 bool DoXform = true;
6202 SmallVector<SDNode*, 4> SetCCs;
6203 if (!N0.hasOneUse())
6204 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6207 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6208 LN0->getChain(), LN0->getBasePtr(),
6210 LN0->getMemOperand());
6211 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6212 Mask = Mask.zext(VT.getSizeInBits());
6214 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6215 ExtLoad, DAG.getConstant(Mask, DL, VT));
6216 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6217 SDLoc(N0.getOperand(0)),
6218 N0.getOperand(0).getValueType(), ExtLoad);
6220 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6221 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6223 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6228 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6229 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6230 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6231 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6232 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6233 EVT MemVT = LN0->getMemoryVT();
6234 if ((!LegalOperations && !LN0->isVolatile()) ||
6235 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6236 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6238 LN0->getBasePtr(), MemVT,
6239 LN0->getMemOperand());
6240 CombineTo(N, ExtLoad);
6241 CombineTo(N0.getNode(),
6242 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6244 ExtLoad.getValue(1));
6245 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6249 if (N0.getOpcode() == ISD::SETCC) {
6250 if (!LegalOperations && VT.isVector() &&
6251 N0.getValueType().getVectorElementType() == MVT::i1) {
6252 EVT N0VT = N0.getOperand(0).getValueType();
6253 if (getSetCCResultType(N0VT) == N0.getValueType())
6256 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6257 // Only do this before legalize for now.
6258 EVT EltVT = VT.getVectorElementType();
6260 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6261 DAG.getConstant(1, DL, EltVT));
6262 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6263 // We know that the # elements of the results is the same as the
6264 // # elements of the compare (and the # elements of the compare result
6265 // for that matter). Check to see that they are the same size. If so,
6266 // we know that the element size of the sext'd result matches the
6267 // element size of the compare operands.
6268 return DAG.getNode(ISD::AND, DL, VT,
6269 DAG.getSetCC(DL, VT, N0.getOperand(0),
6271 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6272 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6275 // If the desired elements are smaller or larger than the source
6276 // elements we can use a matching integer vector type and then
6277 // truncate/sign extend
6278 EVT MatchingElementType =
6279 EVT::getIntegerVT(*DAG.getContext(),
6280 N0VT.getScalarType().getSizeInBits());
6281 EVT MatchingVectorType =
6282 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6283 N0VT.getVectorNumElements());
6285 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6287 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6288 return DAG.getNode(ISD::AND, DL, VT,
6289 DAG.getSExtOrTrunc(VsetCC, DL, VT),
6290 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6293 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6296 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6297 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6298 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6299 if (SCC.getNode()) return SCC;
6302 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6303 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6304 isa<ConstantSDNode>(N0.getOperand(1)) &&
6305 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6307 SDValue ShAmt = N0.getOperand(1);
6308 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6309 if (N0.getOpcode() == ISD::SHL) {
6310 SDValue InnerZExt = N0.getOperand(0);
6311 // If the original shl may be shifting out bits, do not perform this
6313 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6314 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6315 if (ShAmtVal > KnownZeroBits)
6321 // Ensure that the shift amount is wide enough for the shifted value.
6322 if (VT.getSizeInBits() >= 256)
6323 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6325 return DAG.getNode(N0.getOpcode(), DL, VT,
6326 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6333 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6334 SDValue N0 = N->getOperand(0);
6335 EVT VT = N->getValueType(0);
6337 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6339 return SDValue(Res, 0);
6341 // fold (aext (aext x)) -> (aext x)
6342 // fold (aext (zext x)) -> (zext x)
6343 // fold (aext (sext x)) -> (sext x)
6344 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6345 N0.getOpcode() == ISD::ZERO_EXTEND ||
6346 N0.getOpcode() == ISD::SIGN_EXTEND)
6347 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6349 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6350 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6351 if (N0.getOpcode() == ISD::TRUNCATE) {
6352 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6353 if (NarrowLoad.getNode()) {
6354 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6355 if (NarrowLoad.getNode() != N0.getNode()) {
6356 CombineTo(N0.getNode(), NarrowLoad);
6357 // CombineTo deleted the truncate, if needed, but not what's under it.
6360 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6364 // fold (aext (truncate x))
6365 if (N0.getOpcode() == ISD::TRUNCATE) {
6366 SDValue TruncOp = N0.getOperand(0);
6367 if (TruncOp.getValueType() == VT)
6368 return TruncOp; // x iff x size == zext size.
6369 if (TruncOp.getValueType().bitsGT(VT))
6370 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6371 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6374 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6375 // if the trunc is not free.
6376 if (N0.getOpcode() == ISD::AND &&
6377 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6378 N0.getOperand(1).getOpcode() == ISD::Constant &&
6379 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6380 N0.getValueType())) {
6381 SDValue X = N0.getOperand(0).getOperand(0);
6382 if (X.getValueType().bitsLT(VT)) {
6383 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6384 } else if (X.getValueType().bitsGT(VT)) {
6385 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6387 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6388 Mask = Mask.zext(VT.getSizeInBits());
6390 return DAG.getNode(ISD::AND, DL, VT,
6391 X, DAG.getConstant(Mask, DL, VT));
6394 // fold (aext (load x)) -> (aext (truncate (extload x)))
6395 // None of the supported targets knows how to perform load and any_ext
6396 // on vectors in one instruction. We only perform this transformation on
6398 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6399 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6400 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6401 bool DoXform = true;
6402 SmallVector<SDNode*, 4> SetCCs;
6403 if (!N0.hasOneUse())
6404 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6406 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6407 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6409 LN0->getBasePtr(), N0.getValueType(),
6410 LN0->getMemOperand());
6411 CombineTo(N, ExtLoad);
6412 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6413 N0.getValueType(), ExtLoad);
6414 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6415 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6417 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6421 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6422 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6423 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6424 if (N0.getOpcode() == ISD::LOAD &&
6425 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6427 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6428 ISD::LoadExtType ExtType = LN0->getExtensionType();
6429 EVT MemVT = LN0->getMemoryVT();
6430 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6431 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6432 VT, LN0->getChain(), LN0->getBasePtr(),
6433 MemVT, LN0->getMemOperand());
6434 CombineTo(N, ExtLoad);
6435 CombineTo(N0.getNode(),
6436 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6437 N0.getValueType(), ExtLoad),
6438 ExtLoad.getValue(1));
6439 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6443 if (N0.getOpcode() == ISD::SETCC) {
6445 // aext(setcc) -> vsetcc
6446 // aext(setcc) -> truncate(vsetcc)
6447 // aext(setcc) -> aext(vsetcc)
6448 // Only do this before legalize for now.
6449 if (VT.isVector() && !LegalOperations) {
6450 EVT N0VT = N0.getOperand(0).getValueType();
6451 // We know that the # elements of the results is the same as the
6452 // # elements of the compare (and the # elements of the compare result
6453 // for that matter). Check to see that they are the same size. If so,
6454 // we know that the element size of the sext'd result matches the
6455 // element size of the compare operands.
6456 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6457 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6459 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6460 // If the desired elements are smaller or larger than the source
6461 // elements we can use a matching integer vector type and then
6462 // truncate/any extend
6464 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6466 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6468 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6469 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6473 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6476 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6477 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6478 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6486 /// See if the specified operand can be simplified with the knowledge that only
6487 /// the bits specified by Mask are used. If so, return the simpler operand,
6488 /// otherwise return a null SDValue.
6489 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6490 switch (V.getOpcode()) {
6492 case ISD::Constant: {
6493 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6494 assert(CV && "Const value should be ConstSDNode.");
6495 const APInt &CVal = CV->getAPIntValue();
6496 APInt NewVal = CVal & Mask;
6498 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6503 // If the LHS or RHS don't contribute bits to the or, drop them.
6504 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6505 return V.getOperand(1);
6506 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6507 return V.getOperand(0);
6510 // Only look at single-use SRLs.
6511 if (!V.getNode()->hasOneUse())
6513 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6514 // See if we can recursively simplify the LHS.
6515 unsigned Amt = RHSC->getZExtValue();
6517 // Watch out for shift count overflow though.
6518 if (Amt >= Mask.getBitWidth()) break;
6519 APInt NewMask = Mask << Amt;
6520 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6521 if (SimplifyLHS.getNode())
6522 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6523 SimplifyLHS, V.getOperand(1));
6529 /// If the result of a wider load is shifted to right of N bits and then
6530 /// truncated to a narrower type and where N is a multiple of number of bits of
6531 /// the narrower type, transform it to a narrower load from address + N / num of
6532 /// bits of new type. If the result is to be extended, also fold the extension
6533 /// to form a extending load.
6534 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6535 unsigned Opc = N->getOpcode();
6537 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6538 SDValue N0 = N->getOperand(0);
6539 EVT VT = N->getValueType(0);
6542 // This transformation isn't valid for vector loads.
6546 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6548 if (Opc == ISD::SIGN_EXTEND_INREG) {
6549 ExtType = ISD::SEXTLOAD;
6550 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6551 } else if (Opc == ISD::SRL) {
6552 // Another special-case: SRL is basically zero-extending a narrower value.
6553 ExtType = ISD::ZEXTLOAD;
6555 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6556 if (!N01) return SDValue();
6557 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6558 VT.getSizeInBits() - N01->getZExtValue());
6560 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6563 unsigned EVTBits = ExtVT.getSizeInBits();
6565 // Do not generate loads of non-round integer types since these can
6566 // be expensive (and would be wrong if the type is not byte sized).
6567 if (!ExtVT.isRound())
6571 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6572 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6573 ShAmt = N01->getZExtValue();
6574 // Is the shift amount a multiple of size of VT?
6575 if ((ShAmt & (EVTBits-1)) == 0) {
6576 N0 = N0.getOperand(0);
6577 // Is the load width a multiple of size of VT?
6578 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6582 // At this point, we must have a load or else we can't do the transform.
6583 if (!isa<LoadSDNode>(N0)) return SDValue();
6585 // Because a SRL must be assumed to *need* to zero-extend the high bits
6586 // (as opposed to anyext the high bits), we can't combine the zextload
6587 // lowering of SRL and an sextload.
6588 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6591 // If the shift amount is larger than the input type then we're not
6592 // accessing any of the loaded bytes. If the load was a zextload/extload
6593 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6594 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6599 // If the load is shifted left (and the result isn't shifted back right),
6600 // we can fold the truncate through the shift.
6601 unsigned ShLeftAmt = 0;
6602 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6603 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6604 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6605 ShLeftAmt = N01->getZExtValue();
6606 N0 = N0.getOperand(0);
6610 // If we haven't found a load, we can't narrow it. Don't transform one with
6611 // multiple uses, this would require adding a new load.
6612 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6615 // Don't change the width of a volatile load.
6616 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6617 if (LN0->isVolatile())
6620 // Verify that we are actually reducing a load width here.
6621 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6624 // For the transform to be legal, the load must produce only two values
6625 // (the value loaded and the chain). Don't transform a pre-increment
6626 // load, for example, which produces an extra value. Otherwise the
6627 // transformation is not equivalent, and the downstream logic to replace
6628 // uses gets things wrong.
6629 if (LN0->getNumValues() > 2)
6632 // If the load that we're shrinking is an extload and we're not just
6633 // discarding the extension we can't simply shrink the load. Bail.
6634 // TODO: It would be possible to merge the extensions in some cases.
6635 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6636 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6639 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6642 EVT PtrType = N0.getOperand(1).getValueType();
6644 if (PtrType == MVT::Untyped || PtrType.isExtended())
6645 // It's not possible to generate a constant of extended or untyped type.
6648 // For big endian targets, we need to adjust the offset to the pointer to
6649 // load the correct bytes.
6650 if (TLI.isBigEndian()) {
6651 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6652 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6653 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6656 uint64_t PtrOff = ShAmt / 8;
6657 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6659 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6660 PtrType, LN0->getBasePtr(),
6661 DAG.getConstant(PtrOff, DL, PtrType));
6662 AddToWorklist(NewPtr.getNode());
6665 if (ExtType == ISD::NON_EXTLOAD)
6666 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6667 LN0->getPointerInfo().getWithOffset(PtrOff),
6668 LN0->isVolatile(), LN0->isNonTemporal(),
6669 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6671 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6672 LN0->getPointerInfo().getWithOffset(PtrOff),
6673 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6674 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6676 // Replace the old load's chain with the new load's chain.
6677 WorklistRemover DeadNodes(*this);
6678 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6680 // Shift the result left, if we've swallowed a left shift.
6681 SDValue Result = Load;
6682 if (ShLeftAmt != 0) {
6683 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6684 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6686 // If the shift amount is as large as the result size (but, presumably,
6687 // no larger than the source) then the useful bits of the result are
6688 // zero; we can't simply return the shortened shift, because the result
6689 // of that operation is undefined.
6691 if (ShLeftAmt >= VT.getSizeInBits())
6692 Result = DAG.getConstant(0, DL, VT);
6694 Result = DAG.getNode(ISD::SHL, DL, VT,
6695 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6698 // Return the new loaded value.
6702 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6703 SDValue N0 = N->getOperand(0);
6704 SDValue N1 = N->getOperand(1);
6705 EVT VT = N->getValueType(0);
6706 EVT EVT = cast<VTSDNode>(N1)->getVT();
6707 unsigned VTBits = VT.getScalarType().getSizeInBits();
6708 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6710 // fold (sext_in_reg c1) -> c1
6711 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6712 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6714 // If the input is already sign extended, just drop the extension.
6715 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6718 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6719 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6720 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6721 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6722 N0.getOperand(0), N1);
6724 // fold (sext_in_reg (sext x)) -> (sext x)
6725 // fold (sext_in_reg (aext x)) -> (sext x)
6726 // if x is small enough.
6727 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6728 SDValue N00 = N0.getOperand(0);
6729 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6730 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6731 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6734 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6735 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6736 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6738 // fold operands of sext_in_reg based on knowledge that the top bits are not
6740 if (SimplifyDemandedBits(SDValue(N, 0)))
6741 return SDValue(N, 0);
6743 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6744 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6745 SDValue NarrowLoad = ReduceLoadWidth(N);
6746 if (NarrowLoad.getNode())
6749 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6750 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6751 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6752 if (N0.getOpcode() == ISD::SRL) {
6753 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6754 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6755 // We can turn this into an SRA iff the input to the SRL is already sign
6757 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6758 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6759 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6760 N0.getOperand(0), N0.getOperand(1));
6764 // fold (sext_inreg (extload x)) -> (sextload x)
6765 if (ISD::isEXTLoad(N0.getNode()) &&
6766 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6767 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6768 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6769 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6770 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6771 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6773 LN0->getBasePtr(), EVT,
6774 LN0->getMemOperand());
6775 CombineTo(N, ExtLoad);
6776 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6777 AddToWorklist(ExtLoad.getNode());
6778 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6780 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6781 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6783 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6784 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6785 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6786 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6787 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6789 LN0->getBasePtr(), EVT,
6790 LN0->getMemOperand());
6791 CombineTo(N, ExtLoad);
6792 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6793 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6796 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6797 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6798 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6799 N0.getOperand(1), false);
6800 if (BSwap.getNode())
6801 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6805 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6806 // into a build_vector.
6807 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6808 SmallVector<SDValue, 8> Elts;
6809 unsigned NumElts = N0->getNumOperands();
6810 unsigned ShAmt = VTBits - EVTBits;
6812 for (unsigned i = 0; i != NumElts; ++i) {
6813 SDValue Op = N0->getOperand(i);
6814 if (Op->getOpcode() == ISD::UNDEF) {
6819 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6820 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6821 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6822 SDLoc(Op), Op.getValueType()));
6825 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6831 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6832 SDValue N0 = N->getOperand(0);
6833 EVT VT = N->getValueType(0);
6835 if (N0.getOpcode() == ISD::UNDEF)
6836 return DAG.getUNDEF(VT);
6838 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6840 return SDValue(Res, 0);
6845 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6846 SDValue N0 = N->getOperand(0);
6847 EVT VT = N->getValueType(0);
6848 bool isLE = TLI.isLittleEndian();
6851 if (N0.getValueType() == N->getValueType(0))
6853 // fold (truncate c1) -> c1
6854 if (isConstantIntBuildVectorOrConstantInt(N0))
6855 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6856 // fold (truncate (truncate x)) -> (truncate x)
6857 if (N0.getOpcode() == ISD::TRUNCATE)
6858 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6859 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6860 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6861 N0.getOpcode() == ISD::SIGN_EXTEND ||
6862 N0.getOpcode() == ISD::ANY_EXTEND) {
6863 if (N0.getOperand(0).getValueType().bitsLT(VT))
6864 // if the source is smaller than the dest, we still need an extend
6865 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6867 if (N0.getOperand(0).getValueType().bitsGT(VT))
6868 // if the source is larger than the dest, than we just need the truncate
6869 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6870 // if the source and dest are the same type, we can drop both the extend
6871 // and the truncate.
6872 return N0.getOperand(0);
6875 // Fold extract-and-trunc into a narrow extract. For example:
6876 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6877 // i32 y = TRUNCATE(i64 x)
6879 // v16i8 b = BITCAST (v2i64 val)
6880 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6882 // Note: We only run this optimization after type legalization (which often
6883 // creates this pattern) and before operation legalization after which
6884 // we need to be more careful about the vector instructions that we generate.
6885 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6886 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6888 EVT VecTy = N0.getOperand(0).getValueType();
6889 EVT ExTy = N0.getValueType();
6890 EVT TrTy = N->getValueType(0);
6892 unsigned NumElem = VecTy.getVectorNumElements();
6893 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6895 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6896 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6898 SDValue EltNo = N0->getOperand(1);
6899 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6900 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6901 EVT IndexTy = TLI.getVectorIdxTy();
6902 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6904 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6905 NVT, N0.getOperand(0));
6908 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6910 DAG.getConstant(Index, DL, IndexTy));
6914 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6915 if (N0.getOpcode() == ISD::SELECT) {
6916 EVT SrcVT = N0.getValueType();
6917 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6918 TLI.isTruncateFree(SrcVT, VT)) {
6920 SDValue Cond = N0.getOperand(0);
6921 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6922 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6923 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6927 // Fold a series of buildvector, bitcast, and truncate if possible.
6929 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6930 // (2xi32 (buildvector x, y)).
6931 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6932 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6933 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6934 N0.getOperand(0).hasOneUse()) {
6936 SDValue BuildVect = N0.getOperand(0);
6937 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6938 EVT TruncVecEltTy = VT.getVectorElementType();
6940 // Check that the element types match.
6941 if (BuildVectEltTy == TruncVecEltTy) {
6942 // Now we only need to compute the offset of the truncated elements.
6943 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6944 unsigned TruncVecNumElts = VT.getVectorNumElements();
6945 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6947 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6948 "Invalid number of elements");
6950 SmallVector<SDValue, 8> Opnds;
6951 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6952 Opnds.push_back(BuildVect.getOperand(i));
6954 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6958 // See if we can simplify the input to this truncate through knowledge that
6959 // only the low bits are being used.
6960 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6961 // Currently we only perform this optimization on scalars because vectors
6962 // may have different active low bits.
6963 if (!VT.isVector()) {
6965 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6966 VT.getSizeInBits()));
6967 if (Shorter.getNode())
6968 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6970 // fold (truncate (load x)) -> (smaller load x)
6971 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6972 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6973 SDValue Reduced = ReduceLoadWidth(N);
6974 if (Reduced.getNode())
6976 // Handle the case where the load remains an extending load even
6977 // after truncation.
6978 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6979 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6980 if (!LN0->isVolatile() &&
6981 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6982 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6983 VT, LN0->getChain(), LN0->getBasePtr(),
6985 LN0->getMemOperand());
6986 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6991 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6992 // where ... are all 'undef'.
6993 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6994 SmallVector<EVT, 8> VTs;
6997 unsigned NumDefs = 0;
6999 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7000 SDValue X = N0.getOperand(i);
7001 if (X.getOpcode() != ISD::UNDEF) {
7006 // Stop if more than one members are non-undef.
7009 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7010 VT.getVectorElementType(),
7011 X.getValueType().getVectorNumElements()));
7015 return DAG.getUNDEF(VT);
7018 assert(V.getNode() && "The single defined operand is empty!");
7019 SmallVector<SDValue, 8> Opnds;
7020 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7022 Opnds.push_back(DAG.getUNDEF(VTs[i]));
7025 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7026 AddToWorklist(NV.getNode());
7027 Opnds.push_back(NV);
7029 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7033 // Simplify the operands using demanded-bits information.
7034 if (!VT.isVector() &&
7035 SimplifyDemandedBits(SDValue(N, 0)))
7036 return SDValue(N, 0);
7041 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7042 SDValue Elt = N->getOperand(i);
7043 if (Elt.getOpcode() != ISD::MERGE_VALUES)
7044 return Elt.getNode();
7045 return Elt.getOperand(Elt.getResNo()).getNode();
7048 /// build_pair (load, load) -> load
7049 /// if load locations are consecutive.
7050 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7051 assert(N->getOpcode() == ISD::BUILD_PAIR);
7053 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7054 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7055 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7056 LD1->getAddressSpace() != LD2->getAddressSpace())
7058 EVT LD1VT = LD1->getValueType(0);
7060 if (ISD::isNON_EXTLoad(LD2) &&
7062 // If both are volatile this would reduce the number of volatile loads.
7063 // If one is volatile it might be ok, but play conservative and bail out.
7064 !LD1->isVolatile() &&
7065 !LD2->isVolatile() &&
7066 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7067 unsigned Align = LD1->getAlignment();
7068 unsigned NewAlign = TLI.getDataLayout()->
7069 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7071 if (NewAlign <= Align &&
7072 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7073 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7074 LD1->getBasePtr(), LD1->getPointerInfo(),
7075 false, false, false, Align);
7081 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7082 SDValue N0 = N->getOperand(0);
7083 EVT VT = N->getValueType(0);
7085 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7086 // Only do this before legalize, since afterward the target may be depending
7087 // on the bitconvert.
7088 // First check to see if this is all constant.
7090 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7092 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7094 EVT DestEltVT = N->getValueType(0).getVectorElementType();
7095 assert(!DestEltVT.isVector() &&
7096 "Element type of vector ValueType must not be vector!");
7098 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7101 // If the input is a constant, let getNode fold it.
7102 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7103 // If we can't allow illegal operations, we need to check that this is just
7104 // a fp -> int or int -> conversion and that the resulting operation will
7106 if (!LegalOperations ||
7107 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7108 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7109 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7110 TLI.isOperationLegal(ISD::Constant, VT)))
7111 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7114 // (conv (conv x, t1), t2) -> (conv x, t2)
7115 if (N0.getOpcode() == ISD::BITCAST)
7116 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7119 // fold (conv (load x)) -> (load (conv*)x)
7120 // If the resultant load doesn't need a higher alignment than the original!
7121 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7122 // Do not change the width of a volatile load.
7123 !cast<LoadSDNode>(N0)->isVolatile() &&
7124 // Do not remove the cast if the types differ in endian layout.
7125 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
7126 TLI.hasBigEndianPartOrdering(VT) &&
7127 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7128 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7129 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7130 unsigned Align = TLI.getDataLayout()->
7131 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7132 unsigned OrigAlign = LN0->getAlignment();
7134 if (Align <= OrigAlign) {
7135 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7136 LN0->getBasePtr(), LN0->getPointerInfo(),
7137 LN0->isVolatile(), LN0->isNonTemporal(),
7138 LN0->isInvariant(), OrigAlign,
7140 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7145 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7146 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7147 // This often reduces constant pool loads.
7148 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7149 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7150 N0.getNode()->hasOneUse() && VT.isInteger() &&
7151 !VT.isVector() && !N0.getValueType().isVector()) {
7152 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7154 AddToWorklist(NewConv.getNode());
7157 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7158 if (N0.getOpcode() == ISD::FNEG)
7159 return DAG.getNode(ISD::XOR, DL, VT,
7160 NewConv, DAG.getConstant(SignBit, DL, VT));
7161 assert(N0.getOpcode() == ISD::FABS);
7162 return DAG.getNode(ISD::AND, DL, VT,
7163 NewConv, DAG.getConstant(~SignBit, DL, VT));
7166 // fold (bitconvert (fcopysign cst, x)) ->
7167 // (or (and (bitconvert x), sign), (and cst, (not sign)))
7168 // Note that we don't handle (copysign x, cst) because this can always be
7169 // folded to an fneg or fabs.
7170 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7171 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7172 VT.isInteger() && !VT.isVector()) {
7173 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7174 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7175 if (isTypeLegal(IntXVT)) {
7176 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7177 IntXVT, N0.getOperand(1));
7178 AddToWorklist(X.getNode());
7180 // If X has a different width than the result/lhs, sext it or truncate it.
7181 unsigned VTWidth = VT.getSizeInBits();
7182 if (OrigXWidth < VTWidth) {
7183 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7184 AddToWorklist(X.getNode());
7185 } else if (OrigXWidth > VTWidth) {
7186 // To get the sign bit in the right place, we have to shift it right
7187 // before truncating.
7189 X = DAG.getNode(ISD::SRL, DL,
7190 X.getValueType(), X,
7191 DAG.getConstant(OrigXWidth-VTWidth, DL,
7193 AddToWorklist(X.getNode());
7194 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7195 AddToWorklist(X.getNode());
7198 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7199 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7200 X, DAG.getConstant(SignBit, SDLoc(X), VT));
7201 AddToWorklist(X.getNode());
7203 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7204 VT, N0.getOperand(0));
7205 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7206 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7207 AddToWorklist(Cst.getNode());
7209 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7213 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7214 if (N0.getOpcode() == ISD::BUILD_PAIR) {
7215 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
7216 if (CombineLD.getNode())
7220 // Remove double bitcasts from shuffles - this is often a legacy of
7221 // XformToShuffleWithZero being used to combine bitmaskings (of
7222 // float vectors bitcast to integer vectors) into shuffles.
7223 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7224 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7225 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7226 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7227 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7228 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7230 // If operands are a bitcast, peek through if it casts the original VT.
7231 // If operands are a UNDEF or constant, just bitcast back to original VT.
7232 auto PeekThroughBitcast = [&](SDValue Op) {
7233 if (Op.getOpcode() == ISD::BITCAST &&
7234 Op.getOperand(0)->getValueType(0) == VT)
7235 return SDValue(Op.getOperand(0));
7236 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7237 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7238 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7242 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7243 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7248 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7249 SmallVector<int, 8> NewMask;
7250 for (int M : SVN->getMask())
7251 for (int i = 0; i != MaskScale; ++i)
7252 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7254 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7256 std::swap(SV0, SV1);
7257 ShuffleVectorSDNode::commuteMask(NewMask);
7258 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7262 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7268 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7269 EVT VT = N->getValueType(0);
7270 return CombineConsecutiveLoads(N, VT);
7273 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7274 /// operands. DstEltVT indicates the destination element value type.
7275 SDValue DAGCombiner::
7276 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7277 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7279 // If this is already the right type, we're done.
7280 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7282 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7283 unsigned DstBitSize = DstEltVT.getSizeInBits();
7285 // If this is a conversion of N elements of one type to N elements of another
7286 // type, convert each element. This handles FP<->INT cases.
7287 if (SrcBitSize == DstBitSize) {
7288 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7289 BV->getValueType(0).getVectorNumElements());
7291 // Due to the FP element handling below calling this routine recursively,
7292 // we can end up with a scalar-to-vector node here.
7293 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7294 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7295 DAG.getNode(ISD::BITCAST, SDLoc(BV),
7296 DstEltVT, BV->getOperand(0)));
7298 SmallVector<SDValue, 8> Ops;
7299 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7300 SDValue Op = BV->getOperand(i);
7301 // If the vector element type is not legal, the BUILD_VECTOR operands
7302 // are promoted and implicitly truncated. Make that explicit here.
7303 if (Op.getValueType() != SrcEltVT)
7304 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7305 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7307 AddToWorklist(Ops.back().getNode());
7309 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7312 // Otherwise, we're growing or shrinking the elements. To avoid having to
7313 // handle annoying details of growing/shrinking FP values, we convert them to
7315 if (SrcEltVT.isFloatingPoint()) {
7316 // Convert the input float vector to a int vector where the elements are the
7318 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7319 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7323 // Now we know the input is an integer vector. If the output is a FP type,
7324 // convert to integer first, then to FP of the right size.
7325 if (DstEltVT.isFloatingPoint()) {
7326 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7327 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7329 // Next, convert to FP elements of the same size.
7330 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7335 // Okay, we know the src/dst types are both integers of differing types.
7336 // Handling growing first.
7337 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7338 if (SrcBitSize < DstBitSize) {
7339 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7341 SmallVector<SDValue, 8> Ops;
7342 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7343 i += NumInputsPerOutput) {
7344 bool isLE = TLI.isLittleEndian();
7345 APInt NewBits = APInt(DstBitSize, 0);
7346 bool EltIsUndef = true;
7347 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7348 // Shift the previously computed bits over.
7349 NewBits <<= SrcBitSize;
7350 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7351 if (Op.getOpcode() == ISD::UNDEF) continue;
7354 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7355 zextOrTrunc(SrcBitSize).zext(DstBitSize);
7359 Ops.push_back(DAG.getUNDEF(DstEltVT));
7361 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7364 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7365 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7368 // Finally, this must be the case where we are shrinking elements: each input
7369 // turns into multiple outputs.
7370 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7371 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7372 NumOutputsPerInput*BV->getNumOperands());
7373 SmallVector<SDValue, 8> Ops;
7375 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7376 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7377 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7381 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7382 getAPIntValue().zextOrTrunc(SrcBitSize);
7384 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7385 APInt ThisVal = OpVal.trunc(DstBitSize);
7386 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7387 OpVal = OpVal.lshr(DstBitSize);
7390 // For big endian targets, swap the order of the pieces of each element.
7391 if (TLI.isBigEndian())
7392 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7395 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7398 /// Try to perform FMA combining on a given FADD node.
7399 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7400 SDValue N0 = N->getOperand(0);
7401 SDValue N1 = N->getOperand(1);
7402 EVT VT = N->getValueType(0);
7405 const TargetOptions &Options = DAG.getTarget().Options;
7406 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7407 Options.UnsafeFPMath);
7409 // Floating-point multiply-add with intermediate rounding.
7410 bool HasFMAD = (LegalOperations &&
7411 TLI.isOperationLegal(ISD::FMAD, VT));
7413 // Floating-point multiply-add without intermediate rounding.
7414 bool HasFMA = ((!LegalOperations ||
7415 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7416 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7419 // No valid opcode, do not combine.
7420 if (!HasFMAD && !HasFMA)
7423 // Always prefer FMAD to FMA for precision.
7424 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7425 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7426 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7428 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7429 if (N0.getOpcode() == ISD::FMUL &&
7430 (Aggressive || N0->hasOneUse())) {
7431 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7432 N0.getOperand(0), N0.getOperand(1), N1);
7435 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7436 // Note: Commutes FADD operands.
7437 if (N1.getOpcode() == ISD::FMUL &&
7438 (Aggressive || N1->hasOneUse())) {
7439 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7440 N1.getOperand(0), N1.getOperand(1), N0);
7443 // Look through FP_EXTEND nodes to do more combining.
7444 if (UnsafeFPMath && LookThroughFPExt) {
7445 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7446 if (N0.getOpcode() == ISD::FP_EXTEND) {
7447 SDValue N00 = N0.getOperand(0);
7448 if (N00.getOpcode() == ISD::FMUL)
7449 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7450 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7452 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7453 N00.getOperand(1)), N1);
7456 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7457 // Note: Commutes FADD operands.
7458 if (N1.getOpcode() == ISD::FP_EXTEND) {
7459 SDValue N10 = N1.getOperand(0);
7460 if (N10.getOpcode() == ISD::FMUL)
7461 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7462 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7464 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7465 N10.getOperand(1)), N0);
7469 // More folding opportunities when target permits.
7470 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7471 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7472 if (N0.getOpcode() == PreferredFusedOpcode &&
7473 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7474 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7475 N0.getOperand(0), N0.getOperand(1),
7476 DAG.getNode(PreferredFusedOpcode, SL, VT,
7477 N0.getOperand(2).getOperand(0),
7478 N0.getOperand(2).getOperand(1),
7482 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7483 if (N1->getOpcode() == PreferredFusedOpcode &&
7484 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7485 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7486 N1.getOperand(0), N1.getOperand(1),
7487 DAG.getNode(PreferredFusedOpcode, SL, VT,
7488 N1.getOperand(2).getOperand(0),
7489 N1.getOperand(2).getOperand(1),
7493 if (UnsafeFPMath && LookThroughFPExt) {
7494 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7495 // -> (fma x, y, (fma (fpext u), (fpext v), z))
7496 auto FoldFAddFMAFPExtFMul = [&] (
7497 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7498 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7499 DAG.getNode(PreferredFusedOpcode, SL, VT,
7500 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7501 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7504 if (N0.getOpcode() == PreferredFusedOpcode) {
7505 SDValue N02 = N0.getOperand(2);
7506 if (N02.getOpcode() == ISD::FP_EXTEND) {
7507 SDValue N020 = N02.getOperand(0);
7508 if (N020.getOpcode() == ISD::FMUL)
7509 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7510 N020.getOperand(0), N020.getOperand(1),
7515 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7516 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7517 // FIXME: This turns two single-precision and one double-precision
7518 // operation into two double-precision operations, which might not be
7519 // interesting for all targets, especially GPUs.
7520 auto FoldFAddFPExtFMAFMul = [&] (
7521 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7522 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7523 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7524 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7525 DAG.getNode(PreferredFusedOpcode, SL, VT,
7526 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7527 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7530 if (N0.getOpcode() == ISD::FP_EXTEND) {
7531 SDValue N00 = N0.getOperand(0);
7532 if (N00.getOpcode() == PreferredFusedOpcode) {
7533 SDValue N002 = N00.getOperand(2);
7534 if (N002.getOpcode() == ISD::FMUL)
7535 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7536 N002.getOperand(0), N002.getOperand(1),
7541 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7542 // -> (fma y, z, (fma (fpext u), (fpext v), x))
7543 if (N1.getOpcode() == PreferredFusedOpcode) {
7544 SDValue N12 = N1.getOperand(2);
7545 if (N12.getOpcode() == ISD::FP_EXTEND) {
7546 SDValue N120 = N12.getOperand(0);
7547 if (N120.getOpcode() == ISD::FMUL)
7548 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7549 N120.getOperand(0), N120.getOperand(1),
7554 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7555 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7556 // FIXME: This turns two single-precision and one double-precision
7557 // operation into two double-precision operations, which might not be
7558 // interesting for all targets, especially GPUs.
7559 if (N1.getOpcode() == ISD::FP_EXTEND) {
7560 SDValue N10 = N1.getOperand(0);
7561 if (N10.getOpcode() == PreferredFusedOpcode) {
7562 SDValue N102 = N10.getOperand(2);
7563 if (N102.getOpcode() == ISD::FMUL)
7564 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7565 N102.getOperand(0), N102.getOperand(1),
7575 /// Try to perform FMA combining on a given FSUB node.
7576 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7577 SDValue N0 = N->getOperand(0);
7578 SDValue N1 = N->getOperand(1);
7579 EVT VT = N->getValueType(0);
7582 const TargetOptions &Options = DAG.getTarget().Options;
7583 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7584 Options.UnsafeFPMath);
7586 // Floating-point multiply-add with intermediate rounding.
7587 bool HasFMAD = (LegalOperations &&
7588 TLI.isOperationLegal(ISD::FMAD, VT));
7590 // Floating-point multiply-add without intermediate rounding.
7591 bool HasFMA = ((!LegalOperations ||
7592 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7593 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7596 // No valid opcode, do not combine.
7597 if (!HasFMAD && !HasFMA)
7600 // Always prefer FMAD to FMA for precision.
7601 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7602 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7603 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7605 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7606 if (N0.getOpcode() == ISD::FMUL &&
7607 (Aggressive || N0->hasOneUse())) {
7608 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7609 N0.getOperand(0), N0.getOperand(1),
7610 DAG.getNode(ISD::FNEG, SL, VT, N1));
7613 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7614 // Note: Commutes FSUB operands.
7615 if (N1.getOpcode() == ISD::FMUL &&
7616 (Aggressive || N1->hasOneUse()))
7617 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7618 DAG.getNode(ISD::FNEG, SL, VT,
7620 N1.getOperand(1), N0);
7622 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7623 if (N0.getOpcode() == ISD::FNEG &&
7624 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7625 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7626 SDValue N00 = N0.getOperand(0).getOperand(0);
7627 SDValue N01 = N0.getOperand(0).getOperand(1);
7628 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7629 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7630 DAG.getNode(ISD::FNEG, SL, VT, N1));
7633 // Look through FP_EXTEND nodes to do more combining.
7634 if (UnsafeFPMath && LookThroughFPExt) {
7635 // fold (fsub (fpext (fmul x, y)), z)
7636 // -> (fma (fpext x), (fpext y), (fneg z))
7637 if (N0.getOpcode() == ISD::FP_EXTEND) {
7638 SDValue N00 = N0.getOperand(0);
7639 if (N00.getOpcode() == ISD::FMUL)
7640 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7641 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7643 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7645 DAG.getNode(ISD::FNEG, SL, VT, N1));
7648 // fold (fsub x, (fpext (fmul y, z)))
7649 // -> (fma (fneg (fpext y)), (fpext z), x)
7650 // Note: Commutes FSUB operands.
7651 if (N1.getOpcode() == ISD::FP_EXTEND) {
7652 SDValue N10 = N1.getOperand(0);
7653 if (N10.getOpcode() == ISD::FMUL)
7654 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7655 DAG.getNode(ISD::FNEG, SL, VT,
7656 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7657 N10.getOperand(0))),
7658 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7663 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7664 // -> (fneg (fma (fpext x), (fpext y), z))
7665 // Note: This could be removed with appropriate canonicalization of the
7666 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7667 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7668 // from implementing the canonicalization in visitFSUB.
7669 if (N0.getOpcode() == ISD::FP_EXTEND) {
7670 SDValue N00 = N0.getOperand(0);
7671 if (N00.getOpcode() == ISD::FNEG) {
7672 SDValue N000 = N00.getOperand(0);
7673 if (N000.getOpcode() == ISD::FMUL) {
7674 return DAG.getNode(ISD::FNEG, SL, VT,
7675 DAG.getNode(PreferredFusedOpcode, SL, VT,
7676 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7677 N000.getOperand(0)),
7678 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7679 N000.getOperand(1)),
7685 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7686 // -> (fneg (fma (fpext x)), (fpext y), z)
7687 // Note: This could be removed with appropriate canonicalization of the
7688 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7689 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7690 // from implementing the canonicalization in visitFSUB.
7691 if (N0.getOpcode() == ISD::FNEG) {
7692 SDValue N00 = N0.getOperand(0);
7693 if (N00.getOpcode() == ISD::FP_EXTEND) {
7694 SDValue N000 = N00.getOperand(0);
7695 if (N000.getOpcode() == ISD::FMUL) {
7696 return DAG.getNode(ISD::FNEG, SL, VT,
7697 DAG.getNode(PreferredFusedOpcode, SL, VT,
7698 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7699 N000.getOperand(0)),
7700 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7701 N000.getOperand(1)),
7709 // More folding opportunities when target permits.
7710 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7711 // fold (fsub (fma x, y, (fmul u, v)), z)
7712 // -> (fma x, y (fma u, v, (fneg z)))
7713 if (N0.getOpcode() == PreferredFusedOpcode &&
7714 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7715 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7716 N0.getOperand(0), N0.getOperand(1),
7717 DAG.getNode(PreferredFusedOpcode, SL, VT,
7718 N0.getOperand(2).getOperand(0),
7719 N0.getOperand(2).getOperand(1),
7720 DAG.getNode(ISD::FNEG, SL, VT,
7724 // fold (fsub x, (fma y, z, (fmul u, v)))
7725 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7726 if (N1.getOpcode() == PreferredFusedOpcode &&
7727 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7728 SDValue N20 = N1.getOperand(2).getOperand(0);
7729 SDValue N21 = N1.getOperand(2).getOperand(1);
7730 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7731 DAG.getNode(ISD::FNEG, SL, VT,
7734 DAG.getNode(PreferredFusedOpcode, SL, VT,
7735 DAG.getNode(ISD::FNEG, SL, VT, N20),
7740 if (UnsafeFPMath && LookThroughFPExt) {
7741 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7742 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7743 if (N0.getOpcode() == PreferredFusedOpcode) {
7744 SDValue N02 = N0.getOperand(2);
7745 if (N02.getOpcode() == ISD::FP_EXTEND) {
7746 SDValue N020 = N02.getOperand(0);
7747 if (N020.getOpcode() == ISD::FMUL)
7748 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7749 N0.getOperand(0), N0.getOperand(1),
7750 DAG.getNode(PreferredFusedOpcode, SL, VT,
7751 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7752 N020.getOperand(0)),
7753 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7754 N020.getOperand(1)),
7755 DAG.getNode(ISD::FNEG, SL, VT,
7760 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7761 // -> (fma (fpext x), (fpext y),
7762 // (fma (fpext u), (fpext v), (fneg z)))
7763 // FIXME: This turns two single-precision and one double-precision
7764 // operation into two double-precision operations, which might not be
7765 // interesting for all targets, especially GPUs.
7766 if (N0.getOpcode() == ISD::FP_EXTEND) {
7767 SDValue N00 = N0.getOperand(0);
7768 if (N00.getOpcode() == PreferredFusedOpcode) {
7769 SDValue N002 = N00.getOperand(2);
7770 if (N002.getOpcode() == ISD::FMUL)
7771 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7772 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7774 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7776 DAG.getNode(PreferredFusedOpcode, SL, VT,
7777 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7778 N002.getOperand(0)),
7779 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7780 N002.getOperand(1)),
7781 DAG.getNode(ISD::FNEG, SL, VT,
7786 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7787 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7788 if (N1.getOpcode() == PreferredFusedOpcode &&
7789 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7790 SDValue N120 = N1.getOperand(2).getOperand(0);
7791 if (N120.getOpcode() == ISD::FMUL) {
7792 SDValue N1200 = N120.getOperand(0);
7793 SDValue N1201 = N120.getOperand(1);
7794 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7795 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7797 DAG.getNode(PreferredFusedOpcode, SL, VT,
7798 DAG.getNode(ISD::FNEG, SL, VT,
7799 DAG.getNode(ISD::FP_EXTEND, SL,
7801 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7807 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7808 // -> (fma (fneg (fpext y)), (fpext z),
7809 // (fma (fneg (fpext u)), (fpext v), x))
7810 // FIXME: This turns two single-precision and one double-precision
7811 // operation into two double-precision operations, which might not be
7812 // interesting for all targets, especially GPUs.
7813 if (N1.getOpcode() == ISD::FP_EXTEND &&
7814 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7815 SDValue N100 = N1.getOperand(0).getOperand(0);
7816 SDValue N101 = N1.getOperand(0).getOperand(1);
7817 SDValue N102 = N1.getOperand(0).getOperand(2);
7818 if (N102.getOpcode() == ISD::FMUL) {
7819 SDValue N1020 = N102.getOperand(0);
7820 SDValue N1021 = N102.getOperand(1);
7821 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7822 DAG.getNode(ISD::FNEG, SL, VT,
7823 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7825 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7826 DAG.getNode(PreferredFusedOpcode, SL, VT,
7827 DAG.getNode(ISD::FNEG, SL, VT,
7828 DAG.getNode(ISD::FP_EXTEND, SL,
7830 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7841 SDValue DAGCombiner::visitFADD(SDNode *N) {
7842 SDValue N0 = N->getOperand(0);
7843 SDValue N1 = N->getOperand(1);
7844 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7845 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7846 EVT VT = N->getValueType(0);
7848 const TargetOptions &Options = DAG.getTarget().Options;
7852 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7855 // fold (fadd c1, c2) -> c1 + c2
7857 return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7859 // canonicalize constant to RHS
7860 if (N0CFP && !N1CFP)
7861 return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7863 // fold (fadd A, (fneg B)) -> (fsub A, B)
7864 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7865 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7866 return DAG.getNode(ISD::FSUB, DL, VT, N0,
7867 GetNegatedExpression(N1, DAG, LegalOperations));
7869 // fold (fadd (fneg A), B) -> (fsub B, A)
7870 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7871 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7872 return DAG.getNode(ISD::FSUB, DL, VT, N1,
7873 GetNegatedExpression(N0, DAG, LegalOperations));
7875 // If 'unsafe math' is enabled, fold lots of things.
7876 if (Options.UnsafeFPMath) {
7877 // No FP constant should be created after legalization as Instruction
7878 // Selection pass has a hard time dealing with FP constants.
7879 bool AllowNewConst = (Level < AfterLegalizeDAG);
7881 // fold (fadd A, 0) -> A
7882 if (N1CFP && N1CFP->isZero())
7885 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7886 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7887 isa<ConstantFPSDNode>(N0.getOperand(1)))
7888 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7889 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7891 // If allowed, fold (fadd (fneg x), x) -> 0.0
7892 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7893 return DAG.getConstantFP(0.0, DL, VT);
7895 // If allowed, fold (fadd x, (fneg x)) -> 0.0
7896 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7897 return DAG.getConstantFP(0.0, DL, VT);
7899 // We can fold chains of FADD's of the same value into multiplications.
7900 // This transform is not safe in general because we are reducing the number
7901 // of rounding steps.
7902 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7903 if (N0.getOpcode() == ISD::FMUL) {
7904 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7905 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7907 // (fadd (fmul x, c), x) -> (fmul x, c+1)
7908 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7909 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7910 DAG.getConstantFP(1.0, DL, VT));
7911 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7914 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7915 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7916 N1.getOperand(0) == N1.getOperand(1) &&
7917 N0.getOperand(0) == N1.getOperand(0)) {
7918 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7919 DAG.getConstantFP(2.0, DL, VT));
7920 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
7924 if (N1.getOpcode() == ISD::FMUL) {
7925 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7926 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7928 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7929 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7930 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7931 DAG.getConstantFP(1.0, DL, VT));
7932 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
7935 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7936 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7937 N0.getOperand(0) == N0.getOperand(1) &&
7938 N1.getOperand(0) == N0.getOperand(0)) {
7939 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7940 DAG.getConstantFP(2.0, DL, VT));
7941 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
7945 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7946 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7947 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7948 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7949 (N0.getOperand(0) == N1)) {
7950 return DAG.getNode(ISD::FMUL, DL, VT,
7951 N1, DAG.getConstantFP(3.0, DL, VT));
7955 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7956 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7957 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7958 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7959 N1.getOperand(0) == N0) {
7960 return DAG.getNode(ISD::FMUL, DL, VT,
7961 N0, DAG.getConstantFP(3.0, DL, VT));
7965 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7966 if (AllowNewConst &&
7967 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7968 N0.getOperand(0) == N0.getOperand(1) &&
7969 N1.getOperand(0) == N1.getOperand(1) &&
7970 N0.getOperand(0) == N1.getOperand(0)) {
7971 return DAG.getNode(ISD::FMUL, DL, VT,
7972 N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
7975 } // enable-unsafe-fp-math
7977 // FADD -> FMA combines:
7978 SDValue Fused = visitFADDForFMACombine(N);
7980 AddToWorklist(Fused.getNode());
7987 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7988 SDValue N0 = N->getOperand(0);
7989 SDValue N1 = N->getOperand(1);
7990 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7991 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7992 EVT VT = N->getValueType(0);
7994 const TargetOptions &Options = DAG.getTarget().Options;
7998 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8001 // fold (fsub c1, c2) -> c1-c2
8003 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
8005 // fold (fsub A, (fneg B)) -> (fadd A, B)
8006 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8007 return DAG.getNode(ISD::FADD, dl, VT, N0,
8008 GetNegatedExpression(N1, DAG, LegalOperations));
8010 // If 'unsafe math' is enabled, fold lots of things.
8011 if (Options.UnsafeFPMath) {
8013 if (N1CFP && N1CFP->isZero())
8016 // (fsub 0, B) -> -B
8017 if (N0CFP && N0CFP->isZero()) {
8018 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8019 return GetNegatedExpression(N1, DAG, LegalOperations);
8020 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8021 return DAG.getNode(ISD::FNEG, dl, VT, N1);
8024 // (fsub x, x) -> 0.0
8026 return DAG.getConstantFP(0.0f, dl, VT);
8028 // (fsub x, (fadd x, y)) -> (fneg y)
8029 // (fsub x, (fadd y, x)) -> (fneg y)
8030 if (N1.getOpcode() == ISD::FADD) {
8031 SDValue N10 = N1->getOperand(0);
8032 SDValue N11 = N1->getOperand(1);
8034 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8035 return GetNegatedExpression(N11, DAG, LegalOperations);
8037 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8038 return GetNegatedExpression(N10, DAG, LegalOperations);
8042 // FSUB -> FMA combines:
8043 SDValue Fused = visitFSUBForFMACombine(N);
8045 AddToWorklist(Fused.getNode());
8052 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8053 SDValue N0 = N->getOperand(0);
8054 SDValue N1 = N->getOperand(1);
8055 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8056 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8057 EVT VT = N->getValueType(0);
8059 const TargetOptions &Options = DAG.getTarget().Options;
8062 if (VT.isVector()) {
8063 // This just handles C1 * C2 for vectors. Other vector folds are below.
8064 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8068 // fold (fmul c1, c2) -> c1*c2
8070 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
8072 // canonicalize constant to RHS
8073 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8074 !isConstantFPBuildVectorOrConstantFP(N1))
8075 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
8077 // fold (fmul A, 1.0) -> A
8078 if (N1CFP && N1CFP->isExactlyValue(1.0))
8081 if (Options.UnsafeFPMath) {
8082 // fold (fmul A, 0) -> 0
8083 if (N1CFP && N1CFP->isZero())
8086 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8087 if (N0.getOpcode() == ISD::FMUL) {
8088 // Fold scalars or any vector constants (not just splats).
8089 // This fold is done in general by InstCombine, but extra fmul insts
8090 // may have been generated during lowering.
8091 SDValue N00 = N0.getOperand(0);
8092 SDValue N01 = N0.getOperand(1);
8093 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8094 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8095 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8097 // Check 1: Make sure that the first operand of the inner multiply is NOT
8098 // a constant. Otherwise, we may induce infinite looping.
8099 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8100 // Check 2: Make sure that the second operand of the inner multiply and
8101 // the second operand of the outer multiply are constants.
8102 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8103 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8104 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8105 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
8110 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8111 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8112 // during an early run of DAGCombiner can prevent folding with fmuls
8113 // inserted during lowering.
8114 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
8115 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8116 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8117 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
8121 // fold (fmul X, 2.0) -> (fadd X, X)
8122 if (N1CFP && N1CFP->isExactlyValue(+2.0))
8123 return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
8125 // fold (fmul X, -1.0) -> (fneg X)
8126 if (N1CFP && N1CFP->isExactlyValue(-1.0))
8127 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8128 return DAG.getNode(ISD::FNEG, DL, VT, N0);
8130 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8131 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8132 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8133 // Both can be negated for free, check to see if at least one is cheaper
8135 if (LHSNeg == 2 || RHSNeg == 2)
8136 return DAG.getNode(ISD::FMUL, DL, VT,
8137 GetNegatedExpression(N0, DAG, LegalOperations),
8138 GetNegatedExpression(N1, DAG, LegalOperations));
8145 SDValue DAGCombiner::visitFMA(SDNode *N) {
8146 SDValue N0 = N->getOperand(0);
8147 SDValue N1 = N->getOperand(1);
8148 SDValue N2 = N->getOperand(2);
8149 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8150 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8151 EVT VT = N->getValueType(0);
8153 const TargetOptions &Options = DAG.getTarget().Options;
8155 // Constant fold FMA.
8156 if (isa<ConstantFPSDNode>(N0) &&
8157 isa<ConstantFPSDNode>(N1) &&
8158 isa<ConstantFPSDNode>(N2)) {
8159 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8162 if (Options.UnsafeFPMath) {
8163 if (N0CFP && N0CFP->isZero())
8165 if (N1CFP && N1CFP->isZero())
8168 if (N0CFP && N0CFP->isExactlyValue(1.0))
8169 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8170 if (N1CFP && N1CFP->isExactlyValue(1.0))
8171 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8173 // Canonicalize (fma c, x, y) -> (fma x, c, y)
8174 if (N0CFP && !N1CFP)
8175 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8177 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8178 if (Options.UnsafeFPMath && N1CFP &&
8179 N2.getOpcode() == ISD::FMUL &&
8180 N0 == N2.getOperand(0) &&
8181 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8182 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8183 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8187 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8188 if (Options.UnsafeFPMath &&
8189 N0.getOpcode() == ISD::FMUL && N1CFP &&
8190 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8191 return DAG.getNode(ISD::FMA, dl, VT,
8193 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8197 // (fma x, 1, y) -> (fadd x, y)
8198 // (fma x, -1, y) -> (fadd (fneg x), y)
8200 if (N1CFP->isExactlyValue(1.0))
8201 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8203 if (N1CFP->isExactlyValue(-1.0) &&
8204 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8205 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8206 AddToWorklist(RHSNeg.getNode());
8207 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8211 // (fma x, c, x) -> (fmul x, (c+1))
8212 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8213 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8214 DAG.getNode(ISD::FADD, dl, VT,
8215 N1, DAG.getConstantFP(1.0, dl, VT)));
8217 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8218 if (Options.UnsafeFPMath && N1CFP &&
8219 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8220 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8221 DAG.getNode(ISD::FADD, dl, VT,
8222 N1, DAG.getConstantFP(-1.0, dl, VT)));
8228 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8229 SDValue N0 = N->getOperand(0);
8230 SDValue N1 = N->getOperand(1);
8231 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8232 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8233 EVT VT = N->getValueType(0);
8235 const TargetOptions &Options = DAG.getTarget().Options;
8239 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8242 // fold (fdiv c1, c2) -> c1/c2
8244 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8246 if (Options.UnsafeFPMath) {
8247 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8249 // Compute the reciprocal 1.0 / c2.
8250 APFloat N1APF = N1CFP->getValueAPF();
8251 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8252 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8253 // Only do the transform if the reciprocal is a legal fp immediate that
8254 // isn't too nasty (eg NaN, denormal, ...).
8255 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8256 (!LegalOperations ||
8257 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8258 // backend)... we should handle this gracefully after Legalize.
8259 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8260 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8261 TLI.isFPImmLegal(Recip, VT)))
8262 return DAG.getNode(ISD::FMUL, DL, VT, N0,
8263 DAG.getConstantFP(Recip, DL, VT));
8266 // If this FDIV is part of a reciprocal square root, it may be folded
8267 // into a target-specific square root estimate instruction.
8268 if (N1.getOpcode() == ISD::FSQRT) {
8269 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8270 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8272 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8273 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8274 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8275 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8276 AddToWorklist(RV.getNode());
8277 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8279 } else if (N1.getOpcode() == ISD::FP_ROUND &&
8280 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8281 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8282 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8283 AddToWorklist(RV.getNode());
8284 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8286 } else if (N1.getOpcode() == ISD::FMUL) {
8287 // Look through an FMUL. Even though this won't remove the FDIV directly,
8288 // it's still worthwhile to get rid of the FSQRT if possible.
8291 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8292 SqrtOp = N1.getOperand(0);
8293 OtherOp = N1.getOperand(1);
8294 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8295 SqrtOp = N1.getOperand(1);
8296 OtherOp = N1.getOperand(0);
8298 if (SqrtOp.getNode()) {
8299 // We found a FSQRT, so try to make this fold:
8300 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8301 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8302 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8303 AddToWorklist(RV.getNode());
8304 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8309 // Fold into a reciprocal estimate and multiply instead of a real divide.
8310 if (SDValue RV = BuildReciprocalEstimate(N1)) {
8311 AddToWorklist(RV.getNode());
8312 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8316 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8317 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8318 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8319 // Both can be negated for free, check to see if at least one is cheaper
8321 if (LHSNeg == 2 || RHSNeg == 2)
8322 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8323 GetNegatedExpression(N0, DAG, LegalOperations),
8324 GetNegatedExpression(N1, DAG, LegalOperations));
8328 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8330 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8331 // Notice that this is not always beneficial. One reason is different target
8332 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8333 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8334 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8335 if (Options.UnsafeFPMath) {
8336 // Skip if current node is a reciprocal.
8337 if (N0CFP && N0CFP->isExactlyValue(1.0))
8340 SmallVector<SDNode *, 4> Users;
8341 // Find all FDIV users of the same divisor.
8342 for (auto *U : N1->uses()) {
8343 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8347 if (TLI.combineRepeatedFPDivisors(Users.size())) {
8348 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8349 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8351 // Dividend / Divisor -> Dividend * Reciprocal
8352 for (auto *U : Users) {
8353 SDValue Dividend = U->getOperand(0);
8354 if (Dividend != FPOne) {
8355 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8357 DAG.ReplaceAllUsesWith(U, NewNode.getNode());
8367 SDValue DAGCombiner::visitFREM(SDNode *N) {
8368 SDValue N0 = N->getOperand(0);
8369 SDValue N1 = N->getOperand(1);
8370 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8371 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8372 EVT VT = N->getValueType(0);
8374 // fold (frem c1, c2) -> fmod(c1,c2)
8376 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8381 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8382 if (DAG.getTarget().Options.UnsafeFPMath &&
8383 !TLI.isFsqrtCheap()) {
8384 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8385 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
8386 EVT VT = RV.getValueType();
8388 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8389 AddToWorklist(RV.getNode());
8391 // Unfortunately, RV is now NaN if the input was exactly 0.
8392 // Select out this case and force the answer to 0.
8393 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8395 DAG.getSetCC(DL, TLI.getSetCCResultType(*DAG.getContext(), VT),
8396 N->getOperand(0), Zero, ISD::SETEQ);
8397 AddToWorklist(ZeroCmp.getNode());
8398 AddToWorklist(RV.getNode());
8400 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8401 DL, VT, ZeroCmp, Zero, RV);
8408 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8409 SDValue N0 = N->getOperand(0);
8410 SDValue N1 = N->getOperand(1);
8411 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8412 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8413 EVT VT = N->getValueType(0);
8415 if (N0CFP && N1CFP) // Constant fold
8416 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8419 const APFloat& V = N1CFP->getValueAPF();
8420 // copysign(x, c1) -> fabs(x) iff ispos(c1)
8421 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8422 if (!V.isNegative()) {
8423 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8424 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8426 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8427 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8428 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8432 // copysign(fabs(x), y) -> copysign(x, y)
8433 // copysign(fneg(x), y) -> copysign(x, y)
8434 // copysign(copysign(x,z), y) -> copysign(x, y)
8435 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8436 N0.getOpcode() == ISD::FCOPYSIGN)
8437 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8438 N0.getOperand(0), N1);
8440 // copysign(x, abs(y)) -> abs(x)
8441 if (N1.getOpcode() == ISD::FABS)
8442 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8444 // copysign(x, copysign(y,z)) -> copysign(x, z)
8445 if (N1.getOpcode() == ISD::FCOPYSIGN)
8446 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8447 N0, N1.getOperand(1));
8449 // copysign(x, fp_extend(y)) -> copysign(x, y)
8450 // copysign(x, fp_round(y)) -> copysign(x, y)
8451 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8452 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8453 N0, N1.getOperand(0));
8458 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8459 SDValue N0 = N->getOperand(0);
8460 EVT VT = N->getValueType(0);
8461 EVT OpVT = N0.getValueType();
8463 // fold (sint_to_fp c1) -> c1fp
8464 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8465 // ...but only if the target supports immediate floating-point values
8466 (!LegalOperations ||
8467 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8468 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8470 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8471 // but UINT_TO_FP is legal on this target, try to convert.
8472 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8473 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8474 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8475 if (DAG.SignBitIsZero(N0))
8476 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8479 // The next optimizations are desirable only if SELECT_CC can be lowered.
8480 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8481 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8482 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8484 (!LegalOperations ||
8485 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8488 { N0.getOperand(0), N0.getOperand(1),
8489 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8491 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8494 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8495 // (select_cc x, y, 1.0, 0.0,, cc)
8496 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8497 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8498 (!LegalOperations ||
8499 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8502 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8503 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8504 N0.getOperand(0).getOperand(2) };
8505 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8512 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8513 SDValue N0 = N->getOperand(0);
8514 EVT VT = N->getValueType(0);
8515 EVT OpVT = N0.getValueType();
8517 // fold (uint_to_fp c1) -> c1fp
8518 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8519 // ...but only if the target supports immediate floating-point values
8520 (!LegalOperations ||
8521 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8522 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8524 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8525 // but SINT_TO_FP is legal on this target, try to convert.
8526 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8527 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8528 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8529 if (DAG.SignBitIsZero(N0))
8530 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8533 // The next optimizations are desirable only if SELECT_CC can be lowered.
8534 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8535 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8537 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8538 (!LegalOperations ||
8539 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8542 { N0.getOperand(0), N0.getOperand(1),
8543 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8545 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8552 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8553 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8554 SDValue N0 = N->getOperand(0);
8555 EVT VT = N->getValueType(0);
8557 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8560 SDValue Src = N0.getOperand(0);
8561 EVT SrcVT = Src.getValueType();
8562 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8563 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8565 // We can safely assume the conversion won't overflow the output range,
8566 // because (for example) (uint8_t)18293.f is undefined behavior.
8568 // Since we can assume the conversion won't overflow, our decision as to
8569 // whether the input will fit in the float should depend on the minimum
8570 // of the input range and output range.
8572 // This means this is also safe for a signed input and unsigned output, since
8573 // a negative input would lead to undefined behavior.
8574 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8575 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8576 unsigned ActualSize = std::min(InputSize, OutputSize);
8577 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8579 // We can only fold away the float conversion if the input range can be
8580 // represented exactly in the float range.
8581 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8582 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8583 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8585 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8587 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8588 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8591 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8596 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8597 SDValue N0 = N->getOperand(0);
8598 EVT VT = N->getValueType(0);
8600 // fold (fp_to_sint c1fp) -> c1
8601 if (isConstantFPBuildVectorOrConstantFP(N0))
8602 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8604 return FoldIntToFPToInt(N, DAG);
8607 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8608 SDValue N0 = N->getOperand(0);
8609 EVT VT = N->getValueType(0);
8611 // fold (fp_to_uint c1fp) -> c1
8612 if (isConstantFPBuildVectorOrConstantFP(N0))
8613 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8615 return FoldIntToFPToInt(N, DAG);
8618 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8619 SDValue N0 = N->getOperand(0);
8620 SDValue N1 = N->getOperand(1);
8621 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8622 EVT VT = N->getValueType(0);
8624 // fold (fp_round c1fp) -> c1fp
8626 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8628 // fold (fp_round (fp_extend x)) -> x
8629 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8630 return N0.getOperand(0);
8632 // fold (fp_round (fp_round x)) -> (fp_round x)
8633 if (N0.getOpcode() == ISD::FP_ROUND) {
8634 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8635 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8636 // If the first fp_round isn't a value preserving truncation, it might
8637 // introduce a tie in the second fp_round, that wouldn't occur in the
8638 // single-step fp_round we want to fold to.
8639 // In other words, double rounding isn't the same as rounding.
8640 // Also, this is a value preserving truncation iff both fp_round's are.
8641 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8643 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8644 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8648 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8649 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8650 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8651 N0.getOperand(0), N1);
8652 AddToWorklist(Tmp.getNode());
8653 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8654 Tmp, N0.getOperand(1));
8660 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8661 SDValue N0 = N->getOperand(0);
8662 EVT VT = N->getValueType(0);
8663 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8664 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8666 // fold (fp_round_inreg c1fp) -> c1fp
8667 if (N0CFP && isTypeLegal(EVT)) {
8669 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8670 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8676 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8677 SDValue N0 = N->getOperand(0);
8678 EVT VT = N->getValueType(0);
8680 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8681 if (N->hasOneUse() &&
8682 N->use_begin()->getOpcode() == ISD::FP_ROUND)
8685 // fold (fp_extend c1fp) -> c1fp
8686 if (isConstantFPBuildVectorOrConstantFP(N0))
8687 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8689 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8690 if (N0.getOpcode() == ISD::FP16_TO_FP &&
8691 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8692 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8694 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8696 if (N0.getOpcode() == ISD::FP_ROUND
8697 && N0.getNode()->getConstantOperandVal(1) == 1) {
8698 SDValue In = N0.getOperand(0);
8699 if (In.getValueType() == VT) return In;
8700 if (VT.bitsLT(In.getValueType()))
8701 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8702 In, N0.getOperand(1));
8703 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8706 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8707 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8708 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8709 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8710 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8712 LN0->getBasePtr(), N0.getValueType(),
8713 LN0->getMemOperand());
8714 CombineTo(N, ExtLoad);
8715 CombineTo(N0.getNode(),
8716 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8717 N0.getValueType(), ExtLoad,
8718 DAG.getIntPtrConstant(1, SDLoc(N0))),
8719 ExtLoad.getValue(1));
8720 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8726 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8727 SDValue N0 = N->getOperand(0);
8728 EVT VT = N->getValueType(0);
8730 // fold (fceil c1) -> fceil(c1)
8731 if (isConstantFPBuildVectorOrConstantFP(N0))
8732 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8737 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8738 SDValue N0 = N->getOperand(0);
8739 EVT VT = N->getValueType(0);
8741 // fold (ftrunc c1) -> ftrunc(c1)
8742 if (isConstantFPBuildVectorOrConstantFP(N0))
8743 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8748 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8749 SDValue N0 = N->getOperand(0);
8750 EVT VT = N->getValueType(0);
8752 // fold (ffloor c1) -> ffloor(c1)
8753 if (isConstantFPBuildVectorOrConstantFP(N0))
8754 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8759 // FIXME: FNEG and FABS have a lot in common; refactor.
8760 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8761 SDValue N0 = N->getOperand(0);
8762 EVT VT = N->getValueType(0);
8764 // Constant fold FNEG.
8765 if (isConstantFPBuildVectorOrConstantFP(N0))
8766 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8768 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8769 &DAG.getTarget().Options))
8770 return GetNegatedExpression(N0, DAG, LegalOperations);
8772 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8773 // constant pool values.
8774 if (!TLI.isFNegFree(VT) &&
8775 N0.getOpcode() == ISD::BITCAST &&
8776 N0.getNode()->hasOneUse()) {
8777 SDValue Int = N0.getOperand(0);
8778 EVT IntVT = Int.getValueType();
8779 if (IntVT.isInteger() && !IntVT.isVector()) {
8781 if (N0.getValueType().isVector()) {
8782 // For a vector, get a mask such as 0x80... per scalar element
8784 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8785 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8787 // For a scalar, just generate 0x80...
8788 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8791 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8792 DAG.getConstant(SignMask, DL0, IntVT));
8793 AddToWorklist(Int.getNode());
8794 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8798 // (fneg (fmul c, x)) -> (fmul -c, x)
8799 if (N0.getOpcode() == ISD::FMUL &&
8800 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
8801 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8803 APFloat CVal = CFP1->getValueAPF();
8805 if (Level >= AfterLegalizeDAG &&
8806 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8807 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8809 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8810 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8817 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8818 SDValue N0 = N->getOperand(0);
8819 SDValue N1 = N->getOperand(1);
8820 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8821 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8823 if (N0CFP && N1CFP) {
8824 const APFloat &C0 = N0CFP->getValueAPF();
8825 const APFloat &C1 = N1CFP->getValueAPF();
8826 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8830 EVT VT = N->getValueType(0);
8831 // Canonicalize to constant on RHS.
8832 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8838 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8839 SDValue N0 = N->getOperand(0);
8840 SDValue N1 = N->getOperand(1);
8841 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8842 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8844 if (N0CFP && N1CFP) {
8845 const APFloat &C0 = N0CFP->getValueAPF();
8846 const APFloat &C1 = N1CFP->getValueAPF();
8847 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8851 EVT VT = N->getValueType(0);
8852 // Canonicalize to constant on RHS.
8853 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8859 SDValue DAGCombiner::visitFABS(SDNode *N) {
8860 SDValue N0 = N->getOperand(0);
8861 EVT VT = N->getValueType(0);
8863 // fold (fabs c1) -> fabs(c1)
8864 if (isConstantFPBuildVectorOrConstantFP(N0))
8865 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8867 // fold (fabs (fabs x)) -> (fabs x)
8868 if (N0.getOpcode() == ISD::FABS)
8869 return N->getOperand(0);
8871 // fold (fabs (fneg x)) -> (fabs x)
8872 // fold (fabs (fcopysign x, y)) -> (fabs x)
8873 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8874 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8876 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8877 // constant pool values.
8878 if (!TLI.isFAbsFree(VT) &&
8879 N0.getOpcode() == ISD::BITCAST &&
8880 N0.getNode()->hasOneUse()) {
8881 SDValue Int = N0.getOperand(0);
8882 EVT IntVT = Int.getValueType();
8883 if (IntVT.isInteger() && !IntVT.isVector()) {
8885 if (N0.getValueType().isVector()) {
8886 // For a vector, get a mask such as 0x7f... per scalar element
8888 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8889 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8891 // For a scalar, just generate 0x7f...
8892 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8895 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8896 DAG.getConstant(SignMask, DL, IntVT));
8897 AddToWorklist(Int.getNode());
8898 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8905 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8906 SDValue Chain = N->getOperand(0);
8907 SDValue N1 = N->getOperand(1);
8908 SDValue N2 = N->getOperand(2);
8910 // If N is a constant we could fold this into a fallthrough or unconditional
8911 // branch. However that doesn't happen very often in normal code, because
8912 // Instcombine/SimplifyCFG should have handled the available opportunities.
8913 // If we did this folding here, it would be necessary to update the
8914 // MachineBasicBlock CFG, which is awkward.
8916 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8918 if (N1.getOpcode() == ISD::SETCC &&
8919 TLI.isOperationLegalOrCustom(ISD::BR_CC,
8920 N1.getOperand(0).getValueType())) {
8921 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8922 Chain, N1.getOperand(2),
8923 N1.getOperand(0), N1.getOperand(1), N2);
8926 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8927 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8928 (N1.getOperand(0).hasOneUse() &&
8929 N1.getOperand(0).getOpcode() == ISD::SRL))) {
8930 SDNode *Trunc = nullptr;
8931 if (N1.getOpcode() == ISD::TRUNCATE) {
8932 // Look pass the truncate.
8933 Trunc = N1.getNode();
8934 N1 = N1.getOperand(0);
8937 // Match this pattern so that we can generate simpler code:
8940 // %b = and i32 %a, 2
8941 // %c = srl i32 %b, 1
8942 // brcond i32 %c ...
8947 // %b = and i32 %a, 2
8948 // %c = setcc eq %b, 0
8951 // This applies only when the AND constant value has one bit set and the
8952 // SRL constant is equal to the log2 of the AND constant. The back-end is
8953 // smart enough to convert the result into a TEST/JMP sequence.
8954 SDValue Op0 = N1.getOperand(0);
8955 SDValue Op1 = N1.getOperand(1);
8957 if (Op0.getOpcode() == ISD::AND &&
8958 Op1.getOpcode() == ISD::Constant) {
8959 SDValue AndOp1 = Op0.getOperand(1);
8961 if (AndOp1.getOpcode() == ISD::Constant) {
8962 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8964 if (AndConst.isPowerOf2() &&
8965 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8969 getSetCCResultType(Op0.getValueType()),
8970 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
8973 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
8974 MVT::Other, Chain, SetCC, N2);
8975 // Don't add the new BRCond into the worklist or else SimplifySelectCC
8976 // will convert it back to (X & C1) >> C2.
8977 CombineTo(N, NewBRCond, false);
8978 // Truncate is dead.
8980 deleteAndRecombine(Trunc);
8981 // Replace the uses of SRL with SETCC
8982 WorklistRemover DeadNodes(*this);
8983 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8984 deleteAndRecombine(N1.getNode());
8985 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8991 // Restore N1 if the above transformation doesn't match.
8992 N1 = N->getOperand(1);
8995 // Transform br(xor(x, y)) -> br(x != y)
8996 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8997 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8998 SDNode *TheXor = N1.getNode();
8999 SDValue Op0 = TheXor->getOperand(0);
9000 SDValue Op1 = TheXor->getOperand(1);
9001 if (Op0.getOpcode() == Op1.getOpcode()) {
9002 // Avoid missing important xor optimizations.
9003 SDValue Tmp = visitXOR(TheXor);
9004 if (Tmp.getNode()) {
9005 if (Tmp.getNode() != TheXor) {
9006 DEBUG(dbgs() << "\nReplacing.8 ";
9008 dbgs() << "\nWith: ";
9009 Tmp.getNode()->dump(&DAG);
9011 WorklistRemover DeadNodes(*this);
9012 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9013 deleteAndRecombine(TheXor);
9014 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9015 MVT::Other, Chain, Tmp, N2);
9018 // visitXOR has changed XOR's operands or replaced the XOR completely,
9020 return SDValue(N, 0);
9024 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9026 if (isOneConstant(Op0) && Op0.hasOneUse() &&
9027 Op0.getOpcode() == ISD::XOR) {
9028 TheXor = Op0.getNode();
9032 EVT SetCCVT = N1.getValueType();
9034 SetCCVT = getSetCCResultType(SetCCVT);
9035 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9038 Equal ? ISD::SETEQ : ISD::SETNE);
9039 // Replace the uses of XOR with SETCC
9040 WorklistRemover DeadNodes(*this);
9041 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9042 deleteAndRecombine(N1.getNode());
9043 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9044 MVT::Other, Chain, SetCC, N2);
9051 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9053 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9054 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9055 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9057 // If N is a constant we could fold this into a fallthrough or unconditional
9058 // branch. However that doesn't happen very often in normal code, because
9059 // Instcombine/SimplifyCFG should have handled the available opportunities.
9060 // If we did this folding here, it would be necessary to update the
9061 // MachineBasicBlock CFG, which is awkward.
9063 // Use SimplifySetCC to simplify SETCC's.
9064 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9065 CondLHS, CondRHS, CC->get(), SDLoc(N),
9067 if (Simp.getNode()) AddToWorklist(Simp.getNode());
9069 // fold to a simpler setcc
9070 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9071 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9072 N->getOperand(0), Simp.getOperand(2),
9073 Simp.getOperand(0), Simp.getOperand(1),
9079 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9080 /// and that N may be folded in the load / store addressing mode.
9081 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9083 const TargetLowering &TLI) {
9087 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
9088 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9090 VT = LD->getMemoryVT();
9091 AS = LD->getAddressSpace();
9092 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
9093 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9095 VT = ST->getMemoryVT();
9096 AS = ST->getAddressSpace();
9100 TargetLowering::AddrMode AM;
9101 if (N->getOpcode() == ISD::ADD) {
9102 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9105 AM.BaseOffs = Offset->getSExtValue();
9109 } else if (N->getOpcode() == ISD::SUB) {
9110 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9113 AM.BaseOffs = -Offset->getSExtValue();
9120 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()), AS);
9123 /// Try turning a load/store into a pre-indexed load/store when the base
9124 /// pointer is an add or subtract and it has other uses besides the load/store.
9125 /// After the transformation, the new indexed load/store has effectively folded
9126 /// the add/subtract in and all of its other uses are redirected to the
9128 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9129 if (Level < AfterLegalizeDAG)
9135 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9136 if (LD->isIndexed())
9138 VT = LD->getMemoryVT();
9139 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9140 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9142 Ptr = LD->getBasePtr();
9143 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9144 if (ST->isIndexed())
9146 VT = ST->getMemoryVT();
9147 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9148 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9150 Ptr = ST->getBasePtr();
9156 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9157 // out. There is no reason to make this a preinc/predec.
9158 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9159 Ptr.getNode()->hasOneUse())
9162 // Ask the target to do addressing mode selection.
9165 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9166 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9169 // Backends without true r+i pre-indexed forms may need to pass a
9170 // constant base with a variable offset so that constant coercion
9171 // will work with the patterns in canonical form.
9172 bool Swapped = false;
9173 if (isa<ConstantSDNode>(BasePtr)) {
9174 std::swap(BasePtr, Offset);
9178 // Don't create a indexed load / store with zero offset.
9179 if (isNullConstant(Offset))
9182 // Try turning it into a pre-indexed load / store except when:
9183 // 1) The new base ptr is a frame index.
9184 // 2) If N is a store and the new base ptr is either the same as or is a
9185 // predecessor of the value being stored.
9186 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9187 // that would create a cycle.
9188 // 4) All uses are load / store ops that use it as old base ptr.
9190 // Check #1. Preinc'ing a frame index would require copying the stack pointer
9191 // (plus the implicit offset) to a register to preinc anyway.
9192 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9197 SDValue Val = cast<StoreSDNode>(N)->getValue();
9198 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9202 // If the offset is a constant, there may be other adds of constants that
9203 // can be folded with this one. We should do this to avoid having to keep
9204 // a copy of the original base pointer.
9205 SmallVector<SDNode *, 16> OtherUses;
9206 if (isa<ConstantSDNode>(Offset))
9207 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9208 UE = BasePtr.getNode()->use_end();
9210 SDUse &Use = UI.getUse();
9211 // Skip the use that is Ptr and uses of other results from BasePtr's
9212 // node (important for nodes that return multiple results).
9213 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9216 if (Use.getUser()->isPredecessorOf(N))
9219 if (Use.getUser()->getOpcode() != ISD::ADD &&
9220 Use.getUser()->getOpcode() != ISD::SUB) {
9225 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9226 if (!isa<ConstantSDNode>(Op1)) {
9231 // FIXME: In some cases, we can be smarter about this.
9232 if (Op1.getValueType() != Offset.getValueType()) {
9237 OtherUses.push_back(Use.getUser());
9241 std::swap(BasePtr, Offset);
9243 // Now check for #3 and #4.
9244 bool RealUse = false;
9246 // Caches for hasPredecessorHelper
9247 SmallPtrSet<const SDNode *, 32> Visited;
9248 SmallVector<const SDNode *, 16> Worklist;
9250 for (SDNode *Use : Ptr.getNode()->uses()) {
9253 if (N->hasPredecessorHelper(Use, Visited, Worklist))
9256 // If Ptr may be folded in addressing mode of other use, then it's
9257 // not profitable to do this transformation.
9258 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9267 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9268 BasePtr, Offset, AM);
9270 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9271 BasePtr, Offset, AM);
9274 DEBUG(dbgs() << "\nReplacing.4 ";
9276 dbgs() << "\nWith: ";
9277 Result.getNode()->dump(&DAG);
9279 WorklistRemover DeadNodes(*this);
9281 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9282 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9284 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9287 // Finally, since the node is now dead, remove it from the graph.
9288 deleteAndRecombine(N);
9291 std::swap(BasePtr, Offset);
9293 // Replace other uses of BasePtr that can be updated to use Ptr
9294 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9295 unsigned OffsetIdx = 1;
9296 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9298 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9299 BasePtr.getNode() && "Expected BasePtr operand");
9301 // We need to replace ptr0 in the following expression:
9302 // x0 * offset0 + y0 * ptr0 = t0
9304 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9306 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9307 // indexed load/store and the expresion that needs to be re-written.
9309 // Therefore, we have:
9310 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9312 ConstantSDNode *CN =
9313 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9315 APInt Offset0 = CN->getAPIntValue();
9316 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9318 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9319 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9320 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9321 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9323 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9325 APInt CNV = Offset0;
9326 if (X0 < 0) CNV = -CNV;
9327 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9328 else CNV = CNV - Offset1;
9330 SDLoc DL(OtherUses[i]);
9332 // We can now generate the new expression.
9333 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9334 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9336 SDValue NewUse = DAG.getNode(Opcode,
9338 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9339 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9340 deleteAndRecombine(OtherUses[i]);
9343 // Replace the uses of Ptr with uses of the updated base value.
9344 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9345 deleteAndRecombine(Ptr.getNode());
9350 /// Try to combine a load/store with a add/sub of the base pointer node into a
9351 /// post-indexed load/store. The transformation folded the add/subtract into the
9352 /// new indexed load/store effectively and all of its uses are redirected to the
9354 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9355 if (Level < AfterLegalizeDAG)
9361 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9362 if (LD->isIndexed())
9364 VT = LD->getMemoryVT();
9365 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9366 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9368 Ptr = LD->getBasePtr();
9369 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9370 if (ST->isIndexed())
9372 VT = ST->getMemoryVT();
9373 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9374 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9376 Ptr = ST->getBasePtr();
9382 if (Ptr.getNode()->hasOneUse())
9385 for (SDNode *Op : Ptr.getNode()->uses()) {
9387 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9392 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9393 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9394 // Don't create a indexed load / store with zero offset.
9395 if (isNullConstant(Offset))
9398 // Try turning it into a post-indexed load / store except when
9399 // 1) All uses are load / store ops that use it as base ptr (and
9400 // it may be folded as addressing mmode).
9401 // 2) Op must be independent of N, i.e. Op is neither a predecessor
9402 // nor a successor of N. Otherwise, if Op is folded that would
9405 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9409 bool TryNext = false;
9410 for (SDNode *Use : BasePtr.getNode()->uses()) {
9411 if (Use == Ptr.getNode())
9414 // If all the uses are load / store addresses, then don't do the
9416 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9417 bool RealUse = false;
9418 for (SDNode *UseUse : Use->uses()) {
9419 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9434 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9435 SDValue Result = isLoad
9436 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9437 BasePtr, Offset, AM)
9438 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9439 BasePtr, Offset, AM);
9442 DEBUG(dbgs() << "\nReplacing.5 ";
9444 dbgs() << "\nWith: ";
9445 Result.getNode()->dump(&DAG);
9447 WorklistRemover DeadNodes(*this);
9449 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9450 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9452 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9455 // Finally, since the node is now dead, remove it from the graph.
9456 deleteAndRecombine(N);
9458 // Replace the uses of Use with uses of the updated base value.
9459 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9460 Result.getValue(isLoad ? 1 : 0));
9461 deleteAndRecombine(Op);
9470 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9471 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9472 ISD::MemIndexedMode AM = LD->getAddressingMode();
9473 assert(AM != ISD::UNINDEXED);
9474 SDValue BP = LD->getOperand(1);
9475 SDValue Inc = LD->getOperand(2);
9477 // Some backends use TargetConstants for load offsets, but don't expect
9478 // TargetConstants in general ADD nodes. We can convert these constants into
9479 // regular Constants (if the constant is not opaque).
9480 assert((Inc.getOpcode() != ISD::TargetConstant ||
9481 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9482 "Cannot split out indexing using opaque target constants");
9483 if (Inc.getOpcode() == ISD::TargetConstant) {
9484 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9485 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9486 ConstInc->getValueType(0));
9490 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9491 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9494 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9495 LoadSDNode *LD = cast<LoadSDNode>(N);
9496 SDValue Chain = LD->getChain();
9497 SDValue Ptr = LD->getBasePtr();
9499 // If load is not volatile and there are no uses of the loaded value (and
9500 // the updated indexed value in case of indexed loads), change uses of the
9501 // chain value into uses of the chain input (i.e. delete the dead load).
9502 if (!LD->isVolatile()) {
9503 if (N->getValueType(1) == MVT::Other) {
9505 if (!N->hasAnyUseOfValue(0)) {
9506 // It's not safe to use the two value CombineTo variant here. e.g.
9507 // v1, chain2 = load chain1, loc
9508 // v2, chain3 = load chain2, loc
9510 // Now we replace use of chain2 with chain1. This makes the second load
9511 // isomorphic to the one we are deleting, and thus makes this load live.
9512 DEBUG(dbgs() << "\nReplacing.6 ";
9514 dbgs() << "\nWith chain: ";
9515 Chain.getNode()->dump(&DAG);
9517 WorklistRemover DeadNodes(*this);
9518 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9521 deleteAndRecombine(N);
9523 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9527 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9529 // If this load has an opaque TargetConstant offset, then we cannot split
9530 // the indexing into an add/sub directly (that TargetConstant may not be
9531 // valid for a different type of node, and we cannot convert an opaque
9532 // target constant into a regular constant).
9533 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9534 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9536 if (!N->hasAnyUseOfValue(0) &&
9537 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9538 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9540 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9541 Index = SplitIndexingFromLoad(LD);
9542 // Try to fold the base pointer arithmetic into subsequent loads and
9544 AddUsersToWorklist(N);
9546 Index = DAG.getUNDEF(N->getValueType(1));
9547 DEBUG(dbgs() << "\nReplacing.7 ";
9549 dbgs() << "\nWith: ";
9550 Undef.getNode()->dump(&DAG);
9551 dbgs() << " and 2 other values\n");
9552 WorklistRemover DeadNodes(*this);
9553 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9554 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9555 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9556 deleteAndRecombine(N);
9557 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9562 // If this load is directly stored, replace the load value with the stored
9564 // TODO: Handle store large -> read small portion.
9565 // TODO: Handle TRUNCSTORE/LOADEXT
9566 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9567 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9568 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9569 if (PrevST->getBasePtr() == Ptr &&
9570 PrevST->getValue().getValueType() == N->getValueType(0))
9571 return CombineTo(N, Chain.getOperand(1), Chain);
9575 // Try to infer better alignment information than the load already has.
9576 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9577 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9578 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9580 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9581 LD->getValueType(0),
9582 Chain, Ptr, LD->getPointerInfo(),
9584 LD->isVolatile(), LD->isNonTemporal(),
9585 LD->isInvariant(), Align, LD->getAAInfo());
9586 if (NewLoad.getNode() != N)
9587 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9592 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9593 : DAG.getSubtarget().useAA();
9595 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9596 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9599 if (UseAA && LD->isUnindexed()) {
9600 // Walk up chain skipping non-aliasing memory nodes.
9601 SDValue BetterChain = FindBetterChain(N, Chain);
9603 // If there is a better chain.
9604 if (Chain != BetterChain) {
9607 // Replace the chain to void dependency.
9608 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9609 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9610 BetterChain, Ptr, LD->getMemOperand());
9612 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9613 LD->getValueType(0),
9614 BetterChain, Ptr, LD->getMemoryVT(),
9615 LD->getMemOperand());
9618 // Create token factor to keep old chain connected.
9619 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9620 MVT::Other, Chain, ReplLoad.getValue(1));
9622 // Make sure the new and old chains are cleaned up.
9623 AddToWorklist(Token.getNode());
9625 // Replace uses with load result and token factor. Don't add users
9627 return CombineTo(N, ReplLoad.getValue(0), Token, false);
9631 // Try transforming N to an indexed load.
9632 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9633 return SDValue(N, 0);
9635 // Try to slice up N to more direct loads if the slices are mapped to
9636 // different register banks or pairing can take place.
9638 return SDValue(N, 0);
9644 /// \brief Helper structure used to slice a load in smaller loads.
9645 /// Basically a slice is obtained from the following sequence:
9646 /// Origin = load Ty1, Base
9647 /// Shift = srl Ty1 Origin, CstTy Amount
9648 /// Inst = trunc Shift to Ty2
9650 /// Then, it will be rewriten into:
9651 /// Slice = load SliceTy, Base + SliceOffset
9652 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9654 /// SliceTy is deduced from the number of bits that are actually used to
9656 struct LoadedSlice {
9657 /// \brief Helper structure used to compute the cost of a slice.
9659 /// Are we optimizing for code size.
9664 unsigned CrossRegisterBanksCopies;
9668 Cost(bool ForCodeSize = false)
9669 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9670 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9672 /// \brief Get the cost of one isolated slice.
9673 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9674 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9675 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9676 EVT TruncType = LS.Inst->getValueType(0);
9677 EVT LoadedType = LS.getLoadedType();
9678 if (TruncType != LoadedType &&
9679 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9683 /// \brief Account for slicing gain in the current cost.
9684 /// Slicing provide a few gains like removing a shift or a
9685 /// truncate. This method allows to grow the cost of the original
9686 /// load with the gain from this slice.
9687 void addSliceGain(const LoadedSlice &LS) {
9688 // Each slice saves a truncate.
9689 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9690 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9691 LS.Inst->getOperand(0).getValueType()))
9693 // If there is a shift amount, this slice gets rid of it.
9696 // If this slice can merge a cross register bank copy, account for it.
9697 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9698 ++CrossRegisterBanksCopies;
9701 Cost &operator+=(const Cost &RHS) {
9703 Truncates += RHS.Truncates;
9704 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9710 bool operator==(const Cost &RHS) const {
9711 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9712 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9713 ZExts == RHS.ZExts && Shift == RHS.Shift;
9716 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9718 bool operator<(const Cost &RHS) const {
9719 // Assume cross register banks copies are as expensive as loads.
9720 // FIXME: Do we want some more target hooks?
9721 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9722 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9723 // Unless we are optimizing for code size, consider the
9724 // expensive operation first.
9725 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9726 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9727 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9728 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9731 bool operator>(const Cost &RHS) const { return RHS < *this; }
9733 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9735 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9737 // The last instruction that represent the slice. This should be a
9738 // truncate instruction.
9740 // The original load instruction.
9742 // The right shift amount in bits from the original load.
9744 // The DAG from which Origin came from.
9745 // This is used to get some contextual information about legal types, etc.
9748 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9749 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9750 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9752 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9753 /// \return Result is \p BitWidth and has used bits set to 1 and
9754 /// not used bits set to 0.
9755 APInt getUsedBits() const {
9756 // Reproduce the trunc(lshr) sequence:
9757 // - Start from the truncated value.
9758 // - Zero extend to the desired bit width.
9760 assert(Origin && "No original load to compare against.");
9761 unsigned BitWidth = Origin->getValueSizeInBits(0);
9762 assert(Inst && "This slice is not bound to an instruction");
9763 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9764 "Extracted slice is bigger than the whole type!");
9765 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9766 UsedBits.setAllBits();
9767 UsedBits = UsedBits.zext(BitWidth);
9772 /// \brief Get the size of the slice to be loaded in bytes.
9773 unsigned getLoadedSize() const {
9774 unsigned SliceSize = getUsedBits().countPopulation();
9775 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9776 return SliceSize / 8;
9779 /// \brief Get the type that will be loaded for this slice.
9780 /// Note: This may not be the final type for the slice.
9781 EVT getLoadedType() const {
9782 assert(DAG && "Missing context");
9783 LLVMContext &Ctxt = *DAG->getContext();
9784 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9787 /// \brief Get the alignment of the load used for this slice.
9788 unsigned getAlignment() const {
9789 unsigned Alignment = Origin->getAlignment();
9790 unsigned Offset = getOffsetFromBase();
9792 Alignment = MinAlign(Alignment, Alignment + Offset);
9796 /// \brief Check if this slice can be rewritten with legal operations.
9797 bool isLegal() const {
9798 // An invalid slice is not legal.
9799 if (!Origin || !Inst || !DAG)
9802 // Offsets are for indexed load only, we do not handle that.
9803 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9806 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9808 // Check that the type is legal.
9809 EVT SliceType = getLoadedType();
9810 if (!TLI.isTypeLegal(SliceType))
9813 // Check that the load is legal for this type.
9814 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9817 // Check that the offset can be computed.
9818 // 1. Check its type.
9819 EVT PtrType = Origin->getBasePtr().getValueType();
9820 if (PtrType == MVT::Untyped || PtrType.isExtended())
9823 // 2. Check that it fits in the immediate.
9824 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9827 // 3. Check that the computation is legal.
9828 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9831 // Check that the zext is legal if it needs one.
9832 EVT TruncateType = Inst->getValueType(0);
9833 if (TruncateType != SliceType &&
9834 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9840 /// \brief Get the offset in bytes of this slice in the original chunk of
9842 /// \pre DAG != nullptr.
9843 uint64_t getOffsetFromBase() const {
9844 assert(DAG && "Missing context.");
9846 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9847 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9848 uint64_t Offset = Shift / 8;
9849 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9850 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9851 "The size of the original loaded type is not a multiple of a"
9853 // If Offset is bigger than TySizeInBytes, it means we are loading all
9854 // zeros. This should have been optimized before in the process.
9855 assert(TySizeInBytes > Offset &&
9856 "Invalid shift amount for given loaded size");
9858 Offset = TySizeInBytes - Offset - getLoadedSize();
9862 /// \brief Generate the sequence of instructions to load the slice
9863 /// represented by this object and redirect the uses of this slice to
9864 /// this new sequence of instructions.
9865 /// \pre this->Inst && this->Origin are valid Instructions and this
9866 /// object passed the legal check: LoadedSlice::isLegal returned true.
9867 /// \return The last instruction of the sequence used to load the slice.
9868 SDValue loadSlice() const {
9869 assert(Inst && Origin && "Unable to replace a non-existing slice.");
9870 const SDValue &OldBaseAddr = Origin->getBasePtr();
9871 SDValue BaseAddr = OldBaseAddr;
9872 // Get the offset in that chunk of bytes w.r.t. the endianess.
9873 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9874 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9876 // BaseAddr = BaseAddr + Offset.
9877 EVT ArithType = BaseAddr.getValueType();
9879 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9880 DAG->getConstant(Offset, DL, ArithType));
9883 // Create the type of the loaded slice according to its size.
9884 EVT SliceType = getLoadedType();
9886 // Create the load for the slice.
9887 SDValue LastInst = DAG->getLoad(
9888 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9889 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9890 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9891 // If the final type is not the same as the loaded type, this means that
9892 // we have to pad with zero. Create a zero extend for that.
9893 EVT FinalType = Inst->getValueType(0);
9894 if (SliceType != FinalType)
9896 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9900 /// \brief Check if this slice can be merged with an expensive cross register
9901 /// bank copy. E.g.,
9903 /// f = bitcast i32 i to float
9904 bool canMergeExpensiveCrossRegisterBankCopy() const {
9905 if (!Inst || !Inst->hasOneUse())
9907 SDNode *Use = *Inst->use_begin();
9908 if (Use->getOpcode() != ISD::BITCAST)
9910 assert(DAG && "Missing context");
9911 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9912 EVT ResVT = Use->getValueType(0);
9913 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9914 const TargetRegisterClass *ArgRC =
9915 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9916 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9919 // At this point, we know that we perform a cross-register-bank copy.
9920 // Check if it is expensive.
9921 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9922 // Assume bitcasts are cheap, unless both register classes do not
9923 // explicitly share a common sub class.
9924 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9927 // Check if it will be merged with the load.
9928 // 1. Check the alignment constraint.
9929 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9930 ResVT.getTypeForEVT(*DAG->getContext()));
9932 if (RequiredAlignment > getAlignment())
9935 // 2. Check that the load is a legal operation for that type.
9936 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9939 // 3. Check that we do not have a zext in the way.
9940 if (Inst->getValueType(0) != getLoadedType())
9948 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9949 /// \p UsedBits looks like 0..0 1..1 0..0.
9950 static bool areUsedBitsDense(const APInt &UsedBits) {
9951 // If all the bits are one, this is dense!
9952 if (UsedBits.isAllOnesValue())
9955 // Get rid of the unused bits on the right.
9956 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9957 // Get rid of the unused bits on the left.
9958 if (NarrowedUsedBits.countLeadingZeros())
9959 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9960 // Check that the chunk of bits is completely used.
9961 return NarrowedUsedBits.isAllOnesValue();
9964 /// \brief Check whether or not \p First and \p Second are next to each other
9965 /// in memory. This means that there is no hole between the bits loaded
9966 /// by \p First and the bits loaded by \p Second.
9967 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9968 const LoadedSlice &Second) {
9969 assert(First.Origin == Second.Origin && First.Origin &&
9970 "Unable to match different memory origins.");
9971 APInt UsedBits = First.getUsedBits();
9972 assert((UsedBits & Second.getUsedBits()) == 0 &&
9973 "Slices are not supposed to overlap.");
9974 UsedBits |= Second.getUsedBits();
9975 return areUsedBitsDense(UsedBits);
9978 /// \brief Adjust the \p GlobalLSCost according to the target
9979 /// paring capabilities and the layout of the slices.
9980 /// \pre \p GlobalLSCost should account for at least as many loads as
9981 /// there is in the slices in \p LoadedSlices.
9982 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9983 LoadedSlice::Cost &GlobalLSCost) {
9984 unsigned NumberOfSlices = LoadedSlices.size();
9985 // If there is less than 2 elements, no pairing is possible.
9986 if (NumberOfSlices < 2)
9989 // Sort the slices so that elements that are likely to be next to each
9990 // other in memory are next to each other in the list.
9991 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9992 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9993 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9994 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9996 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9997 // First (resp. Second) is the first (resp. Second) potentially candidate
9998 // to be placed in a paired load.
9999 const LoadedSlice *First = nullptr;
10000 const LoadedSlice *Second = nullptr;
10001 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10002 // Set the beginning of the pair.
10005 Second = &LoadedSlices[CurrSlice];
10007 // If First is NULL, it means we start a new pair.
10008 // Get to the next slice.
10012 EVT LoadedType = First->getLoadedType();
10014 // If the types of the slices are different, we cannot pair them.
10015 if (LoadedType != Second->getLoadedType())
10018 // Check if the target supplies paired loads for this type.
10019 unsigned RequiredAlignment = 0;
10020 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10021 // move to the next pair, this type is hopeless.
10025 // Check if we meet the alignment requirement.
10026 if (RequiredAlignment > First->getAlignment())
10029 // Check that both loads are next to each other in memory.
10030 if (!areSlicesNextToEachOther(*First, *Second))
10033 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10034 --GlobalLSCost.Loads;
10035 // Move to the next pair.
10040 /// \brief Check the profitability of all involved LoadedSlice.
10041 /// Currently, it is considered profitable if there is exactly two
10042 /// involved slices (1) which are (2) next to each other in memory, and
10043 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10045 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10046 /// the elements themselves.
10048 /// FIXME: When the cost model will be mature enough, we can relax
10049 /// constraints (1) and (2).
10050 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10051 const APInt &UsedBits, bool ForCodeSize) {
10052 unsigned NumberOfSlices = LoadedSlices.size();
10053 if (StressLoadSlicing)
10054 return NumberOfSlices > 1;
10057 if (NumberOfSlices != 2)
10061 if (!areUsedBitsDense(UsedBits))
10065 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10066 // The original code has one big load.
10067 OrigCost.Loads = 1;
10068 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10069 const LoadedSlice &LS = LoadedSlices[CurrSlice];
10070 // Accumulate the cost of all the slices.
10071 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10072 GlobalSlicingCost += SliceCost;
10074 // Account as cost in the original configuration the gain obtained
10075 // with the current slices.
10076 OrigCost.addSliceGain(LS);
10079 // If the target supports paired load, adjust the cost accordingly.
10080 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10081 return OrigCost > GlobalSlicingCost;
10084 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10085 /// operations, split it in the various pieces being extracted.
10087 /// This sort of thing is introduced by SROA.
10088 /// This slicing takes care not to insert overlapping loads.
10089 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10090 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10091 if (Level < AfterLegalizeDAG)
10094 LoadSDNode *LD = cast<LoadSDNode>(N);
10095 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10096 !LD->getValueType(0).isInteger())
10099 // Keep track of already used bits to detect overlapping values.
10100 // In that case, we will just abort the transformation.
10101 APInt UsedBits(LD->getValueSizeInBits(0), 0);
10103 SmallVector<LoadedSlice, 4> LoadedSlices;
10105 // Check if this load is used as several smaller chunks of bits.
10106 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10107 // of computation for each trunc.
10108 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10109 UI != UIEnd; ++UI) {
10110 // Skip the uses of the chain.
10111 if (UI.getUse().getResNo() != 0)
10114 SDNode *User = *UI;
10115 unsigned Shift = 0;
10117 // Check if this is a trunc(lshr).
10118 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10119 isa<ConstantSDNode>(User->getOperand(1))) {
10120 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10121 User = *User->use_begin();
10124 // At this point, User is a Truncate, iff we encountered, trunc or
10126 if (User->getOpcode() != ISD::TRUNCATE)
10129 // The width of the type must be a power of 2 and greater than 8-bits.
10130 // Otherwise the load cannot be represented in LLVM IR.
10131 // Moreover, if we shifted with a non-8-bits multiple, the slice
10132 // will be across several bytes. We do not support that.
10133 unsigned Width = User->getValueSizeInBits(0);
10134 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10137 // Build the slice for this chain of computations.
10138 LoadedSlice LS(User, LD, Shift, &DAG);
10139 APInt CurrentUsedBits = LS.getUsedBits();
10141 // Check if this slice overlaps with another.
10142 if ((CurrentUsedBits & UsedBits) != 0)
10144 // Update the bits used globally.
10145 UsedBits |= CurrentUsedBits;
10147 // Check if the new slice would be legal.
10151 // Record the slice.
10152 LoadedSlices.push_back(LS);
10155 // Abort slicing if it does not seem to be profitable.
10156 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10161 // Rewrite each chain to use an independent load.
10162 // By construction, each chain can be represented by a unique load.
10164 // Prepare the argument for the new token factor for all the slices.
10165 SmallVector<SDValue, 8> ArgChains;
10166 for (SmallVectorImpl<LoadedSlice>::const_iterator
10167 LSIt = LoadedSlices.begin(),
10168 LSItEnd = LoadedSlices.end();
10169 LSIt != LSItEnd; ++LSIt) {
10170 SDValue SliceInst = LSIt->loadSlice();
10171 CombineTo(LSIt->Inst, SliceInst, true);
10172 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10173 SliceInst = SliceInst.getOperand(0);
10174 assert(SliceInst->getOpcode() == ISD::LOAD &&
10175 "It takes more than a zext to get to the loaded slice!!");
10176 ArgChains.push_back(SliceInst.getValue(1));
10179 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10181 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10185 /// Check to see if V is (and load (ptr), imm), where the load is having
10186 /// specific bytes cleared out. If so, return the byte size being masked out
10187 /// and the shift amount.
10188 static std::pair<unsigned, unsigned>
10189 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10190 std::pair<unsigned, unsigned> Result(0, 0);
10192 // Check for the structure we're looking for.
10193 if (V->getOpcode() != ISD::AND ||
10194 !isa<ConstantSDNode>(V->getOperand(1)) ||
10195 !ISD::isNormalLoad(V->getOperand(0).getNode()))
10198 // Check the chain and pointer.
10199 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10200 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
10202 // The store should be chained directly to the load or be an operand of a
10204 if (LD == Chain.getNode())
10206 else if (Chain->getOpcode() != ISD::TokenFactor)
10207 return Result; // Fail.
10210 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
10211 if (Chain->getOperand(i).getNode() == LD) {
10215 if (!isOk) return Result;
10218 // This only handles simple types.
10219 if (V.getValueType() != MVT::i16 &&
10220 V.getValueType() != MVT::i32 &&
10221 V.getValueType() != MVT::i64)
10224 // Check the constant mask. Invert it so that the bits being masked out are
10225 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
10226 // follow the sign bit for uniformity.
10227 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10228 unsigned NotMaskLZ = countLeadingZeros(NotMask);
10229 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
10230 unsigned NotMaskTZ = countTrailingZeros(NotMask);
10231 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
10232 if (NotMaskLZ == 64) return Result; // All zero mask.
10234 // See if we have a continuous run of bits. If so, we have 0*1+0*
10235 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10238 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10239 if (V.getValueType() != MVT::i64 && NotMaskLZ)
10240 NotMaskLZ -= 64-V.getValueSizeInBits();
10242 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10243 switch (MaskedBytes) {
10247 default: return Result; // All one mask, or 5-byte mask.
10250 // Verify that the first bit starts at a multiple of mask so that the access
10251 // is aligned the same as the access width.
10252 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10254 Result.first = MaskedBytes;
10255 Result.second = NotMaskTZ/8;
10260 /// Check to see if IVal is something that provides a value as specified by
10261 /// MaskInfo. If so, replace the specified store with a narrower store of
10262 /// truncated IVal.
10264 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10265 SDValue IVal, StoreSDNode *St,
10267 unsigned NumBytes = MaskInfo.first;
10268 unsigned ByteShift = MaskInfo.second;
10269 SelectionDAG &DAG = DC->getDAG();
10271 // Check to see if IVal is all zeros in the part being masked in by the 'or'
10272 // that uses this. If not, this is not a replacement.
10273 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10274 ByteShift*8, (ByteShift+NumBytes)*8);
10275 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10277 // Check that it is legal on the target to do this. It is legal if the new
10278 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10280 MVT VT = MVT::getIntegerVT(NumBytes*8);
10281 if (!DC->isTypeLegal(VT))
10284 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
10285 // shifted by ByteShift and truncated down to NumBytes.
10288 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10289 DAG.getConstant(ByteShift*8, DL,
10290 DC->getShiftAmountTy(IVal.getValueType())));
10293 // Figure out the offset for the store and the alignment of the access.
10295 unsigned NewAlign = St->getAlignment();
10297 if (DAG.getTargetLoweringInfo().isLittleEndian())
10298 StOffset = ByteShift;
10300 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10302 SDValue Ptr = St->getBasePtr();
10305 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10306 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10307 NewAlign = MinAlign(NewAlign, StOffset);
10310 // Truncate down to the new size.
10311 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10314 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10315 St->getPointerInfo().getWithOffset(StOffset),
10316 false, false, NewAlign).getNode();
10320 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10321 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10322 /// narrowing the load and store if it would end up being a win for performance
10324 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10325 StoreSDNode *ST = cast<StoreSDNode>(N);
10326 if (ST->isVolatile())
10329 SDValue Chain = ST->getChain();
10330 SDValue Value = ST->getValue();
10331 SDValue Ptr = ST->getBasePtr();
10332 EVT VT = Value.getValueType();
10334 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10337 unsigned Opc = Value.getOpcode();
10339 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10340 // is a byte mask indicating a consecutive number of bytes, check to see if
10341 // Y is known to provide just those bytes. If so, we try to replace the
10342 // load + replace + store sequence with a single (narrower) store, which makes
10344 if (Opc == ISD::OR) {
10345 std::pair<unsigned, unsigned> MaskedLoad;
10346 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10347 if (MaskedLoad.first)
10348 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10349 Value.getOperand(1), ST,this))
10350 return SDValue(NewST, 0);
10352 // Or is commutative, so try swapping X and Y.
10353 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10354 if (MaskedLoad.first)
10355 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10356 Value.getOperand(0), ST,this))
10357 return SDValue(NewST, 0);
10360 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10361 Value.getOperand(1).getOpcode() != ISD::Constant)
10364 SDValue N0 = Value.getOperand(0);
10365 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10366 Chain == SDValue(N0.getNode(), 1)) {
10367 LoadSDNode *LD = cast<LoadSDNode>(N0);
10368 if (LD->getBasePtr() != Ptr ||
10369 LD->getPointerInfo().getAddrSpace() !=
10370 ST->getPointerInfo().getAddrSpace())
10373 // Find the type to narrow it the load / op / store to.
10374 SDValue N1 = Value.getOperand(1);
10375 unsigned BitWidth = N1.getValueSizeInBits();
10376 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10377 if (Opc == ISD::AND)
10378 Imm ^= APInt::getAllOnesValue(BitWidth);
10379 if (Imm == 0 || Imm.isAllOnesValue())
10381 unsigned ShAmt = Imm.countTrailingZeros();
10382 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10383 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10384 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10385 // The narrowing should be profitable, the load/store operation should be
10386 // legal (or custom) and the store size should be equal to the NewVT width.
10387 while (NewBW < BitWidth &&
10388 (NewVT.getStoreSizeInBits() != NewBW ||
10389 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10390 !TLI.isNarrowingProfitable(VT, NewVT))) {
10391 NewBW = NextPowerOf2(NewBW);
10392 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10394 if (NewBW >= BitWidth)
10397 // If the lsb changed does not start at the type bitwidth boundary,
10398 // start at the previous one.
10400 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10401 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10402 std::min(BitWidth, ShAmt + NewBW));
10403 if ((Imm & Mask) == Imm) {
10404 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10405 if (Opc == ISD::AND)
10406 NewImm ^= APInt::getAllOnesValue(NewBW);
10407 uint64_t PtrOff = ShAmt / 8;
10408 // For big endian targets, we need to adjust the offset to the pointer to
10409 // load the correct bytes.
10410 if (TLI.isBigEndian())
10411 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10413 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10414 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10415 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
10418 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10419 Ptr.getValueType(), Ptr,
10420 DAG.getConstant(PtrOff, SDLoc(LD),
10421 Ptr.getValueType()));
10422 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10423 LD->getChain(), NewPtr,
10424 LD->getPointerInfo().getWithOffset(PtrOff),
10425 LD->isVolatile(), LD->isNonTemporal(),
10426 LD->isInvariant(), NewAlign,
10428 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10429 DAG.getConstant(NewImm, SDLoc(Value),
10431 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10433 ST->getPointerInfo().getWithOffset(PtrOff),
10434 false, false, NewAlign);
10436 AddToWorklist(NewPtr.getNode());
10437 AddToWorklist(NewLD.getNode());
10438 AddToWorklist(NewVal.getNode());
10439 WorklistRemover DeadNodes(*this);
10440 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10449 /// For a given floating point load / store pair, if the load value isn't used
10450 /// by any other operations, then consider transforming the pair to integer
10451 /// load / store operations if the target deems the transformation profitable.
10452 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10453 StoreSDNode *ST = cast<StoreSDNode>(N);
10454 SDValue Chain = ST->getChain();
10455 SDValue Value = ST->getValue();
10456 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10457 Value.hasOneUse() &&
10458 Chain == SDValue(Value.getNode(), 1)) {
10459 LoadSDNode *LD = cast<LoadSDNode>(Value);
10460 EVT VT = LD->getMemoryVT();
10461 if (!VT.isFloatingPoint() ||
10462 VT != ST->getMemoryVT() ||
10463 LD->isNonTemporal() ||
10464 ST->isNonTemporal() ||
10465 LD->getPointerInfo().getAddrSpace() != 0 ||
10466 ST->getPointerInfo().getAddrSpace() != 0)
10469 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10470 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10471 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10472 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10473 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10476 unsigned LDAlign = LD->getAlignment();
10477 unsigned STAlign = ST->getAlignment();
10478 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10479 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
10480 if (LDAlign < ABIAlign || STAlign < ABIAlign)
10483 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10484 LD->getChain(), LD->getBasePtr(),
10485 LD->getPointerInfo(),
10486 false, false, false, LDAlign);
10488 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10489 NewLD, ST->getBasePtr(),
10490 ST->getPointerInfo(),
10491 false, false, STAlign);
10493 AddToWorklist(NewLD.getNode());
10494 AddToWorklist(NewST.getNode());
10495 WorklistRemover DeadNodes(*this);
10496 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10505 /// Helper struct to parse and store a memory address as base + index + offset.
10506 /// We ignore sign extensions when it is safe to do so.
10507 /// The following two expressions are not equivalent. To differentiate we need
10508 /// to store whether there was a sign extension involved in the index
10510 /// (load (i64 add (i64 copyfromreg %c)
10511 /// (i64 signextend (add (i8 load %index)
10515 /// (load (i64 add (i64 copyfromreg %c)
10516 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
10518 struct BaseIndexOffset {
10522 bool IsIndexSignExt;
10524 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10526 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10527 bool IsIndexSignExt) :
10528 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10530 bool equalBaseIndex(const BaseIndexOffset &Other) {
10531 return Other.Base == Base && Other.Index == Index &&
10532 Other.IsIndexSignExt == IsIndexSignExt;
10535 /// Parses tree in Ptr for base, index, offset addresses.
10536 static BaseIndexOffset match(SDValue Ptr) {
10537 bool IsIndexSignExt = false;
10539 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10540 // instruction, then it could be just the BASE or everything else we don't
10541 // know how to handle. Just use Ptr as BASE and give up.
10542 if (Ptr->getOpcode() != ISD::ADD)
10543 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10545 // We know that we have at least an ADD instruction. Try to pattern match
10546 // the simple case of BASE + OFFSET.
10547 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10548 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10549 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10553 // Inside a loop the current BASE pointer is calculated using an ADD and a
10554 // MUL instruction. In this case Ptr is the actual BASE pointer.
10555 // (i64 add (i64 %array_ptr)
10556 // (i64 mul (i64 %induction_var)
10557 // (i64 %element_size)))
10558 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10559 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10561 // Look at Base + Index + Offset cases.
10562 SDValue Base = Ptr->getOperand(0);
10563 SDValue IndexOffset = Ptr->getOperand(1);
10565 // Skip signextends.
10566 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10567 IndexOffset = IndexOffset->getOperand(0);
10568 IsIndexSignExt = true;
10571 // Either the case of Base + Index (no offset) or something else.
10572 if (IndexOffset->getOpcode() != ISD::ADD)
10573 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10575 // Now we have the case of Base + Index + offset.
10576 SDValue Index = IndexOffset->getOperand(0);
10577 SDValue Offset = IndexOffset->getOperand(1);
10579 if (!isa<ConstantSDNode>(Offset))
10580 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10582 // Ignore signextends.
10583 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10584 Index = Index->getOperand(0);
10585 IsIndexSignExt = true;
10586 } else IsIndexSignExt = false;
10588 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10589 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10594 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10595 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10596 unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10597 // Make sure we have something to merge.
10601 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10602 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10603 unsigned LatestNodeUsed = 0;
10605 for (unsigned i=0; i < NumElem; ++i) {
10606 // Find a chain for the new wide-store operand. Notice that some
10607 // of the store nodes that we found may not be selected for inclusion
10608 // in the wide store. The chain we use needs to be the chain of the
10609 // latest store node which is *used* and replaced by the wide store.
10610 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10611 LatestNodeUsed = i;
10614 // The latest Node in the DAG.
10615 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10616 SDLoc DL(StoreNodes[0].MemNode);
10620 // Find a legal type for the vector store.
10621 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10622 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10623 if (IsConstantSrc) {
10624 // A vector store with a constant source implies that the constant is
10625 // zero; we only handle merging stores of constant zeros because the zero
10626 // can be materialized without a load.
10627 // It may be beneficial to loosen this restriction to allow non-zero
10629 StoredVal = DAG.getConstant(0, DL, Ty);
10631 SmallVector<SDValue, 8> Ops;
10632 for (unsigned i = 0; i < NumElem ; ++i) {
10633 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10634 SDValue Val = St->getValue();
10635 // All of the operands of a BUILD_VECTOR must have the same type.
10636 if (Val.getValueType() != MemVT)
10638 Ops.push_back(Val);
10641 // Build the extracted vector elements back into a vector.
10642 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10645 // We should always use a vector store when merging extracted vector
10646 // elements, so this path implies a store of constants.
10647 assert(IsConstantSrc && "Merged vector elements should use vector store");
10649 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10650 APInt StoreInt(StoreBW, 0);
10652 // Construct a single integer constant which is made of the smaller
10653 // constant inputs.
10654 bool IsLE = TLI.isLittleEndian();
10655 for (unsigned i = 0; i < NumElem ; ++i) {
10656 unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10657 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10658 SDValue Val = St->getValue();
10659 StoreInt <<= ElementSizeBytes*8;
10660 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10661 StoreInt |= C->getAPIntValue().zext(StoreBW);
10662 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10663 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10665 llvm_unreachable("Invalid constant element type");
10669 // Create the new Load and Store operations.
10670 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10671 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10674 SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10675 FirstInChain->getBasePtr(),
10676 FirstInChain->getPointerInfo(),
10678 FirstInChain->getAlignment());
10680 // Replace the last store with the new store
10681 CombineTo(LatestOp, NewStore);
10682 // Erase all other stores.
10683 for (unsigned i = 0; i < NumElem ; ++i) {
10684 if (StoreNodes[i].MemNode == LatestOp)
10686 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10687 // ReplaceAllUsesWith will replace all uses that existed when it was
10688 // called, but graph optimizations may cause new ones to appear. For
10689 // example, the case in pr14333 looks like
10691 // St's chain -> St -> another store -> X
10693 // And the only difference from St to the other store is the chain.
10694 // When we change it's chain to be St's chain they become identical,
10695 // get CSEed and the net result is that X is now a use of St.
10696 // Since we know that St is redundant, just iterate.
10697 while (!St->use_empty())
10698 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10699 deleteAndRecombine(St);
10705 static bool allowableAlignment(const SelectionDAG &DAG,
10706 const TargetLowering &TLI, EVT EVTTy,
10707 unsigned AS, unsigned Align) {
10708 if (TLI.allowsMisalignedMemoryAccesses(EVTTy, AS, Align))
10711 Type *Ty = EVTTy.getTypeForEVT(*DAG.getContext());
10712 unsigned ABIAlignment = TLI.getDataLayout()->getPrefTypeAlignment(Ty);
10713 return (Align >= ABIAlignment);
10716 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10717 if (OptLevel == CodeGenOpt::None)
10720 EVT MemVT = St->getMemoryVT();
10721 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10722 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10723 Attribute::NoImplicitFloat);
10725 // This function cannot currently deal with non-byte-sized memory sizes.
10726 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10729 // Don't merge vectors into wider inputs.
10730 if (MemVT.isVector() || !MemVT.isSimple())
10733 // Perform an early exit check. Do not bother looking at stored values that
10734 // are not constants, loads, or extracted vector elements.
10735 SDValue StoredVal = St->getValue();
10736 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10737 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10738 isa<ConstantFPSDNode>(StoredVal);
10739 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10741 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10744 // Only look at ends of store sequences.
10745 SDValue Chain = SDValue(St, 0);
10746 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10749 // This holds the base pointer, index, and the offset in bytes from the base
10751 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10753 // We must have a base and an offset.
10754 if (!BasePtr.Base.getNode())
10757 // Do not handle stores to undef base pointers.
10758 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10761 // Save the LoadSDNodes that we find in the chain.
10762 // We need to make sure that these nodes do not interfere with
10763 // any of the store nodes.
10764 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10766 // Save the StoreSDNodes that we find in the chain.
10767 SmallVector<MemOpLink, 8> StoreNodes;
10769 // Walk up the chain and look for nodes with offsets from the same
10770 // base pointer. Stop when reaching an instruction with a different kind
10771 // or instruction which has a different base pointer.
10773 StoreSDNode *Index = St;
10775 // If the chain has more than one use, then we can't reorder the mem ops.
10776 if (Index != St && !SDValue(Index, 0)->hasOneUse())
10779 // Find the base pointer and offset for this memory node.
10780 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10782 // Check that the base pointer is the same as the original one.
10783 if (!Ptr.equalBaseIndex(BasePtr))
10786 // The memory operands must not be volatile.
10787 if (Index->isVolatile() || Index->isIndexed())
10791 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10792 if (St->isTruncatingStore())
10795 // The stored memory type must be the same.
10796 if (Index->getMemoryVT() != MemVT)
10799 // We found a potential memory operand to merge.
10800 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10802 // Find the next memory operand in the chain. If the next operand in the
10803 // chain is a store then move up and continue the scan with the next
10804 // memory operand. If the next operand is a load save it and use alias
10805 // information to check if it interferes with anything.
10806 SDNode *NextInChain = Index->getChain().getNode();
10808 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10809 // We found a store node. Use it for the next iteration.
10812 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10813 if (Ldn->isVolatile()) {
10818 // Save the load node for later. Continue the scan.
10819 AliasLoadNodes.push_back(Ldn);
10820 NextInChain = Ldn->getChain().getNode();
10829 // Check if there is anything to merge.
10830 if (StoreNodes.size() < 2)
10833 // Sort the memory operands according to their distance from the base pointer.
10834 std::sort(StoreNodes.begin(), StoreNodes.end(),
10835 [](MemOpLink LHS, MemOpLink RHS) {
10836 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10837 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10838 LHS.SequenceNum > RHS.SequenceNum);
10841 // Scan the memory operations on the chain and find the first non-consecutive
10842 // store memory address.
10843 unsigned LastConsecutiveStore = 0;
10844 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10845 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10847 // Check that the addresses are consecutive starting from the second
10848 // element in the list of stores.
10850 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10851 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10855 bool Alias = false;
10856 // Check if this store interferes with any of the loads that we found.
10857 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10858 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10862 // We found a load that alias with this store. Stop the sequence.
10866 // Mark this node as useful.
10867 LastConsecutiveStore = i;
10870 // The node with the lowest store address.
10871 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10872 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
10873 unsigned FirstStoreAlign = FirstInChain->getAlignment();
10875 // Store the constants into memory as one consecutive store.
10876 if (IsConstantSrc) {
10877 unsigned LastLegalType = 0;
10878 unsigned LastLegalVectorType = 0;
10879 bool NonZero = false;
10880 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10881 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10882 SDValue StoredVal = St->getValue();
10884 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10885 NonZero |= !C->isNullValue();
10886 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10887 NonZero |= !C->getConstantFPValue()->isNullValue();
10893 // Find a legal type for the constant store.
10894 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10895 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10896 if (TLI.isTypeLegal(StoreTy) &&
10897 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS,
10898 FirstStoreAlign)) {
10899 LastLegalType = i+1;
10900 // Or check whether a truncstore is legal.
10901 } else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10902 TargetLowering::TypePromoteInteger) {
10903 EVT LegalizedStoredValueTy =
10904 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10905 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10906 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
10907 FirstStoreAlign)) {
10908 LastLegalType = i + 1;
10912 // Find a legal type for the vector store.
10913 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10914 if (TLI.isTypeLegal(Ty) &&
10915 allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign)) {
10916 LastLegalVectorType = i + 1;
10921 // We only use vectors if the constant is known to be zero or the target
10922 // allows it and the function is not marked with the noimplicitfloat
10925 LastLegalVectorType = 0;
10926 } else if (NonZero && !TLI.storeOfVectorConstantIsCheap(MemVT,
10927 LastLegalVectorType,
10929 LastLegalVectorType = 0;
10932 // Check if we found a legal integer type to store.
10933 if (LastLegalType == 0 && LastLegalVectorType == 0)
10936 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10937 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10939 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10943 // When extracting multiple vector elements, try to store them
10944 // in one vector store rather than a sequence of scalar stores.
10945 if (IsExtractVecEltSrc) {
10946 unsigned NumElem = 0;
10947 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10948 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10949 SDValue StoredVal = St->getValue();
10950 // This restriction could be loosened.
10951 // Bail out if any stored values are not elements extracted from a vector.
10952 // It should be possible to handle mixed sources, but load sources need
10953 // more careful handling (see the block of code below that handles
10954 // consecutive loads).
10955 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10958 // Find a legal type for the vector store.
10959 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10960 if (TLI.isTypeLegal(Ty) &&
10961 allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign))
10965 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10969 // Below we handle the case of multiple consecutive stores that
10970 // come from multiple consecutive loads. We merge them into a single
10971 // wide load and a single wide store.
10973 // Look for load nodes which are used by the stored values.
10974 SmallVector<MemOpLink, 8> LoadNodes;
10976 // Find acceptable loads. Loads need to have the same chain (token factor),
10977 // must not be zext, volatile, indexed, and they must be consecutive.
10978 BaseIndexOffset LdBasePtr;
10979 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10980 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10981 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10984 // Loads must only have one use.
10985 if (!Ld->hasNUsesOfValue(1, 0))
10988 // The memory operands must not be volatile.
10989 if (Ld->isVolatile() || Ld->isIndexed())
10992 // We do not accept ext loads.
10993 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10996 // The stored memory type must be the same.
10997 if (Ld->getMemoryVT() != MemVT)
11000 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11001 // If this is not the first ptr that we check.
11002 if (LdBasePtr.Base.getNode()) {
11003 // The base ptr must be the same.
11004 if (!LdPtr.equalBaseIndex(LdBasePtr))
11007 // Check that all other base pointers are the same as this one.
11011 // We found a potential memory operand to merge.
11012 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11015 if (LoadNodes.size() < 2)
11018 // If we have load/store pair instructions and we only have two values,
11020 unsigned RequiredAlignment;
11021 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11022 St->getAlignment() >= RequiredAlignment)
11025 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11026 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11027 unsigned FirstLoadAlign = FirstLoad->getAlignment();
11029 // Scan the memory operations on the chain and find the first non-consecutive
11030 // load memory address. These variables hold the index in the store node
11032 unsigned LastConsecutiveLoad = 0;
11033 // This variable refers to the size and not index in the array.
11034 unsigned LastLegalVectorType = 0;
11035 unsigned LastLegalIntegerType = 0;
11036 StartAddress = LoadNodes[0].OffsetFromBase;
11037 SDValue FirstChain = FirstLoad->getChain();
11038 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11039 // All loads much share the same chain.
11040 if (LoadNodes[i].MemNode->getChain() != FirstChain)
11043 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11044 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11046 LastConsecutiveLoad = i;
11048 // Find a legal type for the vector store.
11049 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
11050 if (TLI.isTypeLegal(StoreTy) &&
11051 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
11052 allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign)) {
11053 LastLegalVectorType = i + 1;
11056 // Find a legal type for the integer store.
11057 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
11058 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
11059 if (TLI.isTypeLegal(StoreTy) &&
11060 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
11061 allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign))
11062 LastLegalIntegerType = i + 1;
11063 // Or check whether a truncstore and extload is legal.
11064 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
11065 TargetLowering::TypePromoteInteger) {
11066 EVT LegalizedStoredValueTy =
11067 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
11068 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11069 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11070 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11071 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11072 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
11073 FirstStoreAlign) &&
11074 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstLoadAS,
11076 LastLegalIntegerType = i+1;
11080 // Only use vector types if the vector type is larger than the integer type.
11081 // If they are the same, use integers.
11082 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11083 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11085 // We add +1 here because the LastXXX variables refer to location while
11086 // the NumElem refers to array/index size.
11087 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11088 NumElem = std::min(LastLegalType, NumElem);
11093 // The latest Node in the DAG.
11094 unsigned LatestNodeUsed = 0;
11095 for (unsigned i=1; i<NumElem; ++i) {
11096 // Find a chain for the new wide-store operand. Notice that some
11097 // of the store nodes that we found may not be selected for inclusion
11098 // in the wide store. The chain we use needs to be the chain of the
11099 // latest store node which is *used* and replaced by the wide store.
11100 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11101 LatestNodeUsed = i;
11104 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11106 // Find if it is better to use vectors or integers to load and store
11110 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
11112 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
11113 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
11116 SDLoc LoadDL(LoadNodes[0].MemNode);
11117 SDLoc StoreDL(StoreNodes[0].MemNode);
11119 SDValue NewLoad = DAG.getLoad(
11120 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11121 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11123 SDValue NewStore = DAG.getStore(
11124 LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11125 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11127 // Replace one of the loads with the new load.
11128 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11129 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11130 SDValue(NewLoad.getNode(), 1));
11132 // Remove the rest of the load chains.
11133 for (unsigned i = 1; i < NumElem ; ++i) {
11134 // Replace all chain users of the old load nodes with the chain of the new
11136 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11137 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11140 // Replace the last store with the new store.
11141 CombineTo(LatestOp, NewStore);
11142 // Erase all other stores.
11143 for (unsigned i = 0; i < NumElem ; ++i) {
11144 // Remove all Store nodes.
11145 if (StoreNodes[i].MemNode == LatestOp)
11147 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11148 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11149 deleteAndRecombine(St);
11155 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11156 StoreSDNode *ST = cast<StoreSDNode>(N);
11157 SDValue Chain = ST->getChain();
11158 SDValue Value = ST->getValue();
11159 SDValue Ptr = ST->getBasePtr();
11161 // If this is a store of a bit convert, store the input value if the
11162 // resultant store does not need a higher alignment than the original.
11163 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11164 ST->isUnindexed()) {
11165 unsigned OrigAlign = ST->getAlignment();
11166 EVT SVT = Value.getOperand(0).getValueType();
11167 unsigned Align = TLI.getDataLayout()->
11168 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
11169 if (Align <= OrigAlign &&
11170 ((!LegalOperations && !ST->isVolatile()) ||
11171 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11172 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11173 Ptr, ST->getPointerInfo(), ST->isVolatile(),
11174 ST->isNonTemporal(), OrigAlign,
11178 // Turn 'store undef, Ptr' -> nothing.
11179 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11182 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11183 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11184 // NOTE: If the original store is volatile, this transform must not increase
11185 // the number of stores. For example, on x86-32 an f64 can be stored in one
11186 // processor operation but an i64 (which is not legal) requires two. So the
11187 // transform should not be done in this case.
11188 if (Value.getOpcode() != ISD::TargetConstantFP) {
11190 switch (CFP->getSimpleValueType(0).SimpleTy) {
11191 default: llvm_unreachable("Unknown FP type");
11192 case MVT::f16: // We don't do this for these yet.
11198 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11199 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11201 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11202 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11204 return DAG.getStore(Chain, SDLoc(N), Tmp,
11205 Ptr, ST->getMemOperand());
11209 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11210 !ST->isVolatile()) ||
11211 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11213 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11214 getZExtValue(), SDLoc(CFP), MVT::i64);
11215 return DAG.getStore(Chain, SDLoc(N), Tmp,
11216 Ptr, ST->getMemOperand());
11219 if (!ST->isVolatile() &&
11220 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11221 // Many FP stores are not made apparent until after legalize, e.g. for
11222 // argument passing. Since this is so common, custom legalize the
11223 // 64-bit integer store into two 32-bit stores.
11224 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11225 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11226 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11227 if (TLI.isBigEndian()) std::swap(Lo, Hi);
11229 unsigned Alignment = ST->getAlignment();
11230 bool isVolatile = ST->isVolatile();
11231 bool isNonTemporal = ST->isNonTemporal();
11232 AAMDNodes AAInfo = ST->getAAInfo();
11236 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11237 Ptr, ST->getPointerInfo(),
11238 isVolatile, isNonTemporal,
11239 ST->getAlignment(), AAInfo);
11240 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11241 DAG.getConstant(4, DL, Ptr.getValueType()));
11242 Alignment = MinAlign(Alignment, 4U);
11243 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11244 Ptr, ST->getPointerInfo().getWithOffset(4),
11245 isVolatile, isNonTemporal,
11246 Alignment, AAInfo);
11247 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11256 // Try to infer better alignment information than the store already has.
11257 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11258 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11259 if (Align > ST->getAlignment()) {
11261 DAG.getTruncStore(Chain, SDLoc(N), Value,
11262 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11263 ST->isVolatile(), ST->isNonTemporal(), Align,
11265 if (NewStore.getNode() != N)
11266 return CombineTo(ST, NewStore, true);
11271 // Try transforming a pair floating point load / store ops to integer
11272 // load / store ops.
11273 SDValue NewST = TransformFPLoadStorePair(N);
11274 if (NewST.getNode())
11277 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11278 : DAG.getSubtarget().useAA();
11280 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11281 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11284 if (UseAA && ST->isUnindexed()) {
11285 // Walk up chain skipping non-aliasing memory nodes.
11286 SDValue BetterChain = FindBetterChain(N, Chain);
11288 // If there is a better chain.
11289 if (Chain != BetterChain) {
11292 // Replace the chain to avoid dependency.
11293 if (ST->isTruncatingStore()) {
11294 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11295 ST->getMemoryVT(), ST->getMemOperand());
11297 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11298 ST->getMemOperand());
11301 // Create token to keep both nodes around.
11302 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11303 MVT::Other, Chain, ReplStore);
11305 // Make sure the new and old chains are cleaned up.
11306 AddToWorklist(Token.getNode());
11308 // Don't add users to work list.
11309 return CombineTo(N, Token, false);
11313 // Try transforming N to an indexed store.
11314 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11315 return SDValue(N, 0);
11317 // FIXME: is there such a thing as a truncating indexed store?
11318 if (ST->isTruncatingStore() && ST->isUnindexed() &&
11319 Value.getValueType().isInteger()) {
11320 // See if we can simplify the input to this truncstore with knowledge that
11321 // only the low bits are being used. For example:
11322 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
11324 GetDemandedBits(Value,
11325 APInt::getLowBitsSet(
11326 Value.getValueType().getScalarType().getSizeInBits(),
11327 ST->getMemoryVT().getScalarType().getSizeInBits()));
11328 AddToWorklist(Value.getNode());
11329 if (Shorter.getNode())
11330 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11331 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11333 // Otherwise, see if we can simplify the operation with
11334 // SimplifyDemandedBits, which only works if the value has a single use.
11335 if (SimplifyDemandedBits(Value,
11336 APInt::getLowBitsSet(
11337 Value.getValueType().getScalarType().getSizeInBits(),
11338 ST->getMemoryVT().getScalarType().getSizeInBits())))
11339 return SDValue(N, 0);
11342 // If this is a load followed by a store to the same location, then the store
11344 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11345 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11346 ST->isUnindexed() && !ST->isVolatile() &&
11347 // There can't be any side effects between the load and store, such as
11348 // a call or store.
11349 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11350 // The store is dead, remove it.
11355 // If this is a store followed by a store with the same value to the same
11356 // location, then the store is dead/noop.
11357 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11358 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11359 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11360 ST1->isUnindexed() && !ST1->isVolatile()) {
11361 // The store is dead, remove it.
11366 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11367 // truncating store. We can do this even if this is already a truncstore.
11368 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11369 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11370 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11371 ST->getMemoryVT())) {
11372 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11373 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11376 // Only perform this optimization before the types are legal, because we
11377 // don't want to perform this optimization on every DAGCombine invocation.
11379 bool EverChanged = false;
11382 // There can be multiple store sequences on the same chain.
11383 // Keep trying to merge store sequences until we are unable to do so
11384 // or until we merge the last store on the chain.
11385 bool Changed = MergeConsecutiveStores(ST);
11386 EverChanged |= Changed;
11387 if (!Changed) break;
11388 } while (ST->getOpcode() != ISD::DELETED_NODE);
11391 return SDValue(N, 0);
11394 return ReduceLoadOpStoreWidth(N);
11397 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11398 SDValue InVec = N->getOperand(0);
11399 SDValue InVal = N->getOperand(1);
11400 SDValue EltNo = N->getOperand(2);
11403 // If the inserted element is an UNDEF, just use the input vector.
11404 if (InVal.getOpcode() == ISD::UNDEF)
11407 EVT VT = InVec.getValueType();
11409 // If we can't generate a legal BUILD_VECTOR, exit
11410 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11413 // Check that we know which element is being inserted
11414 if (!isa<ConstantSDNode>(EltNo))
11416 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11418 // Canonicalize insert_vector_elt dag nodes.
11420 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11421 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11423 // Do this only if the child insert_vector node has one use; also
11424 // do this only if indices are both constants and Idx1 < Idx0.
11425 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11426 && isa<ConstantSDNode>(InVec.getOperand(2))) {
11427 unsigned OtherElt =
11428 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11429 if (Elt < OtherElt) {
11431 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11432 InVec.getOperand(0), InVal, EltNo);
11433 AddToWorklist(NewOp.getNode());
11434 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11435 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11439 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11440 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
11441 // vector elements.
11442 SmallVector<SDValue, 8> Ops;
11443 // Do not combine these two vectors if the output vector will not replace
11444 // the input vector.
11445 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11446 Ops.append(InVec.getNode()->op_begin(),
11447 InVec.getNode()->op_end());
11448 } else if (InVec.getOpcode() == ISD::UNDEF) {
11449 unsigned NElts = VT.getVectorNumElements();
11450 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11455 // Insert the element
11456 if (Elt < Ops.size()) {
11457 // All the operands of BUILD_VECTOR must have the same type;
11458 // we enforce that here.
11459 EVT OpVT = Ops[0].getValueType();
11460 if (InVal.getValueType() != OpVT)
11461 InVal = OpVT.bitsGT(InVal.getValueType()) ?
11462 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11463 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11467 // Return the new vector
11468 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11471 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11472 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11473 EVT ResultVT = EVE->getValueType(0);
11474 EVT VecEltVT = InVecVT.getVectorElementType();
11475 unsigned Align = OriginalLoad->getAlignment();
11476 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11477 VecEltVT.getTypeForEVT(*DAG.getContext()));
11479 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11484 SDValue NewPtr = OriginalLoad->getBasePtr();
11486 EVT PtrType = NewPtr.getValueType();
11487 MachinePointerInfo MPI;
11489 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11490 int Elt = ConstEltNo->getZExtValue();
11491 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11492 Offset = DAG.getConstant(PtrOff, DL, PtrType);
11493 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11495 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11496 Offset = DAG.getNode(
11497 ISD::MUL, DL, PtrType, Offset,
11498 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11499 MPI = OriginalLoad->getPointerInfo();
11501 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11503 // The replacement we need to do here is a little tricky: we need to
11504 // replace an extractelement of a load with a load.
11505 // Use ReplaceAllUsesOfValuesWith to do the replacement.
11506 // Note that this replacement assumes that the extractvalue is the only
11507 // use of the load; that's okay because we don't want to perform this
11508 // transformation in other cases anyway.
11511 if (ResultVT.bitsGT(VecEltVT)) {
11512 // If the result type of vextract is wider than the load, then issue an
11513 // extending load instead.
11514 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11518 Load = DAG.getExtLoad(
11519 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11520 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11521 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11522 Chain = Load.getValue(1);
11524 Load = DAG.getLoad(
11525 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11526 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11527 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11528 Chain = Load.getValue(1);
11529 if (ResultVT.bitsLT(VecEltVT))
11530 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11532 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11534 WorklistRemover DeadNodes(*this);
11535 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11536 SDValue To[] = { Load, Chain };
11537 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11538 // Since we're explicitly calling ReplaceAllUses, add the new node to the
11539 // worklist explicitly as well.
11540 AddToWorklist(Load.getNode());
11541 AddUsersToWorklist(Load.getNode()); // Add users too
11542 // Make sure to revisit this node to clean it up; it will usually be dead.
11543 AddToWorklist(EVE);
11545 return SDValue(EVE, 0);
11548 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11549 // (vextract (scalar_to_vector val, 0) -> val
11550 SDValue InVec = N->getOperand(0);
11551 EVT VT = InVec.getValueType();
11552 EVT NVT = N->getValueType(0);
11554 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11555 // Check if the result type doesn't match the inserted element type. A
11556 // SCALAR_TO_VECTOR may truncate the inserted element and the
11557 // EXTRACT_VECTOR_ELT may widen the extracted vector.
11558 SDValue InOp = InVec.getOperand(0);
11559 if (InOp.getValueType() != NVT) {
11560 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11561 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11566 SDValue EltNo = N->getOperand(1);
11567 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11569 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11570 // We only perform this optimization before the op legalization phase because
11571 // we may introduce new vector instructions which are not backed by TD
11572 // patterns. For example on AVX, extracting elements from a wide vector
11573 // without using extract_subvector. However, if we can find an underlying
11574 // scalar value, then we can always use that.
11575 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11577 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11578 int NumElem = VT.getVectorNumElements();
11579 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11580 // Find the new index to extract from.
11581 int OrigElt = SVOp->getMaskElt(Elt);
11583 // Extracting an undef index is undef.
11585 return DAG.getUNDEF(NVT);
11587 // Select the right vector half to extract from.
11589 if (OrigElt < NumElem) {
11590 SVInVec = InVec->getOperand(0);
11592 SVInVec = InVec->getOperand(1);
11593 OrigElt -= NumElem;
11596 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11597 SDValue InOp = SVInVec.getOperand(OrigElt);
11598 if (InOp.getValueType() != NVT) {
11599 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11600 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11606 // FIXME: We should handle recursing on other vector shuffles and
11607 // scalar_to_vector here as well.
11609 if (!LegalOperations) {
11610 EVT IndexTy = TLI.getVectorIdxTy();
11611 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11612 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11616 bool BCNumEltsChanged = false;
11617 EVT ExtVT = VT.getVectorElementType();
11620 // If the result of load has to be truncated, then it's not necessarily
11622 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11625 if (InVec.getOpcode() == ISD::BITCAST) {
11626 // Don't duplicate a load with other uses.
11627 if (!InVec.hasOneUse())
11630 EVT BCVT = InVec.getOperand(0).getValueType();
11631 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11633 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11634 BCNumEltsChanged = true;
11635 InVec = InVec.getOperand(0);
11636 ExtVT = BCVT.getVectorElementType();
11639 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11640 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11641 ISD::isNormalLoad(InVec.getNode()) &&
11642 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11643 SDValue Index = N->getOperand(1);
11644 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11645 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11649 // Perform only after legalization to ensure build_vector / vector_shuffle
11650 // optimizations have already been done.
11651 if (!LegalOperations) return SDValue();
11653 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11654 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11655 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11658 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11660 LoadSDNode *LN0 = nullptr;
11661 const ShuffleVectorSDNode *SVN = nullptr;
11662 if (ISD::isNormalLoad(InVec.getNode())) {
11663 LN0 = cast<LoadSDNode>(InVec);
11664 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11665 InVec.getOperand(0).getValueType() == ExtVT &&
11666 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11667 // Don't duplicate a load with other uses.
11668 if (!InVec.hasOneUse())
11671 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11672 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11673 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11675 // (load $addr+1*size)
11677 // Don't duplicate a load with other uses.
11678 if (!InVec.hasOneUse())
11681 // If the bit convert changed the number of elements, it is unsafe
11682 // to examine the mask.
11683 if (BCNumEltsChanged)
11686 // Select the input vector, guarding against out of range extract vector.
11687 unsigned NumElems = VT.getVectorNumElements();
11688 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11689 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11691 if (InVec.getOpcode() == ISD::BITCAST) {
11692 // Don't duplicate a load with other uses.
11693 if (!InVec.hasOneUse())
11696 InVec = InVec.getOperand(0);
11698 if (ISD::isNormalLoad(InVec.getNode())) {
11699 LN0 = cast<LoadSDNode>(InVec);
11700 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11701 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11705 // Make sure we found a non-volatile load and the extractelement is
11707 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11710 // If Idx was -1 above, Elt is going to be -1, so just return undef.
11712 return DAG.getUNDEF(LVT);
11714 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11720 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11721 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11722 // We perform this optimization post type-legalization because
11723 // the type-legalizer often scalarizes integer-promoted vectors.
11724 // Performing this optimization before may create bit-casts which
11725 // will be type-legalized to complex code sequences.
11726 // We perform this optimization only before the operation legalizer because we
11727 // may introduce illegal operations.
11728 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11731 unsigned NumInScalars = N->getNumOperands();
11733 EVT VT = N->getValueType(0);
11735 // Check to see if this is a BUILD_VECTOR of a bunch of values
11736 // which come from any_extend or zero_extend nodes. If so, we can create
11737 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11738 // optimizations. We do not handle sign-extend because we can't fill the sign
11740 EVT SourceType = MVT::Other;
11741 bool AllAnyExt = true;
11743 for (unsigned i = 0; i != NumInScalars; ++i) {
11744 SDValue In = N->getOperand(i);
11745 // Ignore undef inputs.
11746 if (In.getOpcode() == ISD::UNDEF) continue;
11748 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
11749 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11751 // Abort if the element is not an extension.
11752 if (!ZeroExt && !AnyExt) {
11753 SourceType = MVT::Other;
11757 // The input is a ZeroExt or AnyExt. Check the original type.
11758 EVT InTy = In.getOperand(0).getValueType();
11760 // Check that all of the widened source types are the same.
11761 if (SourceType == MVT::Other)
11764 else if (InTy != SourceType) {
11765 // Multiple income types. Abort.
11766 SourceType = MVT::Other;
11770 // Check if all of the extends are ANY_EXTENDs.
11771 AllAnyExt &= AnyExt;
11774 // In order to have valid types, all of the inputs must be extended from the
11775 // same source type and all of the inputs must be any or zero extend.
11776 // Scalar sizes must be a power of two.
11777 EVT OutScalarTy = VT.getScalarType();
11778 bool ValidTypes = SourceType != MVT::Other &&
11779 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11780 isPowerOf2_32(SourceType.getSizeInBits());
11782 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11783 // turn into a single shuffle instruction.
11787 bool isLE = TLI.isLittleEndian();
11788 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11789 assert(ElemRatio > 1 && "Invalid element size ratio");
11790 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11791 DAG.getConstant(0, SDLoc(N), SourceType);
11793 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11794 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11796 // Populate the new build_vector
11797 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11798 SDValue Cast = N->getOperand(i);
11799 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11800 Cast.getOpcode() == ISD::ZERO_EXTEND ||
11801 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11803 if (Cast.getOpcode() == ISD::UNDEF)
11804 In = DAG.getUNDEF(SourceType);
11806 In = Cast->getOperand(0);
11807 unsigned Index = isLE ? (i * ElemRatio) :
11808 (i * ElemRatio + (ElemRatio - 1));
11810 assert(Index < Ops.size() && "Invalid index");
11814 // The type of the new BUILD_VECTOR node.
11815 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11816 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11817 "Invalid vector size");
11818 // Check if the new vector type is legal.
11819 if (!isTypeLegal(VecVT)) return SDValue();
11821 // Make the new BUILD_VECTOR.
11822 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11824 // The new BUILD_VECTOR node has the potential to be further optimized.
11825 AddToWorklist(BV.getNode());
11826 // Bitcast to the desired type.
11827 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11830 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11831 EVT VT = N->getValueType(0);
11833 unsigned NumInScalars = N->getNumOperands();
11836 EVT SrcVT = MVT::Other;
11837 unsigned Opcode = ISD::DELETED_NODE;
11838 unsigned NumDefs = 0;
11840 for (unsigned i = 0; i != NumInScalars; ++i) {
11841 SDValue In = N->getOperand(i);
11842 unsigned Opc = In.getOpcode();
11844 if (Opc == ISD::UNDEF)
11847 // If all scalar values are floats and converted from integers.
11848 if (Opcode == ISD::DELETED_NODE &&
11849 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11856 EVT InVT = In.getOperand(0).getValueType();
11858 // If all scalar values are typed differently, bail out. It's chosen to
11859 // simplify BUILD_VECTOR of integer types.
11860 if (SrcVT == MVT::Other)
11867 // If the vector has just one element defined, it's not worth to fold it into
11868 // a vectorized one.
11872 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11873 && "Should only handle conversion from integer to float.");
11874 assert(SrcVT != MVT::Other && "Cannot determine source type!");
11876 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11878 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11881 // Just because the floating-point vector type is legal does not necessarily
11882 // mean that the corresponding integer vector type is.
11883 if (!isTypeLegal(NVT))
11886 SmallVector<SDValue, 8> Opnds;
11887 for (unsigned i = 0; i != NumInScalars; ++i) {
11888 SDValue In = N->getOperand(i);
11890 if (In.getOpcode() == ISD::UNDEF)
11891 Opnds.push_back(DAG.getUNDEF(SrcVT));
11893 Opnds.push_back(In.getOperand(0));
11895 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11896 AddToWorklist(BV.getNode());
11898 return DAG.getNode(Opcode, dl, VT, BV);
11901 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11902 unsigned NumInScalars = N->getNumOperands();
11904 EVT VT = N->getValueType(0);
11906 // A vector built entirely of undefs is undef.
11907 if (ISD::allOperandsUndef(N))
11908 return DAG.getUNDEF(VT);
11910 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11913 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11916 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11917 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11918 // at most two distinct vectors, turn this into a shuffle node.
11920 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11921 if (!isTypeLegal(VT))
11924 // May only combine to shuffle after legalize if shuffle is legal.
11925 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11928 SDValue VecIn1, VecIn2;
11929 bool UsesZeroVector = false;
11930 for (unsigned i = 0; i != NumInScalars; ++i) {
11931 SDValue Op = N->getOperand(i);
11932 // Ignore undef inputs.
11933 if (Op.getOpcode() == ISD::UNDEF) continue;
11935 // See if we can combine this build_vector into a blend with a zero vector.
11936 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
11937 UsesZeroVector = true;
11941 // If this input is something other than a EXTRACT_VECTOR_ELT with a
11942 // constant index, bail out.
11943 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11944 !isa<ConstantSDNode>(Op.getOperand(1))) {
11945 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11949 // We allow up to two distinct input vectors.
11950 SDValue ExtractedFromVec = Op.getOperand(0);
11951 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11954 if (!VecIn1.getNode()) {
11955 VecIn1 = ExtractedFromVec;
11956 } else if (!VecIn2.getNode() && !UsesZeroVector) {
11957 VecIn2 = ExtractedFromVec;
11959 // Too many inputs.
11960 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11965 // If everything is good, we can make a shuffle operation.
11966 if (VecIn1.getNode()) {
11967 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11968 SmallVector<int, 8> Mask;
11969 for (unsigned i = 0; i != NumInScalars; ++i) {
11970 unsigned Opcode = N->getOperand(i).getOpcode();
11971 if (Opcode == ISD::UNDEF) {
11972 Mask.push_back(-1);
11976 // Operands can also be zero.
11977 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11978 assert(UsesZeroVector &&
11979 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11980 "Unexpected node found!");
11981 Mask.push_back(NumInScalars+i);
11985 // If extracting from the first vector, just use the index directly.
11986 SDValue Extract = N->getOperand(i);
11987 SDValue ExtVal = Extract.getOperand(1);
11988 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11989 if (Extract.getOperand(0) == VecIn1) {
11990 Mask.push_back(ExtIndex);
11994 // Otherwise, use InIdx + InputVecSize
11995 Mask.push_back(InNumElements + ExtIndex);
11998 // Avoid introducing illegal shuffles with zero.
11999 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12002 // We can't generate a shuffle node with mismatched input and output types.
12003 // Attempt to transform a single input vector to the correct type.
12004 if ((VT != VecIn1.getValueType())) {
12005 // If the input vector type has a different base type to the output
12006 // vector type, bail out.
12007 EVT VTElemType = VT.getVectorElementType();
12008 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12009 (VecIn2.getNode() &&
12010 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12013 // If the input vector is too small, widen it.
12014 // We only support widening of vectors which are half the size of the
12015 // output registers. For example XMM->YMM widening on X86 with AVX.
12016 EVT VecInT = VecIn1.getValueType();
12017 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12018 // If we only have one small input, widen it by adding undef values.
12019 if (!VecIn2.getNode())
12020 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12021 DAG.getUNDEF(VecIn1.getValueType()));
12022 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12023 // If we have two small inputs of the same type, try to concat them.
12024 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12025 VecIn2 = SDValue(nullptr, 0);
12028 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12029 // If the input vector is too large, try to split it.
12030 // We don't support having two input vectors that are too large.
12031 // If the zero vector was used, we can not split the vector,
12032 // since we'd need 3 inputs.
12033 if (UsesZeroVector || VecIn2.getNode())
12036 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12039 // Try to replace VecIn1 with two extract_subvectors
12040 // No need to update the masks, they should still be correct.
12041 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12042 DAG.getConstant(VT.getVectorNumElements(), dl, TLI.getVectorIdxTy()));
12043 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12044 DAG.getConstant(0, dl, TLI.getVectorIdxTy()));
12049 if (UsesZeroVector)
12050 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12051 DAG.getConstantFP(0.0, dl, VT);
12053 // If VecIn2 is unused then change it to undef.
12054 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12056 // Check that we were able to transform all incoming values to the same
12058 if (VecIn2.getValueType() != VecIn1.getValueType() ||
12059 VecIn1.getValueType() != VT)
12062 // Return the new VECTOR_SHUFFLE node.
12066 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12072 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12073 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12074 EVT OpVT = N->getOperand(0).getValueType();
12076 // If the operands are legal vectors, leave them alone.
12077 if (TLI.isTypeLegal(OpVT))
12081 EVT VT = N->getValueType(0);
12082 SmallVector<SDValue, 8> Ops;
12084 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12085 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12087 // Keep track of what we encounter.
12088 bool AnyInteger = false;
12089 bool AnyFP = false;
12090 for (const SDValue &Op : N->ops()) {
12091 if (ISD::BITCAST == Op.getOpcode() &&
12092 !Op.getOperand(0).getValueType().isVector())
12093 Ops.push_back(Op.getOperand(0));
12094 else if (ISD::UNDEF == Op.getOpcode())
12095 Ops.push_back(ScalarUndef);
12099 // Note whether we encounter an integer or floating point scalar.
12100 // If it's neither, bail out, it could be something weird like x86mmx.
12101 EVT LastOpVT = Ops.back().getValueType();
12102 if (LastOpVT.isFloatingPoint())
12104 else if (LastOpVT.isInteger())
12110 // If any of the operands is a floating point scalar bitcast to a vector,
12111 // use floating point types throughout, and bitcast everything.
12112 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12114 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12115 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12117 for (SDValue &Op : Ops) {
12118 if (Op.getValueType() == SVT)
12120 if (Op.getOpcode() == ISD::UNDEF)
12123 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12128 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12129 VT.getSizeInBits() / SVT.getSizeInBits());
12130 return DAG.getNode(ISD::BITCAST, DL, VT,
12131 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12134 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12135 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
12136 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
12137 // inputs come from at most two distinct vectors, turn this into a shuffle
12140 // If we only have one input vector, we don't need to do any concatenation.
12141 if (N->getNumOperands() == 1)
12142 return N->getOperand(0);
12144 // Check if all of the operands are undefs.
12145 EVT VT = N->getValueType(0);
12146 if (ISD::allOperandsUndef(N))
12147 return DAG.getUNDEF(VT);
12149 // Optimize concat_vectors where all but the first of the vectors are undef.
12150 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12151 return Op.getOpcode() == ISD::UNDEF;
12153 SDValue In = N->getOperand(0);
12154 assert(In.getValueType().isVector() && "Must concat vectors");
12156 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12157 if (In->getOpcode() == ISD::BITCAST &&
12158 !In->getOperand(0)->getValueType(0).isVector()) {
12159 SDValue Scalar = In->getOperand(0);
12161 // If the bitcast type isn't legal, it might be a trunc of a legal type;
12162 // look through the trunc so we can still do the transform:
12163 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12164 if (Scalar->getOpcode() == ISD::TRUNCATE &&
12165 !TLI.isTypeLegal(Scalar.getValueType()) &&
12166 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12167 Scalar = Scalar->getOperand(0);
12169 EVT SclTy = Scalar->getValueType(0);
12171 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12174 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12175 VT.getSizeInBits() / SclTy.getSizeInBits());
12176 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12179 SDLoc dl = SDLoc(N);
12180 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12181 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12185 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12186 // We have already tested above for an UNDEF only concatenation.
12187 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12188 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12189 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12190 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12192 bool AllBuildVectorsOrUndefs =
12193 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12194 if (AllBuildVectorsOrUndefs) {
12195 SmallVector<SDValue, 8> Opnds;
12196 EVT SVT = VT.getScalarType();
12199 if (!SVT.isFloatingPoint()) {
12200 // If BUILD_VECTOR are from built from integer, they may have different
12201 // operand types. Get the smallest type and truncate all operands to it.
12202 bool FoundMinVT = false;
12203 for (const SDValue &Op : N->ops())
12204 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12205 EVT OpSVT = Op.getOperand(0)->getValueType(0);
12206 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12209 assert(FoundMinVT && "Concat vector type mismatch");
12212 for (const SDValue &Op : N->ops()) {
12213 EVT OpVT = Op.getValueType();
12214 unsigned NumElts = OpVT.getVectorNumElements();
12216 if (ISD::UNDEF == Op.getOpcode())
12217 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12219 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12220 if (SVT.isFloatingPoint()) {
12221 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12222 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12224 for (unsigned i = 0; i != NumElts; ++i)
12226 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12231 assert(VT.getVectorNumElements() == Opnds.size() &&
12232 "Concat vector type mismatch");
12233 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12236 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12237 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12240 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12241 // nodes often generate nop CONCAT_VECTOR nodes.
12242 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12243 // place the incoming vectors at the exact same location.
12244 SDValue SingleSource = SDValue();
12245 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12247 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12248 SDValue Op = N->getOperand(i);
12250 if (Op.getOpcode() == ISD::UNDEF)
12253 // Check if this is the identity extract:
12254 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12257 // Find the single incoming vector for the extract_subvector.
12258 if (SingleSource.getNode()) {
12259 if (Op.getOperand(0) != SingleSource)
12262 SingleSource = Op.getOperand(0);
12264 // Check the source type is the same as the type of the result.
12265 // If not, this concat may extend the vector, so we can not
12266 // optimize it away.
12267 if (SingleSource.getValueType() != N->getValueType(0))
12271 unsigned IdentityIndex = i * PartNumElem;
12272 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12273 // The extract index must be constant.
12277 // Check that we are reading from the identity index.
12278 if (CS->getZExtValue() != IdentityIndex)
12282 if (SingleSource.getNode())
12283 return SingleSource;
12288 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12289 EVT NVT = N->getValueType(0);
12290 SDValue V = N->getOperand(0);
12292 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12294 // (extract_subvec (concat V1, V2, ...), i)
12297 // Only operand 0 is checked as 'concat' assumes all inputs of the same
12299 if (V->getOperand(0).getValueType() != NVT)
12301 unsigned Idx = N->getConstantOperandVal(1);
12302 unsigned NumElems = NVT.getVectorNumElements();
12303 assert((Idx % NumElems) == 0 &&
12304 "IDX in concat is not a multiple of the result vector length.");
12305 return V->getOperand(Idx / NumElems);
12309 if (V->getOpcode() == ISD::BITCAST)
12310 V = V.getOperand(0);
12312 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12314 // Handle only simple case where vector being inserted and vector
12315 // being extracted are of same type, and are half size of larger vectors.
12316 EVT BigVT = V->getOperand(0).getValueType();
12317 EVT SmallVT = V->getOperand(1).getValueType();
12318 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12321 // Only handle cases where both indexes are constants with the same type.
12322 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12323 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12325 if (InsIdx && ExtIdx &&
12326 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12327 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12329 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12331 // indices are equal or bit offsets are equal => V1
12332 // otherwise => (extract_subvec V1, ExtIdx)
12333 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12334 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12335 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12336 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12337 DAG.getNode(ISD::BITCAST, dl,
12338 N->getOperand(0).getValueType(),
12339 V->getOperand(0)), N->getOperand(1));
12346 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12347 SDValue V, SelectionDAG &DAG) {
12349 EVT VT = V.getValueType();
12351 switch (V.getOpcode()) {
12355 case ISD::CONCAT_VECTORS: {
12356 EVT OpVT = V->getOperand(0).getValueType();
12357 int OpSize = OpVT.getVectorNumElements();
12358 SmallBitVector OpUsedElements(OpSize, false);
12359 bool FoundSimplification = false;
12360 SmallVector<SDValue, 4> NewOps;
12361 NewOps.reserve(V->getNumOperands());
12362 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12363 SDValue Op = V->getOperand(i);
12364 bool OpUsed = false;
12365 for (int j = 0; j < OpSize; ++j)
12366 if (UsedElements[i * OpSize + j]) {
12367 OpUsedElements[j] = true;
12371 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12372 : DAG.getUNDEF(OpVT));
12373 FoundSimplification |= Op == NewOps.back();
12374 OpUsedElements.reset();
12376 if (FoundSimplification)
12377 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12381 case ISD::INSERT_SUBVECTOR: {
12382 SDValue BaseV = V->getOperand(0);
12383 SDValue SubV = V->getOperand(1);
12384 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12388 int SubSize = SubV.getValueType().getVectorNumElements();
12389 int Idx = IdxN->getZExtValue();
12390 bool SubVectorUsed = false;
12391 SmallBitVector SubUsedElements(SubSize, false);
12392 for (int i = 0; i < SubSize; ++i)
12393 if (UsedElements[i + Idx]) {
12394 SubVectorUsed = true;
12395 SubUsedElements[i] = true;
12396 UsedElements[i + Idx] = false;
12399 // Now recurse on both the base and sub vectors.
12400 SDValue SimplifiedSubV =
12402 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12403 : DAG.getUNDEF(SubV.getValueType());
12404 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12405 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12406 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12407 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12413 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12414 SDValue N1, SelectionDAG &DAG) {
12415 EVT VT = SVN->getValueType(0);
12416 int NumElts = VT.getVectorNumElements();
12417 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12418 for (int M : SVN->getMask())
12419 if (M >= 0 && M < NumElts)
12420 N0UsedElements[M] = true;
12421 else if (M >= NumElts)
12422 N1UsedElements[M - NumElts] = true;
12424 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12425 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12426 if (S0 == N0 && S1 == N1)
12429 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12432 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12433 // or turn a shuffle of a single concat into simpler shuffle then concat.
12434 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12435 EVT VT = N->getValueType(0);
12436 unsigned NumElts = VT.getVectorNumElements();
12438 SDValue N0 = N->getOperand(0);
12439 SDValue N1 = N->getOperand(1);
12440 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12442 SmallVector<SDValue, 4> Ops;
12443 EVT ConcatVT = N0.getOperand(0).getValueType();
12444 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12445 unsigned NumConcats = NumElts / NumElemsPerConcat;
12447 // Special case: shuffle(concat(A,B)) can be more efficiently represented
12448 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12449 // half vector elements.
12450 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12451 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12452 SVN->getMask().end(), [](int i) { return i == -1; })) {
12453 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12454 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12455 N1 = DAG.getUNDEF(ConcatVT);
12456 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12459 // Look at every vector that's inserted. We're looking for exact
12460 // subvector-sized copies from a concatenated vector
12461 for (unsigned I = 0; I != NumConcats; ++I) {
12462 // Make sure we're dealing with a copy.
12463 unsigned Begin = I * NumElemsPerConcat;
12464 bool AllUndef = true, NoUndef = true;
12465 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12466 if (SVN->getMaskElt(J) >= 0)
12473 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12476 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12477 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12480 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12481 if (FirstElt < N0.getNumOperands())
12482 Ops.push_back(N0.getOperand(FirstElt));
12484 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12486 } else if (AllUndef) {
12487 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12488 } else { // Mixed with general masks and undefs, can't do optimization.
12493 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12496 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12497 EVT VT = N->getValueType(0);
12498 unsigned NumElts = VT.getVectorNumElements();
12500 SDValue N0 = N->getOperand(0);
12501 SDValue N1 = N->getOperand(1);
12503 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12505 // Canonicalize shuffle undef, undef -> undef
12506 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12507 return DAG.getUNDEF(VT);
12509 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12511 // Canonicalize shuffle v, v -> v, undef
12513 SmallVector<int, 8> NewMask;
12514 for (unsigned i = 0; i != NumElts; ++i) {
12515 int Idx = SVN->getMaskElt(i);
12516 if (Idx >= (int)NumElts) Idx -= NumElts;
12517 NewMask.push_back(Idx);
12519 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12523 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
12524 if (N0.getOpcode() == ISD::UNDEF) {
12525 SmallVector<int, 8> NewMask;
12526 for (unsigned i = 0; i != NumElts; ++i) {
12527 int Idx = SVN->getMaskElt(i);
12529 if (Idx >= (int)NumElts)
12532 Idx = -1; // remove reference to lhs
12534 NewMask.push_back(Idx);
12536 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12540 // Remove references to rhs if it is undef
12541 if (N1.getOpcode() == ISD::UNDEF) {
12542 bool Changed = false;
12543 SmallVector<int, 8> NewMask;
12544 for (unsigned i = 0; i != NumElts; ++i) {
12545 int Idx = SVN->getMaskElt(i);
12546 if (Idx >= (int)NumElts) {
12550 NewMask.push_back(Idx);
12553 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12556 // If it is a splat, check if the argument vector is another splat or a
12558 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12559 SDNode *V = N0.getNode();
12561 // If this is a bit convert that changes the element type of the vector but
12562 // not the number of vector elements, look through it. Be careful not to
12563 // look though conversions that change things like v4f32 to v2f64.
12564 if (V->getOpcode() == ISD::BITCAST) {
12565 SDValue ConvInput = V->getOperand(0);
12566 if (ConvInput.getValueType().isVector() &&
12567 ConvInput.getValueType().getVectorNumElements() == NumElts)
12568 V = ConvInput.getNode();
12571 if (V->getOpcode() == ISD::BUILD_VECTOR) {
12572 assert(V->getNumOperands() == NumElts &&
12573 "BUILD_VECTOR has wrong number of operands");
12575 bool AllSame = true;
12576 for (unsigned i = 0; i != NumElts; ++i) {
12577 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12578 Base = V->getOperand(i);
12582 // Splat of <u, u, u, u>, return <u, u, u, u>
12583 if (!Base.getNode())
12585 for (unsigned i = 0; i != NumElts; ++i) {
12586 if (V->getOperand(i) != Base) {
12591 // Splat of <x, x, x, x>, return <x, x, x, x>
12595 // Canonicalize any other splat as a build_vector.
12596 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12597 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12598 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12599 V->getValueType(0), Ops);
12601 // We may have jumped through bitcasts, so the type of the
12602 // BUILD_VECTOR may not match the type of the shuffle.
12603 if (V->getValueType(0) != VT)
12604 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12609 // There are various patterns used to build up a vector from smaller vectors,
12610 // subvectors, or elements. Scan chains of these and replace unused insertions
12611 // or components with undef.
12612 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12615 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12616 Level < AfterLegalizeVectorOps &&
12617 (N1.getOpcode() == ISD::UNDEF ||
12618 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12619 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12620 SDValue V = partitionShuffleOfConcats(N, DAG);
12626 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12627 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12628 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12629 SmallVector<SDValue, 8> Ops;
12630 for (int M : SVN->getMask()) {
12631 SDValue Op = DAG.getUNDEF(VT.getScalarType());
12633 int Idx = M % NumElts;
12634 SDValue &S = (M < (int)NumElts ? N0 : N1);
12635 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12636 Op = S.getOperand(Idx);
12637 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12639 Op = S.getOperand(0);
12641 // Operand can't be combined - bail out.
12647 if (Ops.size() == VT.getVectorNumElements()) {
12648 // BUILD_VECTOR requires all inputs to be of the same type, find the
12649 // maximum type and extend them all.
12650 EVT SVT = VT.getScalarType();
12651 if (SVT.isInteger())
12652 for (SDValue &Op : Ops)
12653 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12654 if (SVT != VT.getScalarType())
12655 for (SDValue &Op : Ops)
12656 Op = TLI.isZExtFree(Op.getValueType(), SVT)
12657 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12658 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12659 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12663 // If this shuffle only has a single input that is a bitcasted shuffle,
12664 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12665 // back to their original types.
12666 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12667 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12668 TLI.isTypeLegal(VT)) {
12670 // Peek through the bitcast only if there is one user.
12672 while (BC0.getOpcode() == ISD::BITCAST) {
12673 if (!BC0.hasOneUse())
12675 BC0 = BC0.getOperand(0);
12678 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12680 return SmallVector<int, 8>(Mask.begin(), Mask.end());
12682 SmallVector<int, 8> NewMask;
12684 for (int s = 0; s != Scale; ++s)
12685 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12689 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12690 EVT SVT = VT.getScalarType();
12691 EVT InnerVT = BC0->getValueType(0);
12692 EVT InnerSVT = InnerVT.getScalarType();
12694 // Determine which shuffle works with the smaller scalar type.
12695 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12696 EVT ScaleSVT = ScaleVT.getScalarType();
12698 if (TLI.isTypeLegal(ScaleVT) &&
12699 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12700 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12702 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12703 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12705 // Scale the shuffle masks to the smaller scalar type.
12706 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12707 SmallVector<int, 8> InnerMask =
12708 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12709 SmallVector<int, 8> OuterMask =
12710 ScaleShuffleMask(SVN->getMask(), OuterScale);
12712 // Merge the shuffle masks.
12713 SmallVector<int, 8> NewMask;
12714 for (int M : OuterMask)
12715 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12717 // Test for shuffle mask legality over both commutations.
12718 SDValue SV0 = BC0->getOperand(0);
12719 SDValue SV1 = BC0->getOperand(1);
12720 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12722 std::swap(SV0, SV1);
12723 ShuffleVectorSDNode::commuteMask(NewMask);
12724 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12728 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12729 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12730 return DAG.getNode(
12731 ISD::BITCAST, SDLoc(N), VT,
12732 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12738 // Canonicalize shuffles according to rules:
12739 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12740 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12741 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12742 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12743 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12744 TLI.isTypeLegal(VT)) {
12745 // The incoming shuffle must be of the same type as the result of the
12746 // current shuffle.
12747 assert(N1->getOperand(0).getValueType() == VT &&
12748 "Shuffle types don't match");
12750 SDValue SV0 = N1->getOperand(0);
12751 SDValue SV1 = N1->getOperand(1);
12752 bool HasSameOp0 = N0 == SV0;
12753 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12754 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12755 // Commute the operands of this shuffle so that next rule
12757 return DAG.getCommutedVectorShuffle(*SVN);
12760 // Try to fold according to rules:
12761 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12762 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12763 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12764 // Don't try to fold shuffles with illegal type.
12765 // Only fold if this shuffle is the only user of the other shuffle.
12766 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12767 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12768 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12770 // The incoming shuffle must be of the same type as the result of the
12771 // current shuffle.
12772 assert(OtherSV->getOperand(0).getValueType() == VT &&
12773 "Shuffle types don't match");
12776 SmallVector<int, 4> Mask;
12777 // Compute the combined shuffle mask for a shuffle with SV0 as the first
12778 // operand, and SV1 as the second operand.
12779 for (unsigned i = 0; i != NumElts; ++i) {
12780 int Idx = SVN->getMaskElt(i);
12782 // Propagate Undef.
12783 Mask.push_back(Idx);
12787 SDValue CurrentVec;
12788 if (Idx < (int)NumElts) {
12789 // This shuffle index refers to the inner shuffle N0. Lookup the inner
12790 // shuffle mask to identify which vector is actually referenced.
12791 Idx = OtherSV->getMaskElt(Idx);
12793 // Propagate Undef.
12794 Mask.push_back(Idx);
12798 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12799 : OtherSV->getOperand(1);
12801 // This shuffle index references an element within N1.
12805 // Simple case where 'CurrentVec' is UNDEF.
12806 if (CurrentVec.getOpcode() == ISD::UNDEF) {
12807 Mask.push_back(-1);
12811 // Canonicalize the shuffle index. We don't know yet if CurrentVec
12812 // will be the first or second operand of the combined shuffle.
12813 Idx = Idx % NumElts;
12814 if (!SV0.getNode() || SV0 == CurrentVec) {
12815 // Ok. CurrentVec is the left hand side.
12816 // Update the mask accordingly.
12818 Mask.push_back(Idx);
12822 // Bail out if we cannot convert the shuffle pair into a single shuffle.
12823 if (SV1.getNode() && SV1 != CurrentVec)
12826 // Ok. CurrentVec is the right hand side.
12827 // Update the mask accordingly.
12829 Mask.push_back(Idx + NumElts);
12832 // Check if all indices in Mask are Undef. In case, propagate Undef.
12833 bool isUndefMask = true;
12834 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12835 isUndefMask &= Mask[i] < 0;
12838 return DAG.getUNDEF(VT);
12840 if (!SV0.getNode())
12841 SV0 = DAG.getUNDEF(VT);
12842 if (!SV1.getNode())
12843 SV1 = DAG.getUNDEF(VT);
12845 // Avoid introducing shuffles with illegal mask.
12846 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12847 ShuffleVectorSDNode::commuteMask(Mask);
12849 if (!TLI.isShuffleMaskLegal(Mask, VT))
12852 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12853 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12854 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12855 std::swap(SV0, SV1);
12858 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12859 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12860 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12861 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12867 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12868 SDValue InVal = N->getOperand(0);
12869 EVT VT = N->getValueType(0);
12871 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12872 // with a VECTOR_SHUFFLE.
12873 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12874 SDValue InVec = InVal->getOperand(0);
12875 SDValue EltNo = InVal->getOperand(1);
12877 // FIXME: We could support implicit truncation if the shuffle can be
12878 // scaled to a smaller vector scalar type.
12879 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12880 if (C0 && VT == InVec.getValueType() &&
12881 VT.getScalarType() == InVal.getValueType()) {
12882 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12883 int Elt = C0->getZExtValue();
12886 if (TLI.isShuffleMaskLegal(NewMask, VT))
12887 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12895 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12896 SDValue N0 = N->getOperand(0);
12897 SDValue N2 = N->getOperand(2);
12899 // If the input vector is a concatenation, and the insert replaces
12900 // one of the halves, we can optimize into a single concat_vectors.
12901 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12902 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12903 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12904 EVT VT = N->getValueType(0);
12906 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12907 // (concat_vectors Z, Y)
12909 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12910 N->getOperand(1), N0.getOperand(1));
12912 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12913 // (concat_vectors X, Z)
12914 if (InsIdx == VT.getVectorNumElements()/2)
12915 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12916 N0.getOperand(0), N->getOperand(1));
12922 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12923 SDValue N0 = N->getOperand(0);
12925 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12926 if (N0->getOpcode() == ISD::FP16_TO_FP)
12927 return N0->getOperand(0);
12932 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12933 /// with the destination vector and a zero vector.
12934 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12935 /// vector_shuffle V, Zero, <0, 4, 2, 4>
12936 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12937 EVT VT = N->getValueType(0);
12938 SDValue LHS = N->getOperand(0);
12939 SDValue RHS = N->getOperand(1);
12942 // Make sure we're not running after operation legalization where it
12943 // may have custom lowered the vector shuffles.
12944 if (LegalOperations)
12947 if (N->getOpcode() != ISD::AND)
12950 if (RHS.getOpcode() == ISD::BITCAST)
12951 RHS = RHS.getOperand(0);
12953 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12954 SmallVector<int, 8> Indices;
12955 unsigned NumElts = RHS.getNumOperands();
12957 for (unsigned i = 0; i != NumElts; ++i) {
12958 SDValue Elt = RHS.getOperand(i);
12959 if (isAllOnesConstant(Elt))
12960 Indices.push_back(i);
12961 else if (isNullConstant(Elt))
12962 Indices.push_back(NumElts+i);
12967 // Let's see if the target supports this vector_shuffle.
12968 EVT RVT = RHS.getValueType();
12969 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12972 // Return the new VECTOR_SHUFFLE node.
12973 EVT EltVT = RVT.getVectorElementType();
12974 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12975 DAG.getConstant(0, dl, EltVT));
12976 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps);
12977 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12978 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12979 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12985 /// Visit a binary vector operation, like ADD.
12986 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12987 assert(N->getValueType(0).isVector() &&
12988 "SimplifyVBinOp only works on vectors!");
12990 SDValue LHS = N->getOperand(0);
12991 SDValue RHS = N->getOperand(1);
12993 if (SDValue Shuffle = XformToShuffleWithZero(N))
12996 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12998 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12999 RHS.getOpcode() == ISD::BUILD_VECTOR) {
13000 // Check if both vectors are constants. If not bail out.
13001 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
13002 cast<BuildVectorSDNode>(RHS)->isConstant()))
13005 SmallVector<SDValue, 8> Ops;
13006 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
13007 SDValue LHSOp = LHS.getOperand(i);
13008 SDValue RHSOp = RHS.getOperand(i);
13010 // Can't fold divide by zero.
13011 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
13012 N->getOpcode() == ISD::FDIV) {
13013 if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP &&
13014 cast<ConstantFPSDNode>(RHSOp.getNode())->isZero()))
13018 EVT VT = LHSOp.getValueType();
13019 EVT RVT = RHSOp.getValueType();
13021 // Integer BUILD_VECTOR operands may have types larger than the element
13022 // size (e.g., when the element type is not legal). Prior to type
13023 // legalization, the types may not match between the two BUILD_VECTORS.
13024 // Truncate one of the operands to make them match.
13025 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
13026 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
13028 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
13032 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
13034 if (FoldOp.getOpcode() != ISD::UNDEF &&
13035 FoldOp.getOpcode() != ISD::Constant &&
13036 FoldOp.getOpcode() != ISD::ConstantFP)
13038 Ops.push_back(FoldOp);
13039 AddToWorklist(FoldOp.getNode());
13042 if (Ops.size() == LHS.getNumOperands())
13043 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
13046 // Type legalization might introduce new shuffles in the DAG.
13047 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13048 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
13049 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13050 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13051 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13052 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13053 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13054 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13056 if (SVN0->getMask().equals(SVN1->getMask())) {
13057 EVT VT = N->getValueType(0);
13058 SDValue UndefVector = LHS.getOperand(1);
13059 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13060 LHS.getOperand(0), RHS.getOperand(0));
13061 AddUsersToWorklist(N);
13062 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13063 &SVN0->getMask()[0]);
13070 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13071 SDValue N1, SDValue N2){
13072 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13074 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13075 cast<CondCodeSDNode>(N0.getOperand(2))->get());
13077 // If we got a simplified select_cc node back from SimplifySelectCC, then
13078 // break it down into a new SETCC node, and a new SELECT node, and then return
13079 // the SELECT node, since we were called with a SELECT node.
13080 if (SCC.getNode()) {
13081 // Check to see if we got a select_cc back (to turn into setcc/select).
13082 // Otherwise, just return whatever node we got back, like fabs.
13083 if (SCC.getOpcode() == ISD::SELECT_CC) {
13084 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13086 SCC.getOperand(0), SCC.getOperand(1),
13087 SCC.getOperand(4));
13088 AddToWorklist(SETCC.getNode());
13089 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13090 SCC.getOperand(2), SCC.getOperand(3));
13098 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13099 /// being selected between, see if we can simplify the select. Callers of this
13100 /// should assume that TheSelect is deleted if this returns true. As such, they
13101 /// should return the appropriate thing (e.g. the node) back to the top-level of
13102 /// the DAG combiner loop to avoid it being looked at.
13103 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13106 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13107 // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13108 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13109 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13110 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13111 SDValue Sqrt = RHS;
13114 const ConstantFPSDNode *NegZero = nullptr;
13116 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13117 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13118 CmpLHS = TheSelect->getOperand(0);
13119 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13121 // SELECT or VSELECT
13122 SDValue Cmp = TheSelect->getOperand(0);
13123 if (Cmp.getOpcode() == ISD::SETCC) {
13124 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13125 CmpLHS = Cmp.getOperand(0);
13126 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13129 if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13130 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13131 CC == ISD::SETULT || CC == ISD::SETLT)) {
13132 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13133 CombineTo(TheSelect, Sqrt);
13138 // Cannot simplify select with vector condition
13139 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13141 // If this is a select from two identical things, try to pull the operation
13142 // through the select.
13143 if (LHS.getOpcode() != RHS.getOpcode() ||
13144 !LHS.hasOneUse() || !RHS.hasOneUse())
13147 // If this is a load and the token chain is identical, replace the select
13148 // of two loads with a load through a select of the address to load from.
13149 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13150 // constants have been dropped into the constant pool.
13151 if (LHS.getOpcode() == ISD::LOAD) {
13152 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13153 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13155 // Token chains must be identical.
13156 if (LHS.getOperand(0) != RHS.getOperand(0) ||
13157 // Do not let this transformation reduce the number of volatile loads.
13158 LLD->isVolatile() || RLD->isVolatile() ||
13159 // FIXME: If either is a pre/post inc/dec load,
13160 // we'd need to split out the address adjustment.
13161 LLD->isIndexed() || RLD->isIndexed() ||
13162 // If this is an EXTLOAD, the VT's must match.
13163 LLD->getMemoryVT() != RLD->getMemoryVT() ||
13164 // If this is an EXTLOAD, the kind of extension must match.
13165 (LLD->getExtensionType() != RLD->getExtensionType() &&
13166 // The only exception is if one of the extensions is anyext.
13167 LLD->getExtensionType() != ISD::EXTLOAD &&
13168 RLD->getExtensionType() != ISD::EXTLOAD) ||
13169 // FIXME: this discards src value information. This is
13170 // over-conservative. It would be beneficial to be able to remember
13171 // both potential memory locations. Since we are discarding
13172 // src value info, don't do the transformation if the memory
13173 // locations are not in the default address space.
13174 LLD->getPointerInfo().getAddrSpace() != 0 ||
13175 RLD->getPointerInfo().getAddrSpace() != 0 ||
13176 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13177 LLD->getBasePtr().getValueType()))
13180 // Check that the select condition doesn't reach either load. If so,
13181 // folding this will induce a cycle into the DAG. If not, this is safe to
13182 // xform, so create a select of the addresses.
13184 if (TheSelect->getOpcode() == ISD::SELECT) {
13185 SDNode *CondNode = TheSelect->getOperand(0).getNode();
13186 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13187 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13189 // The loads must not depend on one another.
13190 if (LLD->isPredecessorOf(RLD) ||
13191 RLD->isPredecessorOf(LLD))
13193 Addr = DAG.getSelect(SDLoc(TheSelect),
13194 LLD->getBasePtr().getValueType(),
13195 TheSelect->getOperand(0), LLD->getBasePtr(),
13196 RLD->getBasePtr());
13197 } else { // Otherwise SELECT_CC
13198 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13199 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13201 if ((LLD->hasAnyUseOfValue(1) &&
13202 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13203 (RLD->hasAnyUseOfValue(1) &&
13204 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13207 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13208 LLD->getBasePtr().getValueType(),
13209 TheSelect->getOperand(0),
13210 TheSelect->getOperand(1),
13211 LLD->getBasePtr(), RLD->getBasePtr(),
13212 TheSelect->getOperand(4));
13216 // It is safe to replace the two loads if they have different alignments,
13217 // but the new load must be the minimum (most restrictive) alignment of the
13219 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13220 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13221 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13222 Load = DAG.getLoad(TheSelect->getValueType(0),
13224 // FIXME: Discards pointer and AA info.
13225 LLD->getChain(), Addr, MachinePointerInfo(),
13226 LLD->isVolatile(), LLD->isNonTemporal(),
13227 isInvariant, Alignment);
13229 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13230 RLD->getExtensionType() : LLD->getExtensionType(),
13232 TheSelect->getValueType(0),
13233 // FIXME: Discards pointer and AA info.
13234 LLD->getChain(), Addr, MachinePointerInfo(),
13235 LLD->getMemoryVT(), LLD->isVolatile(),
13236 LLD->isNonTemporal(), isInvariant, Alignment);
13239 // Users of the select now use the result of the load.
13240 CombineTo(TheSelect, Load);
13242 // Users of the old loads now use the new load's chain. We know the
13243 // old-load value is dead now.
13244 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13245 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13252 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13253 /// where 'cond' is the comparison specified by CC.
13254 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13255 SDValue N2, SDValue N3,
13256 ISD::CondCode CC, bool NotExtCompare) {
13257 // (x ? y : y) -> y.
13258 if (N2 == N3) return N2;
13260 EVT VT = N2.getValueType();
13261 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13262 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13264 // Determine if the condition we're dealing with is constant
13265 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13266 N0, N1, CC, DL, false);
13267 if (SCC.getNode()) AddToWorklist(SCC.getNode());
13269 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13270 // fold select_cc true, x, y -> x
13271 // fold select_cc false, x, y -> y
13272 return !SCCC->isNullValue() ? N2 : N3;
13275 // Check to see if we can simplify the select into an fabs node
13276 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13277 // Allow either -0.0 or 0.0
13278 if (CFP->isZero()) {
13279 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13280 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13281 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13282 N2 == N3.getOperand(0))
13283 return DAG.getNode(ISD::FABS, DL, VT, N0);
13285 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13286 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13287 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13288 N2.getOperand(0) == N3)
13289 return DAG.getNode(ISD::FABS, DL, VT, N3);
13293 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13294 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13295 // in it. This is a win when the constant is not otherwise available because
13296 // it replaces two constant pool loads with one. We only do this if the FP
13297 // type is known to be legal, because if it isn't, then we are before legalize
13298 // types an we want the other legalization to happen first (e.g. to avoid
13299 // messing with soft float) and if the ConstantFP is not legal, because if
13300 // it is legal, we may not need to store the FP constant in a constant pool.
13301 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13302 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13303 if (TLI.isTypeLegal(N2.getValueType()) &&
13304 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13305 TargetLowering::Legal &&
13306 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13307 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13308 // If both constants have multiple uses, then we won't need to do an
13309 // extra load, they are likely around in registers for other users.
13310 (TV->hasOneUse() || FV->hasOneUse())) {
13311 Constant *Elts[] = {
13312 const_cast<ConstantFP*>(FV->getConstantFPValue()),
13313 const_cast<ConstantFP*>(TV->getConstantFPValue())
13315 Type *FPTy = Elts[0]->getType();
13316 const DataLayout &TD = *TLI.getDataLayout();
13318 // Create a ConstantArray of the two constants.
13319 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13320 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
13321 TD.getPrefTypeAlignment(FPTy));
13322 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13324 // Get the offsets to the 0 and 1 element of the array so that we can
13325 // select between them.
13326 SDValue Zero = DAG.getIntPtrConstant(0, DL);
13327 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13328 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13330 SDValue Cond = DAG.getSetCC(DL,
13331 getSetCCResultType(N0.getValueType()),
13333 AddToWorklist(Cond.getNode());
13334 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13336 AddToWorklist(CstOffset.getNode());
13337 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13339 AddToWorklist(CPIdx.getNode());
13340 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13341 MachinePointerInfo::getConstantPool(), false,
13342 false, false, Alignment);
13346 // Check to see if we can perform the "gzip trick", transforming
13347 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13348 if (isNullConstant(N3) && CC == ISD::SETLT &&
13349 (isNullConstant(N1) || // (a < 0) ? b : 0
13350 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0
13351 EVT XType = N0.getValueType();
13352 EVT AType = N2.getValueType();
13353 if (XType.bitsGE(AType)) {
13354 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13355 // single-bit constant.
13356 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13357 unsigned ShCtV = N2C->getAPIntValue().logBase2();
13358 ShCtV = XType.getSizeInBits() - ShCtV - 1;
13359 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13360 getShiftAmountTy(N0.getValueType()));
13361 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13363 AddToWorklist(Shift.getNode());
13365 if (XType.bitsGT(AType)) {
13366 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13367 AddToWorklist(Shift.getNode());
13370 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13373 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13375 DAG.getConstant(XType.getSizeInBits() - 1,
13377 getShiftAmountTy(N0.getValueType())));
13378 AddToWorklist(Shift.getNode());
13380 if (XType.bitsGT(AType)) {
13381 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13382 AddToWorklist(Shift.getNode());
13385 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13389 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13390 // where y is has a single bit set.
13391 // A plaintext description would be, we can turn the SELECT_CC into an AND
13392 // when the condition can be materialized as an all-ones register. Any
13393 // single bit-test can be materialized as an all-ones register with
13394 // shift-left and shift-right-arith.
13395 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13396 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13397 SDValue AndLHS = N0->getOperand(0);
13398 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13399 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13400 // Shift the tested bit over the sign bit.
13401 APInt AndMask = ConstAndRHS->getAPIntValue();
13403 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13404 getShiftAmountTy(AndLHS.getValueType()));
13405 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13407 // Now arithmetic right shift it all the way over, so the result is either
13408 // all-ones, or zero.
13410 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13411 getShiftAmountTy(Shl.getValueType()));
13412 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13414 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13418 // fold select C, 16, 0 -> shl C, 4
13419 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13420 TLI.getBooleanContents(N0.getValueType()) ==
13421 TargetLowering::ZeroOrOneBooleanContent) {
13423 // If the caller doesn't want us to simplify this into a zext of a compare,
13425 if (NotExtCompare && N2C->isOne())
13428 // Get a SetCC of the condition
13429 // NOTE: Don't create a SETCC if it's not legal on this target.
13430 if (!LegalOperations ||
13431 TLI.isOperationLegal(ISD::SETCC,
13432 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13434 // cast from setcc result type to select result type
13436 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13438 if (N2.getValueType().bitsLT(SCC.getValueType()))
13439 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13440 N2.getValueType());
13442 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13443 N2.getValueType(), SCC);
13445 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13446 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13447 N2.getValueType(), SCC);
13450 AddToWorklist(SCC.getNode());
13451 AddToWorklist(Temp.getNode());
13456 // shl setcc result by log2 n2c
13457 return DAG.getNode(
13458 ISD::SHL, DL, N2.getValueType(), Temp,
13459 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13460 getShiftAmountTy(Temp.getValueType())));
13464 // Check to see if this is the equivalent of setcc
13465 // FIXME: Turn all of these into setcc if setcc if setcc is legal
13466 // otherwise, go ahead with the folds.
13467 if (0 && isNullConstant(N3) && isOneConstant(N2)) {
13468 EVT XType = N0.getValueType();
13469 if (!LegalOperations ||
13470 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13471 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13472 if (Res.getValueType() != VT)
13473 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13477 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13478 if (isNullConstant(N1) && CC == ISD::SETEQ &&
13479 (!LegalOperations ||
13480 TLI.isOperationLegal(ISD::CTLZ, XType))) {
13481 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13482 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13483 DAG.getConstant(Log2_32(XType.getSizeInBits()),
13485 getShiftAmountTy(Ctlz.getValueType())));
13487 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13488 if (isNullConstant(N1) && CC == ISD::SETGT) {
13490 SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13491 XType, DAG.getConstant(0, DL, XType), N0);
13492 SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13493 return DAG.getNode(ISD::SRL, DL, XType,
13494 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13495 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13496 getShiftAmountTy(XType)));
13498 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13499 if (isAllOnesConstant(N1) && CC == ISD::SETGT) {
13501 SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13502 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13503 getShiftAmountTy(N0.getValueType())));
13504 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13509 // Check to see if this is an integer abs.
13510 // select_cc setg[te] X, 0, X, -X ->
13511 // select_cc setgt X, -1, X, -X ->
13512 // select_cc setl[te] X, 0, -X, X ->
13513 // select_cc setlt X, 1, -X, X ->
13514 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13516 ConstantSDNode *SubC = nullptr;
13517 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13518 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13519 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13520 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13521 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13522 (N1C->isOne() && CC == ISD::SETLT)) &&
13523 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13524 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13526 EVT XType = N0.getValueType();
13527 if (SubC && SubC->isNullValue() && XType.isInteger()) {
13529 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13531 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13532 getShiftAmountTy(N0.getValueType())));
13533 SDValue Add = DAG.getNode(ISD::ADD, DL,
13535 AddToWorklist(Shift.getNode());
13536 AddToWorklist(Add.getNode());
13537 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13544 /// This is a stub for TargetLowering::SimplifySetCC.
13545 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13546 SDValue N1, ISD::CondCode Cond,
13547 SDLoc DL, bool foldBooleans) {
13548 TargetLowering::DAGCombinerInfo
13549 DagCombineInfo(DAG, Level, false, this);
13550 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13553 /// Given an ISD::SDIV node expressing a divide by constant, return
13554 /// a DAG expression to select that will generate the same value by multiplying
13555 /// by a magic number.
13556 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13557 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13558 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13562 // Avoid division by zero.
13563 if (C->isNullValue())
13566 std::vector<SDNode*> Built;
13568 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13570 for (SDNode *N : Built)
13575 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13576 /// DAG expression that will generate the same value by right shifting.
13577 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13578 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13582 // Avoid division by zero.
13583 if (C->isNullValue())
13586 std::vector<SDNode *> Built;
13587 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13589 for (SDNode *N : Built)
13594 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13595 /// expression that will generate the same value by multiplying by a magic
13597 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13598 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13599 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13603 // Avoid division by zero.
13604 if (C->isNullValue())
13607 std::vector<SDNode*> Built;
13609 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13611 for (SDNode *N : Built)
13616 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13617 if (Level >= AfterLegalizeDAG)
13620 // Expose the DAG combiner to the target combiner implementations.
13621 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13623 unsigned Iterations = 0;
13624 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13626 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13627 // For the reciprocal, we need to find the zero of the function:
13628 // F(X) = A X - 1 [which has a zero at X = 1/A]
13630 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13631 // does not require additional intermediate precision]
13632 EVT VT = Op.getValueType();
13634 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13636 AddToWorklist(Est.getNode());
13638 // Newton iterations: Est = Est + Est (1 - Arg * Est)
13639 for (unsigned i = 0; i < Iterations; ++i) {
13640 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13641 AddToWorklist(NewEst.getNode());
13643 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13644 AddToWorklist(NewEst.getNode());
13646 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13647 AddToWorklist(NewEst.getNode());
13649 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13650 AddToWorklist(Est.getNode());
13659 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13660 /// For the reciprocal sqrt, we need to find the zero of the function:
13661 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13663 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13664 /// As a result, we precompute A/2 prior to the iteration loop.
13665 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13666 unsigned Iterations) {
13667 EVT VT = Arg.getValueType();
13669 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13671 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13672 // this entire sequence requires only one FP constant.
13673 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13674 AddToWorklist(HalfArg.getNode());
13676 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13677 AddToWorklist(HalfArg.getNode());
13679 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13680 for (unsigned i = 0; i < Iterations; ++i) {
13681 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13682 AddToWorklist(NewEst.getNode());
13684 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13685 AddToWorklist(NewEst.getNode());
13687 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13688 AddToWorklist(NewEst.getNode());
13690 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13691 AddToWorklist(Est.getNode());
13696 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13697 /// For the reciprocal sqrt, we need to find the zero of the function:
13698 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13700 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13701 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13702 unsigned Iterations) {
13703 EVT VT = Arg.getValueType();
13705 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13706 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13708 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13709 for (unsigned i = 0; i < Iterations; ++i) {
13710 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13711 AddToWorklist(HalfEst.getNode());
13713 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13714 AddToWorklist(Est.getNode());
13716 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13717 AddToWorklist(Est.getNode());
13719 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13720 AddToWorklist(Est.getNode());
13722 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13723 AddToWorklist(Est.getNode());
13728 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13729 if (Level >= AfterLegalizeDAG)
13732 // Expose the DAG combiner to the target combiner implementations.
13733 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13734 unsigned Iterations = 0;
13735 bool UseOneConstNR = false;
13736 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13737 AddToWorklist(Est.getNode());
13739 Est = UseOneConstNR ?
13740 BuildRsqrtNROneConst(Op, Est, Iterations) :
13741 BuildRsqrtNRTwoConst(Op, Est, Iterations);
13749 /// Return true if base is a frame index, which is known not to alias with
13750 /// anything but itself. Provides base object and offset as results.
13751 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13752 const GlobalValue *&GV, const void *&CV) {
13753 // Assume it is a primitive operation.
13754 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13756 // If it's an adding a simple constant then integrate the offset.
13757 if (Base.getOpcode() == ISD::ADD) {
13758 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13759 Base = Base.getOperand(0);
13760 Offset += C->getZExtValue();
13764 // Return the underlying GlobalValue, and update the Offset. Return false
13765 // for GlobalAddressSDNode since the same GlobalAddress may be represented
13766 // by multiple nodes with different offsets.
13767 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13768 GV = G->getGlobal();
13769 Offset += G->getOffset();
13773 // Return the underlying Constant value, and update the Offset. Return false
13774 // for ConstantSDNodes since the same constant pool entry may be represented
13775 // by multiple nodes with different offsets.
13776 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13777 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13778 : (const void *)C->getConstVal();
13779 Offset += C->getOffset();
13782 // If it's any of the following then it can't alias with anything but itself.
13783 return isa<FrameIndexSDNode>(Base);
13786 /// Return true if there is any possibility that the two addresses overlap.
13787 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13788 // If they are the same then they must be aliases.
13789 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13791 // If they are both volatile then they cannot be reordered.
13792 if (Op0->isVolatile() && Op1->isVolatile()) return true;
13794 // Gather base node and offset information.
13795 SDValue Base1, Base2;
13796 int64_t Offset1, Offset2;
13797 const GlobalValue *GV1, *GV2;
13798 const void *CV1, *CV2;
13799 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13800 Base1, Offset1, GV1, CV1);
13801 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13802 Base2, Offset2, GV2, CV2);
13804 // If they have a same base address then check to see if they overlap.
13805 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13806 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13807 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13809 // It is possible for different frame indices to alias each other, mostly
13810 // when tail call optimization reuses return address slots for arguments.
13811 // To catch this case, look up the actual index of frame indices to compute
13812 // the real alias relationship.
13813 if (isFrameIndex1 && isFrameIndex2) {
13814 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13815 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13816 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13817 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13818 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13821 // Otherwise, if we know what the bases are, and they aren't identical, then
13822 // we know they cannot alias.
13823 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13826 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13827 // compared to the size and offset of the access, we may be able to prove they
13828 // do not alias. This check is conservative for now to catch cases created by
13829 // splitting vector types.
13830 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13831 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13832 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13833 Op1->getMemoryVT().getSizeInBits() >> 3) &&
13834 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13835 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13836 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13838 // There is no overlap between these relatively aligned accesses of similar
13839 // size, return no alias.
13840 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13841 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13845 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13847 : DAG.getSubtarget().useAA();
13849 if (CombinerAAOnlyFunc.getNumOccurrences() &&
13850 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13854 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13855 // Use alias analysis information.
13856 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13857 Op1->getSrcValueOffset());
13858 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13859 Op0->getSrcValueOffset() - MinOffset;
13860 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13861 Op1->getSrcValueOffset() - MinOffset;
13862 AliasAnalysis::AliasResult AAResult =
13863 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13865 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13866 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13868 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13869 if (AAResult == AliasAnalysis::NoAlias)
13873 // Otherwise we have to assume they alias.
13877 /// Walk up chain skipping non-aliasing memory nodes,
13878 /// looking for aliasing nodes and adding them to the Aliases vector.
13879 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13880 SmallVectorImpl<SDValue> &Aliases) {
13881 SmallVector<SDValue, 8> Chains; // List of chains to visit.
13882 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
13884 // Get alias information for node.
13885 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13888 Chains.push_back(OriginalChain);
13889 unsigned Depth = 0;
13891 // Look at each chain and determine if it is an alias. If so, add it to the
13892 // aliases list. If not, then continue up the chain looking for the next
13894 while (!Chains.empty()) {
13895 SDValue Chain = Chains.back();
13898 // For TokenFactor nodes, look at each operand and only continue up the
13899 // chain until we find two aliases. If we've seen two aliases, assume we'll
13900 // find more and revert to original chain since the xform is unlikely to be
13903 // FIXME: The depth check could be made to return the last non-aliasing
13904 // chain we found before we hit a tokenfactor rather than the original
13906 if (Depth > 6 || Aliases.size() == 2) {
13908 Aliases.push_back(OriginalChain);
13912 // Don't bother if we've been before.
13913 if (!Visited.insert(Chain.getNode()).second)
13916 switch (Chain.getOpcode()) {
13917 case ISD::EntryToken:
13918 // Entry token is ideal chain operand, but handled in FindBetterChain.
13923 // Get alias information for Chain.
13924 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13925 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13927 // If chain is alias then stop here.
13928 if (!(IsLoad && IsOpLoad) &&
13929 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13930 Aliases.push_back(Chain);
13932 // Look further up the chain.
13933 Chains.push_back(Chain.getOperand(0));
13939 case ISD::TokenFactor:
13940 // We have to check each of the operands of the token factor for "small"
13941 // token factors, so we queue them up. Adding the operands to the queue
13942 // (stack) in reverse order maintains the original order and increases the
13943 // likelihood that getNode will find a matching token factor (CSE.)
13944 if (Chain.getNumOperands() > 16) {
13945 Aliases.push_back(Chain);
13948 for (unsigned n = Chain.getNumOperands(); n;)
13949 Chains.push_back(Chain.getOperand(--n));
13954 // For all other instructions we will just have to take what we can get.
13955 Aliases.push_back(Chain);
13960 // We need to be careful here to also search for aliases through the
13961 // value operand of a store, etc. Consider the following situation:
13963 // L1 = load Token1, %52
13964 // S1 = store Token1, L1, %51
13965 // L2 = load Token1, %52+8
13966 // S2 = store Token1, L2, %51+8
13967 // Token2 = Token(S1, S2)
13968 // L3 = load Token2, %53
13969 // S3 = store Token2, L3, %52
13970 // L4 = load Token2, %53+8
13971 // S4 = store Token2, L4, %52+8
13972 // If we search for aliases of S3 (which loads address %52), and we look
13973 // only through the chain, then we'll miss the trivial dependence on L1
13974 // (which also loads from %52). We then might change all loads and
13975 // stores to use Token1 as their chain operand, which could result in
13976 // copying %53 into %52 before copying %52 into %51 (which should
13979 // The problem is, however, that searching for such data dependencies
13980 // can become expensive, and the cost is not directly related to the
13981 // chain depth. Instead, we'll rule out such configurations here by
13982 // insisting that we've visited all chain users (except for users
13983 // of the original chain, which is not necessary). When doing this,
13984 // we need to look through nodes we don't care about (otherwise, things
13985 // like register copies will interfere with trivial cases).
13987 SmallVector<const SDNode *, 16> Worklist;
13988 for (const SDNode *N : Visited)
13989 if (N != OriginalChain.getNode())
13990 Worklist.push_back(N);
13992 while (!Worklist.empty()) {
13993 const SDNode *M = Worklist.pop_back_val();
13995 // We have already visited M, and want to make sure we've visited any uses
13996 // of M that we care about. For uses that we've not visisted, and don't
13997 // care about, queue them to the worklist.
13999 for (SDNode::use_iterator UI = M->use_begin(),
14000 UIE = M->use_end(); UI != UIE; ++UI)
14001 if (UI.getUse().getValueType() == MVT::Other &&
14002 Visited.insert(*UI).second) {
14003 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
14004 // We've not visited this use, and we care about it (it could have an
14005 // ordering dependency with the original node).
14007 Aliases.push_back(OriginalChain);
14011 // We've not visited this use, but we don't care about it. Mark it as
14012 // visited and enqueue it to the worklist.
14013 Worklist.push_back(*UI);
14018 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14019 /// (aliasing node.)
14020 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14021 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
14023 // Accumulate all the aliases to this node.
14024 GatherAllAliases(N, OldChain, Aliases);
14026 // If no operands then chain to entry token.
14027 if (Aliases.size() == 0)
14028 return DAG.getEntryNode();
14030 // If a single operand then chain to it. We don't need to revisit it.
14031 if (Aliases.size() == 1)
14034 // Construct a custom tailored token factor.
14035 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14038 /// This is the entry point for the file.
14039 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14040 CodeGenOpt::Level OptLevel) {
14041 /// This is the main entry point to this class.
14042 DAGCombiner(*this, AA, OptLevel).Run(Level);