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 MergeStoresOfConstantsOrVecElts. Returns a
392 /// constant build_vector of the stored constant values in Stores.
393 SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
395 ArrayRef<MemOpLink> Stores,
398 /// This is a helper function for MergeConsecutiveStores. When the source
399 /// elements of the consecutive stores are all constants or all extracted
400 /// vector elements, try to merge them into one larger store.
401 /// \return True if a merged store was created.
402 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
403 EVT MemVT, unsigned NumElem,
404 bool IsConstantSrc, bool UseVector);
406 /// This is a helper function for MergeConsecutiveStores.
407 /// Stores that may be merged are placed in StoreNodes.
408 /// Loads that may alias with those stores are placed in AliasLoadNodes.
409 void getStoreMergeAndAliasCandidates(
410 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
411 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
413 /// Merge consecutive store operations into a wide store.
414 /// This optimization uses wide integers or vectors when possible.
415 /// \return True if some memory operations were changed.
416 bool MergeConsecutiveStores(StoreSDNode *N);
418 /// \brief Try to transform a truncation where C is a constant:
419 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
421 /// \p N needs to be a truncation and its first operand an AND. Other
422 /// requirements are checked by the function (e.g. that trunc is
423 /// single-use) and if missed an empty SDValue is returned.
424 SDValue distributeTruncateThroughAnd(SDNode *N);
427 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
428 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
429 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
430 auto *F = DAG.getMachineFunction().getFunction();
431 ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
432 F->hasFnAttribute(Attribute::MinSize);
435 /// Runs the dag combiner on all nodes in the work list
436 void Run(CombineLevel AtLevel);
438 SelectionDAG &getDAG() const { return DAG; }
440 /// Returns a type large enough to hold any valid shift amount - before type
441 /// legalization these can be huge.
442 EVT getShiftAmountTy(EVT LHSTy) {
443 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
444 if (LHSTy.isVector())
446 auto &DL = DAG.getDataLayout();
447 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
448 : TLI.getPointerTy(DL);
451 /// This method returns true if we are running before type legalization or
452 /// if the specified VT is legal.
453 bool isTypeLegal(const EVT &VT) {
454 if (!LegalTypes) return true;
455 return TLI.isTypeLegal(VT);
458 /// Convenience wrapper around TargetLowering::getSetCCResultType
459 EVT getSetCCResultType(EVT VT) const {
460 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
467 /// This class is a DAGUpdateListener that removes any deleted
468 /// nodes from the worklist.
469 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
472 explicit WorklistRemover(DAGCombiner &dc)
473 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
475 void NodeDeleted(SDNode *N, SDNode *E) override {
476 DC.removeFromWorklist(N);
481 //===----------------------------------------------------------------------===//
482 // TargetLowering::DAGCombinerInfo implementation
483 //===----------------------------------------------------------------------===//
485 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
486 ((DAGCombiner*)DC)->AddToWorklist(N);
489 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
490 ((DAGCombiner*)DC)->removeFromWorklist(N);
493 SDValue TargetLowering::DAGCombinerInfo::
494 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
495 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
498 SDValue TargetLowering::DAGCombinerInfo::
499 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
500 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
504 SDValue TargetLowering::DAGCombinerInfo::
505 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
506 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
509 void TargetLowering::DAGCombinerInfo::
510 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
511 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
514 //===----------------------------------------------------------------------===//
516 //===----------------------------------------------------------------------===//
518 void DAGCombiner::deleteAndRecombine(SDNode *N) {
519 removeFromWorklist(N);
521 // If the operands of this node are only used by the node, they will now be
522 // dead. Make sure to re-visit them and recursively delete dead nodes.
523 for (const SDValue &Op : N->ops())
524 // For an operand generating multiple values, one of the values may
525 // become dead allowing further simplification (e.g. split index
526 // arithmetic from an indexed load).
527 if (Op->hasOneUse() || Op->getNumValues() > 1)
528 AddToWorklist(Op.getNode());
533 /// Return 1 if we can compute the negated form of the specified expression for
534 /// the same cost as the expression itself, or 2 if we can compute the negated
535 /// form more cheaply than the expression itself.
536 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
537 const TargetLowering &TLI,
538 const TargetOptions *Options,
539 unsigned Depth = 0) {
540 // fneg is removable even if it has multiple uses.
541 if (Op.getOpcode() == ISD::FNEG) return 2;
543 // Don't allow anything with multiple uses.
544 if (!Op.hasOneUse()) return 0;
546 // Don't recurse exponentially.
547 if (Depth > 6) return 0;
549 switch (Op.getOpcode()) {
550 default: return false;
551 case ISD::ConstantFP:
552 // Don't invert constant FP values after legalize. The negated constant
553 // isn't necessarily legal.
554 return LegalOperations ? 0 : 1;
556 // FIXME: determine better conditions for this xform.
557 if (!Options->UnsafeFPMath) return 0;
559 // After operation legalization, it might not be legal to create new FSUBs.
560 if (LegalOperations &&
561 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
564 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
565 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
568 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
569 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
572 // We can't turn -(A-B) into B-A when we honor signed zeros.
573 if (!Options->UnsafeFPMath) return 0;
575 // fold (fneg (fsub A, B)) -> (fsub B, A)
580 if (Options->HonorSignDependentRoundingFPMath()) return 0;
582 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
583 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
587 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
593 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
598 /// If isNegatibleForFree returns true, return the newly negated expression.
599 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
600 bool LegalOperations, unsigned Depth = 0) {
601 const TargetOptions &Options = DAG.getTarget().Options;
602 // fneg is removable even if it has multiple uses.
603 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
605 // Don't allow anything with multiple uses.
606 assert(Op.hasOneUse() && "Unknown reuse!");
608 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
609 switch (Op.getOpcode()) {
610 default: llvm_unreachable("Unknown code");
611 case ISD::ConstantFP: {
612 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
614 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
617 // FIXME: determine better conditions for this xform.
618 assert(Options.UnsafeFPMath);
620 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
621 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
622 DAG.getTargetLoweringInfo(), &Options, Depth+1))
623 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
624 GetNegatedExpression(Op.getOperand(0), DAG,
625 LegalOperations, Depth+1),
627 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
628 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
629 GetNegatedExpression(Op.getOperand(1), DAG,
630 LegalOperations, Depth+1),
633 // We can't turn -(A-B) into B-A when we honor signed zeros.
634 assert(Options.UnsafeFPMath);
636 // fold (fneg (fsub 0, B)) -> B
637 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
639 return Op.getOperand(1);
641 // fold (fneg (fsub A, B)) -> (fsub B, A)
642 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
643 Op.getOperand(1), Op.getOperand(0));
647 assert(!Options.HonorSignDependentRoundingFPMath());
649 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
650 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
651 DAG.getTargetLoweringInfo(), &Options, Depth+1))
652 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
653 GetNegatedExpression(Op.getOperand(0), DAG,
654 LegalOperations, Depth+1),
657 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
658 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
660 GetNegatedExpression(Op.getOperand(1), DAG,
661 LegalOperations, Depth+1));
665 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
666 GetNegatedExpression(Op.getOperand(0), DAG,
667 LegalOperations, Depth+1));
669 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
670 GetNegatedExpression(Op.getOperand(0), DAG,
671 LegalOperations, Depth+1),
676 // Return true if this node is a setcc, or is a select_cc
677 // that selects between the target values used for true and false, making it
678 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
679 // the appropriate nodes based on the type of node we are checking. This
680 // simplifies life a bit for the callers.
681 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
683 if (N.getOpcode() == ISD::SETCC) {
684 LHS = N.getOperand(0);
685 RHS = N.getOperand(1);
686 CC = N.getOperand(2);
690 if (N.getOpcode() != ISD::SELECT_CC ||
691 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
692 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
695 if (TLI.getBooleanContents(N.getValueType()) ==
696 TargetLowering::UndefinedBooleanContent)
699 LHS = N.getOperand(0);
700 RHS = N.getOperand(1);
701 CC = N.getOperand(4);
705 /// Return true if this is a SetCC-equivalent operation with only one use.
706 /// If this is true, it allows the users to invert the operation for free when
707 /// it is profitable to do so.
708 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
710 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
715 /// Returns true if N is a BUILD_VECTOR node whose
716 /// elements are all the same constant or undefined.
717 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
718 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
723 unsigned SplatBitSize;
725 EVT EltVT = N->getValueType(0).getVectorElementType();
726 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
728 EltVT.getSizeInBits() >= SplatBitSize);
731 // \brief Returns the SDNode if it is a constant integer BuildVector
732 // or constant integer.
733 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
734 if (isa<ConstantSDNode>(N))
736 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
741 // \brief Returns the SDNode if it is a constant float BuildVector
742 // or constant float.
743 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
744 if (isa<ConstantFPSDNode>(N))
746 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
751 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
753 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
754 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
757 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
758 BitVector UndefElements;
759 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
761 // BuildVectors can truncate their operands. Ignore that case here.
762 // FIXME: We blindly ignore splats which include undef which is overly
764 if (CN && UndefElements.none() &&
765 CN->getValueType(0) == N.getValueType().getScalarType())
772 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
774 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
775 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
778 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
779 BitVector UndefElements;
780 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
782 if (CN && UndefElements.none())
789 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
790 SDValue N0, SDValue N1) {
791 EVT VT = N0.getValueType();
792 if (N0.getOpcode() == Opc) {
793 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
794 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
795 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
796 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
797 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
800 if (N0.hasOneUse()) {
801 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
803 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
804 if (!OpNode.getNode())
806 AddToWorklist(OpNode.getNode());
807 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
812 if (N1.getOpcode() == Opc) {
813 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
814 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
815 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
816 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
817 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
820 if (N1.hasOneUse()) {
821 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
823 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
824 if (!OpNode.getNode())
826 AddToWorklist(OpNode.getNode());
827 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
835 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
837 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
839 DEBUG(dbgs() << "\nReplacing.1 ";
841 dbgs() << "\nWith: ";
842 To[0].getNode()->dump(&DAG);
843 dbgs() << " and " << NumTo-1 << " other values\n");
844 for (unsigned i = 0, e = NumTo; i != e; ++i)
845 assert((!To[i].getNode() ||
846 N->getValueType(i) == To[i].getValueType()) &&
847 "Cannot combine value to value of different type!");
849 WorklistRemover DeadNodes(*this);
850 DAG.ReplaceAllUsesWith(N, To);
852 // Push the new nodes and any users onto the worklist
853 for (unsigned i = 0, e = NumTo; i != e; ++i) {
854 if (To[i].getNode()) {
855 AddToWorklist(To[i].getNode());
856 AddUsersToWorklist(To[i].getNode());
861 // Finally, if the node is now dead, remove it from the graph. The node
862 // may not be dead if the replacement process recursively simplified to
863 // something else needing this node.
865 deleteAndRecombine(N);
866 return SDValue(N, 0);
870 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
871 // Replace all uses. If any nodes become isomorphic to other nodes and
872 // are deleted, make sure to remove them from our worklist.
873 WorklistRemover DeadNodes(*this);
874 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
876 // Push the new node and any (possibly new) users onto the worklist.
877 AddToWorklist(TLO.New.getNode());
878 AddUsersToWorklist(TLO.New.getNode());
880 // Finally, if the node is now dead, remove it from the graph. The node
881 // may not be dead if the replacement process recursively simplified to
882 // something else needing this node.
883 if (TLO.Old.getNode()->use_empty())
884 deleteAndRecombine(TLO.Old.getNode());
887 /// Check the specified integer node value to see if it can be simplified or if
888 /// things it uses can be simplified by bit propagation. If so, return true.
889 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
890 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
891 APInt KnownZero, KnownOne;
892 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
896 AddToWorklist(Op.getNode());
898 // Replace the old value with the new one.
900 DEBUG(dbgs() << "\nReplacing.2 ";
901 TLO.Old.getNode()->dump(&DAG);
902 dbgs() << "\nWith: ";
903 TLO.New.getNode()->dump(&DAG);
906 CommitTargetLoweringOpt(TLO);
910 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
912 EVT VT = Load->getValueType(0);
913 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
915 DEBUG(dbgs() << "\nReplacing.9 ";
917 dbgs() << "\nWith: ";
918 Trunc.getNode()->dump(&DAG);
920 WorklistRemover DeadNodes(*this);
921 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
922 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
923 deleteAndRecombine(Load);
924 AddToWorklist(Trunc.getNode());
927 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
930 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
931 EVT MemVT = LD->getMemoryVT();
932 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
933 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
935 : LD->getExtensionType();
937 return DAG.getExtLoad(ExtType, dl, PVT,
938 LD->getChain(), LD->getBasePtr(),
939 MemVT, LD->getMemOperand());
942 unsigned Opc = Op.getOpcode();
945 case ISD::AssertSext:
946 return DAG.getNode(ISD::AssertSext, dl, PVT,
947 SExtPromoteOperand(Op.getOperand(0), PVT),
949 case ISD::AssertZext:
950 return DAG.getNode(ISD::AssertZext, dl, PVT,
951 ZExtPromoteOperand(Op.getOperand(0), PVT),
953 case ISD::Constant: {
955 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
956 return DAG.getNode(ExtOpc, dl, PVT, Op);
960 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
962 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
965 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
966 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 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.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
979 DAG.getValueType(OldVT));
982 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
983 EVT OldVT = Op.getValueType();
985 bool Replace = false;
986 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
987 if (!NewOp.getNode())
989 AddToWorklist(NewOp.getNode());
992 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
993 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
996 /// Promote the specified integer binary operation if the target indicates it is
997 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
998 /// i32 since i16 instructions are longer.
999 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1000 if (!LegalOperations)
1003 EVT VT = Op.getValueType();
1004 if (VT.isVector() || !VT.isInteger())
1007 // If operation type is 'undesirable', e.g. i16 on x86, consider
1009 unsigned Opc = Op.getOpcode();
1010 if (TLI.isTypeDesirableForOp(Opc, VT))
1014 // Consult target whether it is a good idea to promote this operation and
1015 // what's the right type to promote it to.
1016 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1017 assert(PVT != VT && "Don't know what type to promote to!");
1019 bool Replace0 = false;
1020 SDValue N0 = Op.getOperand(0);
1021 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1025 bool Replace1 = false;
1026 SDValue N1 = Op.getOperand(1);
1031 NN1 = PromoteOperand(N1, PVT, Replace1);
1036 AddToWorklist(NN0.getNode());
1038 AddToWorklist(NN1.getNode());
1041 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1043 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1045 DEBUG(dbgs() << "\nPromoting ";
1046 Op.getNode()->dump(&DAG));
1048 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1049 DAG.getNode(Opc, dl, PVT, NN0, NN1));
1054 /// Promote the specified integer shift operation if the target indicates it is
1055 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1056 /// i32 since i16 instructions are longer.
1057 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1058 if (!LegalOperations)
1061 EVT VT = Op.getValueType();
1062 if (VT.isVector() || !VT.isInteger())
1065 // If operation type is 'undesirable', e.g. i16 on x86, consider
1067 unsigned Opc = Op.getOpcode();
1068 if (TLI.isTypeDesirableForOp(Opc, VT))
1072 // Consult target whether it is a good idea to promote this operation and
1073 // what's the right type to promote it to.
1074 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1075 assert(PVT != VT && "Don't know what type to promote to!");
1077 bool Replace = false;
1078 SDValue N0 = Op.getOperand(0);
1079 if (Opc == ISD::SRA)
1080 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1081 else if (Opc == ISD::SRL)
1082 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1084 N0 = PromoteOperand(N0, PVT, Replace);
1088 AddToWorklist(N0.getNode());
1090 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1092 DEBUG(dbgs() << "\nPromoting ";
1093 Op.getNode()->dump(&DAG));
1095 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1096 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1101 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1102 if (!LegalOperations)
1105 EVT VT = Op.getValueType();
1106 if (VT.isVector() || !VT.isInteger())
1109 // If operation type is 'undesirable', e.g. i16 on x86, consider
1111 unsigned Opc = Op.getOpcode();
1112 if (TLI.isTypeDesirableForOp(Opc, VT))
1116 // Consult target whether it is a good idea to promote this operation and
1117 // what's the right type to promote it to.
1118 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1119 assert(PVT != VT && "Don't know what type to promote to!");
1120 // fold (aext (aext x)) -> (aext x)
1121 // fold (aext (zext x)) -> (zext x)
1122 // fold (aext (sext x)) -> (sext x)
1123 DEBUG(dbgs() << "\nPromoting ";
1124 Op.getNode()->dump(&DAG));
1125 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1130 bool DAGCombiner::PromoteLoad(SDValue Op) {
1131 if (!LegalOperations)
1134 EVT VT = Op.getValueType();
1135 if (VT.isVector() || !VT.isInteger())
1138 // If operation type is 'undesirable', e.g. i16 on x86, consider
1140 unsigned Opc = Op.getOpcode();
1141 if (TLI.isTypeDesirableForOp(Opc, VT))
1145 // Consult target whether it is a good idea to promote this operation and
1146 // what's the right type to promote it to.
1147 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1148 assert(PVT != VT && "Don't know what type to promote to!");
1151 SDNode *N = Op.getNode();
1152 LoadSDNode *LD = cast<LoadSDNode>(N);
1153 EVT MemVT = LD->getMemoryVT();
1154 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1155 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1157 : LD->getExtensionType();
1158 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1159 LD->getChain(), LD->getBasePtr(),
1160 MemVT, LD->getMemOperand());
1161 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1163 DEBUG(dbgs() << "\nPromoting ";
1166 Result.getNode()->dump(&DAG);
1168 WorklistRemover DeadNodes(*this);
1169 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1170 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1171 deleteAndRecombine(N);
1172 AddToWorklist(Result.getNode());
1178 /// \brief Recursively delete a node which has no uses and any operands for
1179 /// which it is the only use.
1181 /// Note that this both deletes the nodes and removes them from the worklist.
1182 /// It also adds any nodes who have had a user deleted to the worklist as they
1183 /// may now have only one use and subject to other combines.
1184 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1185 if (!N->use_empty())
1188 SmallSetVector<SDNode *, 16> Nodes;
1191 N = Nodes.pop_back_val();
1195 if (N->use_empty()) {
1196 for (const SDValue &ChildN : N->op_values())
1197 Nodes.insert(ChildN.getNode());
1199 removeFromWorklist(N);
1204 } while (!Nodes.empty());
1208 //===----------------------------------------------------------------------===//
1209 // Main DAG Combiner implementation
1210 //===----------------------------------------------------------------------===//
1212 void DAGCombiner::Run(CombineLevel AtLevel) {
1213 // set the instance variables, so that the various visit routines may use it.
1215 LegalOperations = Level >= AfterLegalizeVectorOps;
1216 LegalTypes = Level >= AfterLegalizeTypes;
1218 // Add all the dag nodes to the worklist.
1219 for (SDNode &Node : DAG.allnodes())
1220 AddToWorklist(&Node);
1222 // Create a dummy node (which is not added to allnodes), that adds a reference
1223 // to the root node, preventing it from being deleted, and tracking any
1224 // changes of the root.
1225 HandleSDNode Dummy(DAG.getRoot());
1227 // while the worklist isn't empty, find a node and
1228 // try and combine it.
1229 while (!WorklistMap.empty()) {
1231 // The Worklist holds the SDNodes in order, but it may contain null entries.
1233 N = Worklist.pop_back_val();
1236 bool GoodWorklistEntry = WorklistMap.erase(N);
1237 (void)GoodWorklistEntry;
1238 assert(GoodWorklistEntry &&
1239 "Found a worklist entry without a corresponding map entry!");
1241 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1242 // N is deleted from the DAG, since they too may now be dead or may have a
1243 // reduced number of uses, allowing other xforms.
1244 if (recursivelyDeleteUnusedNodes(N))
1247 WorklistRemover DeadNodes(*this);
1249 // If this combine is running after legalizing the DAG, re-legalize any
1250 // nodes pulled off the worklist.
1251 if (Level == AfterLegalizeDAG) {
1252 SmallSetVector<SDNode *, 16> UpdatedNodes;
1253 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1255 for (SDNode *LN : UpdatedNodes) {
1257 AddUsersToWorklist(LN);
1263 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1265 // Add any operands of the new node which have not yet been combined to the
1266 // worklist as well. Because the worklist uniques things already, this
1267 // won't repeatedly process the same operand.
1268 CombinedNodes.insert(N);
1269 for (const SDValue &ChildN : N->op_values())
1270 if (!CombinedNodes.count(ChildN.getNode()))
1271 AddToWorklist(ChildN.getNode());
1273 SDValue RV = combine(N);
1280 // If we get back the same node we passed in, rather than a new node or
1281 // zero, we know that the node must have defined multiple values and
1282 // CombineTo was used. Since CombineTo takes care of the worklist
1283 // mechanics for us, we have no work to do in this case.
1284 if (RV.getNode() == N)
1287 assert(N->getOpcode() != ISD::DELETED_NODE &&
1288 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1289 "Node was deleted but visit returned new node!");
1291 DEBUG(dbgs() << " ... into: ";
1292 RV.getNode()->dump(&DAG));
1294 // Transfer debug value.
1295 DAG.TransferDbgValues(SDValue(N, 0), RV);
1296 if (N->getNumValues() == RV.getNode()->getNumValues())
1297 DAG.ReplaceAllUsesWith(N, RV.getNode());
1299 assert(N->getValueType(0) == RV.getValueType() &&
1300 N->getNumValues() == 1 && "Type mismatch");
1302 DAG.ReplaceAllUsesWith(N, &OpV);
1305 // Push the new node and any users onto the worklist
1306 AddToWorklist(RV.getNode());
1307 AddUsersToWorklist(RV.getNode());
1309 // Finally, if the node is now dead, remove it from the graph. The node
1310 // may not be dead if the replacement process recursively simplified to
1311 // something else needing this node. This will also take care of adding any
1312 // operands which have lost a user to the worklist.
1313 recursivelyDeleteUnusedNodes(N);
1316 // If the root changed (e.g. it was a dead load, update the root).
1317 DAG.setRoot(Dummy.getValue());
1318 DAG.RemoveDeadNodes();
1321 SDValue DAGCombiner::visit(SDNode *N) {
1322 switch (N->getOpcode()) {
1324 case ISD::TokenFactor: return visitTokenFactor(N);
1325 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1326 case ISD::ADD: return visitADD(N);
1327 case ISD::SUB: return visitSUB(N);
1328 case ISD::ADDC: return visitADDC(N);
1329 case ISD::SUBC: return visitSUBC(N);
1330 case ISD::ADDE: return visitADDE(N);
1331 case ISD::SUBE: return visitSUBE(N);
1332 case ISD::MUL: return visitMUL(N);
1333 case ISD::SDIV: return visitSDIV(N);
1334 case ISD::UDIV: return visitUDIV(N);
1335 case ISD::SREM: return visitSREM(N);
1336 case ISD::UREM: return visitUREM(N);
1337 case ISD::MULHU: return visitMULHU(N);
1338 case ISD::MULHS: return visitMULHS(N);
1339 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1340 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1341 case ISD::SMULO: return visitSMULO(N);
1342 case ISD::UMULO: return visitUMULO(N);
1343 case ISD::SDIVREM: return visitSDIVREM(N);
1344 case ISD::UDIVREM: return visitUDIVREM(N);
1345 case ISD::AND: return visitAND(N);
1346 case ISD::OR: return visitOR(N);
1347 case ISD::XOR: return visitXOR(N);
1348 case ISD::SHL: return visitSHL(N);
1349 case ISD::SRA: return visitSRA(N);
1350 case ISD::SRL: return visitSRL(N);
1352 case ISD::ROTL: return visitRotate(N);
1353 case ISD::BSWAP: return visitBSWAP(N);
1354 case ISD::CTLZ: return visitCTLZ(N);
1355 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1356 case ISD::CTTZ: return visitCTTZ(N);
1357 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1358 case ISD::CTPOP: return visitCTPOP(N);
1359 case ISD::SELECT: return visitSELECT(N);
1360 case ISD::VSELECT: return visitVSELECT(N);
1361 case ISD::SELECT_CC: return visitSELECT_CC(N);
1362 case ISD::SETCC: return visitSETCC(N);
1363 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1364 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1365 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1366 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1367 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1368 case ISD::TRUNCATE: return visitTRUNCATE(N);
1369 case ISD::BITCAST: return visitBITCAST(N);
1370 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1371 case ISD::FADD: return visitFADD(N);
1372 case ISD::FSUB: return visitFSUB(N);
1373 case ISD::FMUL: return visitFMUL(N);
1374 case ISD::FMA: return visitFMA(N);
1375 case ISD::FDIV: return visitFDIV(N);
1376 case ISD::FREM: return visitFREM(N);
1377 case ISD::FSQRT: return visitFSQRT(N);
1378 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1379 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1380 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1381 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1382 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1383 case ISD::FP_ROUND: return visitFP_ROUND(N);
1384 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1385 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1386 case ISD::FNEG: return visitFNEG(N);
1387 case ISD::FABS: return visitFABS(N);
1388 case ISD::FFLOOR: return visitFFLOOR(N);
1389 case ISD::FMINNUM: return visitFMINNUM(N);
1390 case ISD::FMAXNUM: return visitFMAXNUM(N);
1391 case ISD::FCEIL: return visitFCEIL(N);
1392 case ISD::FTRUNC: return visitFTRUNC(N);
1393 case ISD::BRCOND: return visitBRCOND(N);
1394 case ISD::BR_CC: return visitBR_CC(N);
1395 case ISD::LOAD: return visitLOAD(N);
1396 case ISD::STORE: return visitSTORE(N);
1397 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1398 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1399 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1400 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1401 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1402 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1403 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1404 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1405 case ISD::MGATHER: return visitMGATHER(N);
1406 case ISD::MLOAD: return visitMLOAD(N);
1407 case ISD::MSCATTER: return visitMSCATTER(N);
1408 case ISD::MSTORE: return visitMSTORE(N);
1409 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
1414 SDValue DAGCombiner::combine(SDNode *N) {
1415 SDValue RV = visit(N);
1417 // If nothing happened, try a target-specific DAG combine.
1418 if (!RV.getNode()) {
1419 assert(N->getOpcode() != ISD::DELETED_NODE &&
1420 "Node was deleted but visit returned NULL!");
1422 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1423 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1425 // Expose the DAG combiner to the target combiner impls.
1426 TargetLowering::DAGCombinerInfo
1427 DagCombineInfo(DAG, Level, false, this);
1429 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1433 // If nothing happened still, try promoting the operation.
1434 if (!RV.getNode()) {
1435 switch (N->getOpcode()) {
1443 RV = PromoteIntBinOp(SDValue(N, 0));
1448 RV = PromoteIntShiftOp(SDValue(N, 0));
1450 case ISD::SIGN_EXTEND:
1451 case ISD::ZERO_EXTEND:
1452 case ISD::ANY_EXTEND:
1453 RV = PromoteExtend(SDValue(N, 0));
1456 if (PromoteLoad(SDValue(N, 0)))
1462 // If N is a commutative binary node, try commuting it to enable more
1464 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1465 N->getNumValues() == 1) {
1466 SDValue N0 = N->getOperand(0);
1467 SDValue N1 = N->getOperand(1);
1469 // Constant operands are canonicalized to RHS.
1470 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1471 SDValue Ops[] = {N1, N0};
1473 if (const auto *BinNode = dyn_cast<BinaryWithFlagsSDNode>(N)) {
1474 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1477 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1480 return SDValue(CSENode, 0);
1487 /// Given a node, return its input chain if it has one, otherwise return a null
1489 static SDValue getInputChainForNode(SDNode *N) {
1490 if (unsigned NumOps = N->getNumOperands()) {
1491 if (N->getOperand(0).getValueType() == MVT::Other)
1492 return N->getOperand(0);
1493 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1494 return N->getOperand(NumOps-1);
1495 for (unsigned i = 1; i < NumOps-1; ++i)
1496 if (N->getOperand(i).getValueType() == MVT::Other)
1497 return N->getOperand(i);
1502 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1503 // If N has two operands, where one has an input chain equal to the other,
1504 // the 'other' chain is redundant.
1505 if (N->getNumOperands() == 2) {
1506 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1507 return N->getOperand(0);
1508 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1509 return N->getOperand(1);
1512 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1513 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1514 SmallPtrSet<SDNode*, 16> SeenOps;
1515 bool Changed = false; // If we should replace this token factor.
1517 // Start out with this token factor.
1520 // Iterate through token factors. The TFs grows when new token factors are
1522 for (unsigned i = 0; i < TFs.size(); ++i) {
1523 SDNode *TF = TFs[i];
1525 // Check each of the operands.
1526 for (const SDValue &Op : TF->op_values()) {
1528 switch (Op.getOpcode()) {
1529 case ISD::EntryToken:
1530 // Entry tokens don't need to be added to the list. They are
1535 case ISD::TokenFactor:
1536 if (Op.hasOneUse() &&
1537 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1538 // Queue up for processing.
1539 TFs.push_back(Op.getNode());
1540 // Clean up in case the token factor is removed.
1541 AddToWorklist(Op.getNode());
1548 // Only add if it isn't already in the list.
1549 if (SeenOps.insert(Op.getNode()).second)
1560 // If we've changed things around then replace token factor.
1563 // The entry token is the only possible outcome.
1564 Result = DAG.getEntryNode();
1566 // New and improved token factor.
1567 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1570 // Add users to worklist if AA is enabled, since it may introduce
1571 // a lot of new chained token factors while removing memory deps.
1572 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1573 : DAG.getSubtarget().useAA();
1574 return CombineTo(N, Result, UseAA /*add to worklist*/);
1580 /// MERGE_VALUES can always be eliminated.
1581 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1582 WorklistRemover DeadNodes(*this);
1583 // Replacing results may cause a different MERGE_VALUES to suddenly
1584 // be CSE'd with N, and carry its uses with it. Iterate until no
1585 // uses remain, to ensure that the node can be safely deleted.
1586 // First add the users of this node to the work list so that they
1587 // can be tried again once they have new operands.
1588 AddUsersToWorklist(N);
1590 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1591 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1592 } while (!N->use_empty());
1593 deleteAndRecombine(N);
1594 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1597 static bool isNullConstant(SDValue V) {
1598 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1599 return Const != nullptr && Const->isNullValue();
1602 static bool isNullFPConstant(SDValue V) {
1603 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1604 return Const != nullptr && Const->isZero() && !Const->isNegative();
1607 static bool isAllOnesConstant(SDValue V) {
1608 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1609 return Const != nullptr && Const->isAllOnesValue();
1612 static bool isOneConstant(SDValue V) {
1613 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1614 return Const != nullptr && Const->isOne();
1617 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1618 /// ContantSDNode pointer else nullptr.
1619 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1620 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1621 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1624 SDValue DAGCombiner::visitADD(SDNode *N) {
1625 SDValue N0 = N->getOperand(0);
1626 SDValue N1 = N->getOperand(1);
1627 EVT VT = N0.getValueType();
1630 if (VT.isVector()) {
1631 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1634 // fold (add x, 0) -> x, vector edition
1635 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1637 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1641 // fold (add x, undef) -> undef
1642 if (N0.getOpcode() == ISD::UNDEF)
1644 if (N1.getOpcode() == ISD::UNDEF)
1646 // fold (add c1, c2) -> c1+c2
1647 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1648 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1650 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1651 // canonicalize constant to RHS
1652 if (isConstantIntBuildVectorOrConstantInt(N0) &&
1653 !isConstantIntBuildVectorOrConstantInt(N1))
1654 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1655 // fold (add x, 0) -> x
1656 if (isNullConstant(N1))
1658 // fold (add Sym, c) -> Sym+c
1659 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1660 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1661 GA->getOpcode() == ISD::GlobalAddress)
1662 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1664 (uint64_t)N1C->getSExtValue());
1665 // fold ((c1-A)+c2) -> (c1+c2)-A
1666 if (N1C && N0.getOpcode() == ISD::SUB)
1667 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1669 return DAG.getNode(ISD::SUB, DL, VT,
1670 DAG.getConstant(N1C->getAPIntValue()+
1671 N0C->getAPIntValue(), DL, VT),
1675 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1677 // fold ((0-A) + B) -> B-A
1678 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1679 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1680 // fold (A + (0-B)) -> A-B
1681 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1682 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1683 // fold (A+(B-A)) -> B
1684 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1685 return N1.getOperand(0);
1686 // fold ((B-A)+A) -> B
1687 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1688 return N0.getOperand(0);
1689 // fold (A+(B-(A+C))) to (B-C)
1690 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1691 N0 == N1.getOperand(1).getOperand(0))
1692 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1693 N1.getOperand(1).getOperand(1));
1694 // fold (A+(B-(C+A))) to (B-C)
1695 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1696 N0 == N1.getOperand(1).getOperand(1))
1697 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1698 N1.getOperand(1).getOperand(0));
1699 // fold (A+((B-A)+or-C)) to (B+or-C)
1700 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1701 N1.getOperand(0).getOpcode() == ISD::SUB &&
1702 N0 == N1.getOperand(0).getOperand(1))
1703 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1704 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1706 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1707 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1708 SDValue N00 = N0.getOperand(0);
1709 SDValue N01 = N0.getOperand(1);
1710 SDValue N10 = N1.getOperand(0);
1711 SDValue N11 = N1.getOperand(1);
1713 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1714 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1715 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1716 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1719 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1720 return SDValue(N, 0);
1722 // fold (a+b) -> (a|b) iff a and b share no bits.
1723 if (VT.isInteger() && !VT.isVector()) {
1724 APInt LHSZero, LHSOne;
1725 APInt RHSZero, RHSOne;
1726 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1728 if (LHSZero.getBoolValue()) {
1729 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1731 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1732 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1733 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1734 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1735 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1740 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1741 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1742 isNullConstant(N1.getOperand(0).getOperand(0)))
1743 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1744 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1745 N1.getOperand(0).getOperand(1),
1747 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1748 isNullConstant(N0.getOperand(0).getOperand(0)))
1749 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1750 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1751 N0.getOperand(0).getOperand(1),
1754 if (N1.getOpcode() == ISD::AND) {
1755 SDValue AndOp0 = N1.getOperand(0);
1756 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1757 unsigned DestBits = VT.getScalarType().getSizeInBits();
1759 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1760 // and similar xforms where the inner op is either ~0 or 0.
1761 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1763 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1767 // add (sext i1), X -> sub X, (zext i1)
1768 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1769 N0.getOperand(0).getValueType() == MVT::i1 &&
1770 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1772 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1773 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1776 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1777 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1778 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1779 if (TN->getVT() == MVT::i1) {
1781 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1782 DAG.getConstant(1, DL, VT));
1783 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1790 SDValue DAGCombiner::visitADDC(SDNode *N) {
1791 SDValue N0 = N->getOperand(0);
1792 SDValue N1 = N->getOperand(1);
1793 EVT VT = N0.getValueType();
1795 // If the flag result is dead, turn this into an ADD.
1796 if (!N->hasAnyUseOfValue(1))
1797 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1798 DAG.getNode(ISD::CARRY_FALSE,
1799 SDLoc(N), MVT::Glue));
1801 // canonicalize constant to RHS.
1802 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1803 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1805 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1807 // fold (addc x, 0) -> x + no carry out
1808 if (isNullConstant(N1))
1809 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1810 SDLoc(N), MVT::Glue));
1812 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1813 APInt LHSZero, LHSOne;
1814 APInt RHSZero, RHSOne;
1815 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1817 if (LHSZero.getBoolValue()) {
1818 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1820 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1821 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1822 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1823 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1824 DAG.getNode(ISD::CARRY_FALSE,
1825 SDLoc(N), MVT::Glue));
1831 SDValue DAGCombiner::visitADDE(SDNode *N) {
1832 SDValue N0 = N->getOperand(0);
1833 SDValue N1 = N->getOperand(1);
1834 SDValue CarryIn = N->getOperand(2);
1836 // canonicalize constant to RHS
1837 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1838 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1840 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1843 // fold (adde x, y, false) -> (addc x, y)
1844 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1845 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1850 // Since it may not be valid to emit a fold to zero for vector initializers
1851 // check if we can before folding.
1852 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1854 bool LegalOperations, bool LegalTypes) {
1856 return DAG.getConstant(0, DL, VT);
1857 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1858 return DAG.getConstant(0, DL, VT);
1862 SDValue DAGCombiner::visitSUB(SDNode *N) {
1863 SDValue N0 = N->getOperand(0);
1864 SDValue N1 = N->getOperand(1);
1865 EVT VT = N0.getValueType();
1868 if (VT.isVector()) {
1869 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1872 // fold (sub x, 0) -> x, vector edition
1873 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1877 // fold (sub x, x) -> 0
1878 // FIXME: Refactor this and xor and other similar operations together.
1880 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1881 // fold (sub c1, c2) -> c1-c2
1882 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1883 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1885 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1886 // fold (sub x, c) -> (add x, -c)
1889 return DAG.getNode(ISD::ADD, DL, VT, N0,
1890 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1892 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1893 if (isAllOnesConstant(N0))
1894 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1895 // fold A-(A-B) -> B
1896 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1897 return N1.getOperand(1);
1898 // fold (A+B)-A -> B
1899 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1900 return N0.getOperand(1);
1901 // fold (A+B)-B -> A
1902 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1903 return N0.getOperand(0);
1904 // fold C2-(A+C1) -> (C2-C1)-A
1905 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1906 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1907 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1909 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1911 return DAG.getNode(ISD::SUB, DL, VT, NewC,
1914 // fold ((A+(B+or-C))-B) -> A+or-C
1915 if (N0.getOpcode() == ISD::ADD &&
1916 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1917 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1918 N0.getOperand(1).getOperand(0) == N1)
1919 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1920 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1921 // fold ((A+(C+B))-B) -> A+C
1922 if (N0.getOpcode() == ISD::ADD &&
1923 N0.getOperand(1).getOpcode() == ISD::ADD &&
1924 N0.getOperand(1).getOperand(1) == N1)
1925 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1926 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1927 // fold ((A-(B-C))-C) -> A-B
1928 if (N0.getOpcode() == ISD::SUB &&
1929 N0.getOperand(1).getOpcode() == ISD::SUB &&
1930 N0.getOperand(1).getOperand(1) == N1)
1931 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1932 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1934 // If either operand of a sub is undef, the result is undef
1935 if (N0.getOpcode() == ISD::UNDEF)
1937 if (N1.getOpcode() == ISD::UNDEF)
1940 // If the relocation model supports it, consider symbol offsets.
1941 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1942 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1943 // fold (sub Sym, c) -> Sym-c
1944 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1945 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1947 (uint64_t)N1C->getSExtValue());
1948 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1949 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1950 if (GA->getGlobal() == GB->getGlobal())
1951 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1955 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1956 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1957 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1958 if (TN->getVT() == MVT::i1) {
1960 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1961 DAG.getConstant(1, DL, VT));
1962 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1969 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1970 SDValue N0 = N->getOperand(0);
1971 SDValue N1 = N->getOperand(1);
1972 EVT VT = N0.getValueType();
1974 // If the flag result is dead, turn this into an SUB.
1975 if (!N->hasAnyUseOfValue(1))
1976 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1977 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1980 // fold (subc x, x) -> 0 + no borrow
1983 return CombineTo(N, DAG.getConstant(0, DL, VT),
1984 DAG.getNode(ISD::CARRY_FALSE, DL,
1988 // fold (subc x, 0) -> x + no borrow
1989 if (isNullConstant(N1))
1990 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1993 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1994 if (isAllOnesConstant(N0))
1995 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1996 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
2002 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2003 SDValue N0 = N->getOperand(0);
2004 SDValue N1 = N->getOperand(1);
2005 SDValue CarryIn = N->getOperand(2);
2007 // fold (sube x, y, false) -> (subc x, y)
2008 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2009 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2014 SDValue DAGCombiner::visitMUL(SDNode *N) {
2015 SDValue N0 = N->getOperand(0);
2016 SDValue N1 = N->getOperand(1);
2017 EVT VT = N0.getValueType();
2019 // fold (mul x, undef) -> 0
2020 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2021 return DAG.getConstant(0, SDLoc(N), VT);
2023 bool N0IsConst = false;
2024 bool N1IsConst = false;
2025 bool N1IsOpaqueConst = false;
2026 bool N0IsOpaqueConst = false;
2027 APInt ConstValue0, ConstValue1;
2029 if (VT.isVector()) {
2030 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2033 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2034 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2036 N0IsConst = isa<ConstantSDNode>(N0);
2038 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2039 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2041 N1IsConst = isa<ConstantSDNode>(N1);
2043 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2044 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2048 // fold (mul c1, c2) -> c1*c2
2049 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2050 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2051 N0.getNode(), N1.getNode());
2053 // canonicalize constant to RHS (vector doesn't have to splat)
2054 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2055 !isConstantIntBuildVectorOrConstantInt(N1))
2056 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2057 // fold (mul x, 0) -> 0
2058 if (N1IsConst && ConstValue1 == 0)
2060 // We require a splat of the entire scalar bit width for non-contiguous
2063 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2064 // fold (mul x, 1) -> x
2065 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2067 // fold (mul x, -1) -> 0-x
2068 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2070 return DAG.getNode(ISD::SUB, DL, VT,
2071 DAG.getConstant(0, DL, VT), N0);
2073 // fold (mul x, (1 << c)) -> x << c
2074 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2077 return DAG.getNode(ISD::SHL, DL, VT, N0,
2078 DAG.getConstant(ConstValue1.logBase2(), DL,
2079 getShiftAmountTy(N0.getValueType())));
2081 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2082 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2084 unsigned Log2Val = (-ConstValue1).logBase2();
2086 // FIXME: If the input is something that is easily negated (e.g. a
2087 // single-use add), we should put the negate there.
2088 return DAG.getNode(ISD::SUB, DL, VT,
2089 DAG.getConstant(0, DL, VT),
2090 DAG.getNode(ISD::SHL, DL, VT, N0,
2091 DAG.getConstant(Log2Val, DL,
2092 getShiftAmountTy(N0.getValueType()))));
2096 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2097 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2098 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2099 isa<ConstantSDNode>(N0.getOperand(1)))) {
2100 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2101 N1, N0.getOperand(1));
2102 AddToWorklist(C3.getNode());
2103 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2104 N0.getOperand(0), C3);
2107 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2110 SDValue Sh(nullptr,0), Y(nullptr,0);
2111 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2112 if (N0.getOpcode() == ISD::SHL &&
2113 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2114 isa<ConstantSDNode>(N0.getOperand(1))) &&
2115 N0.getNode()->hasOneUse()) {
2117 } else if (N1.getOpcode() == ISD::SHL &&
2118 isa<ConstantSDNode>(N1.getOperand(1)) &&
2119 N1.getNode()->hasOneUse()) {
2124 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2125 Sh.getOperand(0), Y);
2126 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2127 Mul, Sh.getOperand(1));
2131 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2132 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2133 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2134 isa<ConstantSDNode>(N0.getOperand(1))))
2135 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2136 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2137 N0.getOperand(0), N1),
2138 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2139 N0.getOperand(1), N1));
2142 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2148 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2149 SDValue N0 = N->getOperand(0);
2150 SDValue N1 = N->getOperand(1);
2151 EVT VT = N->getValueType(0);
2155 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2158 // fold (sdiv c1, c2) -> c1/c2
2159 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2160 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2161 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2162 return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2163 // fold (sdiv X, 1) -> X
2164 if (N1C && N1C->isOne())
2166 // fold (sdiv X, -1) -> 0-X
2167 if (N1C && N1C->isAllOnesValue()) {
2169 return DAG.getNode(ISD::SUB, DL, VT,
2170 DAG.getConstant(0, DL, VT), N0);
2172 // If we know the sign bits of both operands are zero, strength reduce to a
2173 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2174 if (!VT.isVector()) {
2175 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2176 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2180 // fold (sdiv X, pow2) -> simple ops after legalize
2181 // FIXME: We check for the exact bit here because the generic lowering gives
2182 // better results in that case. The target-specific lowering should learn how
2183 // to handle exact sdivs efficiently.
2184 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2185 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2186 (N1C->getAPIntValue().isPowerOf2() ||
2187 (-N1C->getAPIntValue()).isPowerOf2())) {
2188 // If dividing by powers of two is cheap, then don't perform the following
2190 if (TLI.isPow2SDivCheap())
2193 // Target-specific implementation of sdiv x, pow2.
2194 if (SDValue Res = BuildSDIVPow2(N))
2197 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2200 // Splat the sign bit into the register
2202 DAG.getNode(ISD::SRA, DL, VT, N0,
2203 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2204 getShiftAmountTy(N0.getValueType())));
2205 AddToWorklist(SGN.getNode());
2207 // Add (N0 < 0) ? abs2 - 1 : 0;
2209 DAG.getNode(ISD::SRL, DL, VT, SGN,
2210 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2211 getShiftAmountTy(SGN.getValueType())));
2212 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2213 AddToWorklist(SRL.getNode());
2214 AddToWorklist(ADD.getNode()); // Divide by pow2
2215 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2216 DAG.getConstant(lg2, DL,
2217 getShiftAmountTy(ADD.getValueType())));
2219 // If we're dividing by a positive value, we're done. Otherwise, we must
2220 // negate the result.
2221 if (N1C->getAPIntValue().isNonNegative())
2224 AddToWorklist(SRA.getNode());
2225 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2228 // If integer divide is expensive and we satisfy the requirements, emit an
2229 // alternate sequence.
2230 if (N1C && !TLI.isIntDivCheap())
2231 if (SDValue Op = BuildSDIV(N))
2235 if (N0.getOpcode() == ISD::UNDEF)
2236 return DAG.getConstant(0, SDLoc(N), VT);
2237 // X / undef -> undef
2238 if (N1.getOpcode() == ISD::UNDEF)
2244 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2245 SDValue N0 = N->getOperand(0);
2246 SDValue N1 = N->getOperand(1);
2247 EVT VT = N->getValueType(0);
2251 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2254 // fold (udiv c1, c2) -> c1/c2
2255 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2256 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2258 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT,
2261 // fold (udiv x, (1 << c)) -> x >>u c
2262 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) {
2264 return DAG.getNode(ISD::SRL, DL, VT, N0,
2265 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2266 getShiftAmountTy(N0.getValueType())));
2268 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2269 if (N1.getOpcode() == ISD::SHL) {
2270 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2271 if (SHC->getAPIntValue().isPowerOf2()) {
2272 EVT ADDVT = N1.getOperand(1).getValueType();
2274 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2276 DAG.getConstant(SHC->getAPIntValue()
2279 AddToWorklist(Add.getNode());
2280 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2284 // fold (udiv x, c) -> alternate
2285 if (N1C && !TLI.isIntDivCheap())
2286 if (SDValue Op = BuildUDIV(N))
2290 if (N0.getOpcode() == ISD::UNDEF)
2291 return DAG.getConstant(0, SDLoc(N), VT);
2292 // X / undef -> undef
2293 if (N1.getOpcode() == ISD::UNDEF)
2299 SDValue DAGCombiner::visitSREM(SDNode *N) {
2300 SDValue N0 = N->getOperand(0);
2301 SDValue N1 = N->getOperand(1);
2302 EVT VT = N->getValueType(0);
2304 // fold (srem c1, c2) -> c1%c2
2305 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2306 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2308 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT,
2311 // If we know the sign bits of both operands are zero, strength reduce to a
2312 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2313 if (!VT.isVector()) {
2314 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2315 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2318 // If X/C can be simplified by the division-by-constant logic, lower
2319 // X%C to the equivalent of X-X/C*C.
2320 if (N1C && !N1C->isNullValue()) {
2321 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2322 AddToWorklist(Div.getNode());
2323 SDValue OptimizedDiv = combine(Div.getNode());
2324 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2325 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2327 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2328 AddToWorklist(Mul.getNode());
2334 if (N0.getOpcode() == ISD::UNDEF)
2335 return DAG.getConstant(0, SDLoc(N), VT);
2336 // X % undef -> undef
2337 if (N1.getOpcode() == ISD::UNDEF)
2343 SDValue DAGCombiner::visitUREM(SDNode *N) {
2344 SDValue N0 = N->getOperand(0);
2345 SDValue N1 = N->getOperand(1);
2346 EVT VT = N->getValueType(0);
2348 // fold (urem c1, c2) -> c1%c2
2349 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2350 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2352 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT,
2355 // fold (urem x, pow2) -> (and x, pow2-1)
2356 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2357 N1C->getAPIntValue().isPowerOf2()) {
2359 return DAG.getNode(ISD::AND, DL, VT, N0,
2360 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2362 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2363 if (N1.getOpcode() == ISD::SHL) {
2364 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2365 if (SHC->getAPIntValue().isPowerOf2()) {
2368 DAG.getNode(ISD::ADD, DL, VT, N1,
2369 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2371 AddToWorklist(Add.getNode());
2372 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2377 // If X/C can be simplified by the division-by-constant logic, lower
2378 // X%C to the equivalent of X-X/C*C.
2379 if (N1C && !N1C->isNullValue()) {
2380 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2381 AddToWorklist(Div.getNode());
2382 SDValue OptimizedDiv = combine(Div.getNode());
2383 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2384 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2386 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2387 AddToWorklist(Mul.getNode());
2393 if (N0.getOpcode() == ISD::UNDEF)
2394 return DAG.getConstant(0, SDLoc(N), VT);
2395 // X % undef -> undef
2396 if (N1.getOpcode() == ISD::UNDEF)
2402 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2403 SDValue N0 = N->getOperand(0);
2404 SDValue N1 = N->getOperand(1);
2405 EVT VT = N->getValueType(0);
2408 // fold (mulhs x, 0) -> 0
2409 if (isNullConstant(N1))
2411 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2412 if (isOneConstant(N1)) {
2414 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2415 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2417 getShiftAmountTy(N0.getValueType())));
2419 // fold (mulhs x, undef) -> 0
2420 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2421 return DAG.getConstant(0, SDLoc(N), VT);
2423 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2425 if (VT.isSimple() && !VT.isVector()) {
2426 MVT Simple = VT.getSimpleVT();
2427 unsigned SimpleSize = Simple.getSizeInBits();
2428 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2429 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2430 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2431 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2432 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2433 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2434 DAG.getConstant(SimpleSize, DL,
2435 getShiftAmountTy(N1.getValueType())));
2436 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2443 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2444 SDValue N0 = N->getOperand(0);
2445 SDValue N1 = N->getOperand(1);
2446 EVT VT = N->getValueType(0);
2449 // fold (mulhu x, 0) -> 0
2450 if (isNullConstant(N1))
2452 // fold (mulhu x, 1) -> 0
2453 if (isOneConstant(N1))
2454 return DAG.getConstant(0, DL, N0.getValueType());
2455 // fold (mulhu x, undef) -> 0
2456 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2457 return DAG.getConstant(0, DL, VT);
2459 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2461 if (VT.isSimple() && !VT.isVector()) {
2462 MVT Simple = VT.getSimpleVT();
2463 unsigned SimpleSize = Simple.getSizeInBits();
2464 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2465 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2466 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2467 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2468 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2469 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2470 DAG.getConstant(SimpleSize, DL,
2471 getShiftAmountTy(N1.getValueType())));
2472 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2479 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2480 /// give the opcodes for the two computations that are being performed. Return
2481 /// true if a simplification was made.
2482 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2484 // If the high half is not needed, just compute the low half.
2485 bool HiExists = N->hasAnyUseOfValue(1);
2487 (!LegalOperations ||
2488 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2489 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2490 return CombineTo(N, Res, Res);
2493 // If the low half is not needed, just compute the high half.
2494 bool LoExists = N->hasAnyUseOfValue(0);
2496 (!LegalOperations ||
2497 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2498 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2499 return CombineTo(N, Res, Res);
2502 // If both halves are used, return as it is.
2503 if (LoExists && HiExists)
2506 // If the two computed results can be simplified separately, separate them.
2508 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2509 AddToWorklist(Lo.getNode());
2510 SDValue LoOpt = combine(Lo.getNode());
2511 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2512 (!LegalOperations ||
2513 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2514 return CombineTo(N, LoOpt, LoOpt);
2518 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2519 AddToWorklist(Hi.getNode());
2520 SDValue HiOpt = combine(Hi.getNode());
2521 if (HiOpt.getNode() && HiOpt != Hi &&
2522 (!LegalOperations ||
2523 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2524 return CombineTo(N, HiOpt, HiOpt);
2530 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2531 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2534 EVT VT = N->getValueType(0);
2537 // If the type is twice as wide is legal, transform the mulhu to a wider
2538 // multiply plus a shift.
2539 if (VT.isSimple() && !VT.isVector()) {
2540 MVT Simple = VT.getSimpleVT();
2541 unsigned SimpleSize = Simple.getSizeInBits();
2542 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2543 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2544 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2545 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2546 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2547 // Compute the high part as N1.
2548 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2549 DAG.getConstant(SimpleSize, DL,
2550 getShiftAmountTy(Lo.getValueType())));
2551 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2552 // Compute the low part as N0.
2553 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2554 return CombineTo(N, Lo, Hi);
2561 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2562 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2565 EVT VT = N->getValueType(0);
2568 // If the type is twice as wide is legal, transform the mulhu to a wider
2569 // multiply plus a shift.
2570 if (VT.isSimple() && !VT.isVector()) {
2571 MVT Simple = VT.getSimpleVT();
2572 unsigned SimpleSize = Simple.getSizeInBits();
2573 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2574 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2575 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2576 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2577 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2578 // Compute the high part as N1.
2579 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2580 DAG.getConstant(SimpleSize, DL,
2581 getShiftAmountTy(Lo.getValueType())));
2582 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2583 // Compute the low part as N0.
2584 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2585 return CombineTo(N, Lo, Hi);
2592 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2593 // (smulo x, 2) -> (saddo x, x)
2594 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2595 if (C2->getAPIntValue() == 2)
2596 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2597 N->getOperand(0), N->getOperand(0));
2602 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2603 // (umulo x, 2) -> (uaddo x, x)
2604 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2605 if (C2->getAPIntValue() == 2)
2606 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2607 N->getOperand(0), N->getOperand(0));
2612 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2613 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM))
2619 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2620 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM))
2626 /// If this is a binary operator with two operands of the same opcode, try to
2628 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2629 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2630 EVT VT = N0.getValueType();
2631 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2633 // Bail early if none of these transforms apply.
2634 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2636 // For each of OP in AND/OR/XOR:
2637 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2638 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2639 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2640 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2641 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2643 // do not sink logical op inside of a vector extend, since it may combine
2645 EVT Op0VT = N0.getOperand(0).getValueType();
2646 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2647 N0.getOpcode() == ISD::SIGN_EXTEND ||
2648 N0.getOpcode() == ISD::BSWAP ||
2649 // Avoid infinite looping with PromoteIntBinOp.
2650 (N0.getOpcode() == ISD::ANY_EXTEND &&
2651 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2652 (N0.getOpcode() == ISD::TRUNCATE &&
2653 (!TLI.isZExtFree(VT, Op0VT) ||
2654 !TLI.isTruncateFree(Op0VT, VT)) &&
2655 TLI.isTypeLegal(Op0VT))) &&
2657 Op0VT == N1.getOperand(0).getValueType() &&
2658 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2659 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2660 N0.getOperand(0).getValueType(),
2661 N0.getOperand(0), N1.getOperand(0));
2662 AddToWorklist(ORNode.getNode());
2663 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2666 // For each of OP in SHL/SRL/SRA/AND...
2667 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2668 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2669 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2670 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2671 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2672 N0.getOperand(1) == N1.getOperand(1)) {
2673 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2674 N0.getOperand(0).getValueType(),
2675 N0.getOperand(0), N1.getOperand(0));
2676 AddToWorklist(ORNode.getNode());
2677 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2678 ORNode, N0.getOperand(1));
2681 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2682 // Only perform this optimization after type legalization and before
2683 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2684 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2685 // we don't want to undo this promotion.
2686 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2688 if ((N0.getOpcode() == ISD::BITCAST ||
2689 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2690 Level == AfterLegalizeTypes) {
2691 SDValue In0 = N0.getOperand(0);
2692 SDValue In1 = N1.getOperand(0);
2693 EVT In0Ty = In0.getValueType();
2694 EVT In1Ty = In1.getValueType();
2696 // If both incoming values are integers, and the original types are the
2698 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2699 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2700 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2701 AddToWorklist(Op.getNode());
2706 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2707 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2708 // If both shuffles use the same mask, and both shuffle within a single
2709 // vector, then it is worthwhile to move the swizzle after the operation.
2710 // The type-legalizer generates this pattern when loading illegal
2711 // vector types from memory. In many cases this allows additional shuffle
2713 // There are other cases where moving the shuffle after the xor/and/or
2714 // is profitable even if shuffles don't perform a swizzle.
2715 // If both shuffles use the same mask, and both shuffles have the same first
2716 // or second operand, then it might still be profitable to move the shuffle
2717 // after the xor/and/or operation.
2718 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2719 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2720 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2722 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2723 "Inputs to shuffles are not the same type");
2725 // Check that both shuffles use the same mask. The masks are known to be of
2726 // the same length because the result vector type is the same.
2727 // Check also that shuffles have only one use to avoid introducing extra
2729 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2730 SVN0->getMask().equals(SVN1->getMask())) {
2731 SDValue ShOp = N0->getOperand(1);
2733 // Don't try to fold this node if it requires introducing a
2734 // build vector of all zeros that might be illegal at this stage.
2735 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2737 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2742 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2743 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2744 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2745 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2746 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2747 N0->getOperand(0), N1->getOperand(0));
2748 AddToWorklist(NewNode.getNode());
2749 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2750 &SVN0->getMask()[0]);
2753 // Don't try to fold this node if it requires introducing a
2754 // build vector of all zeros that might be illegal at this stage.
2755 ShOp = N0->getOperand(0);
2756 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2758 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2763 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2764 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2765 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2766 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2767 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2768 N0->getOperand(1), N1->getOperand(1));
2769 AddToWorklist(NewNode.getNode());
2770 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2771 &SVN0->getMask()[0]);
2779 /// This contains all DAGCombine rules which reduce two values combined by
2780 /// an And operation to a single value. This makes them reusable in the context
2781 /// of visitSELECT(). Rules involving constants are not included as
2782 /// visitSELECT() already handles those cases.
2783 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2784 SDNode *LocReference) {
2785 EVT VT = N1.getValueType();
2787 // fold (and x, undef) -> 0
2788 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2789 return DAG.getConstant(0, SDLoc(LocReference), VT);
2790 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2791 SDValue LL, LR, RL, RR, CC0, CC1;
2792 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2793 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2794 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2796 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2797 LL.getValueType().isInteger()) {
2798 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2799 if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2800 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2801 LR.getValueType(), LL, RL);
2802 AddToWorklist(ORNode.getNode());
2803 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2805 if (isAllOnesConstant(LR)) {
2806 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2807 if (Op1 == ISD::SETEQ) {
2808 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2809 LR.getValueType(), LL, RL);
2810 AddToWorklist(ANDNode.getNode());
2811 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2813 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2814 if (Op1 == ISD::SETGT) {
2815 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2816 LR.getValueType(), LL, RL);
2817 AddToWorklist(ORNode.getNode());
2818 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2822 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2823 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2824 Op0 == Op1 && LL.getValueType().isInteger() &&
2825 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2826 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2828 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2829 LL, DAG.getConstant(1, DL,
2830 LL.getValueType()));
2831 AddToWorklist(ADDNode.getNode());
2832 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2833 DAG.getConstant(2, DL, LL.getValueType()),
2836 // canonicalize equivalent to ll == rl
2837 if (LL == RR && LR == RL) {
2838 Op1 = ISD::getSetCCSwappedOperands(Op1);
2841 if (LL == RL && LR == RR) {
2842 bool isInteger = LL.getValueType().isInteger();
2843 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2844 if (Result != ISD::SETCC_INVALID &&
2845 (!LegalOperations ||
2846 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2847 TLI.isOperationLegal(ISD::SETCC,
2848 getSetCCResultType(N0.getSimpleValueType())))))
2849 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2854 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2855 VT.getSizeInBits() <= 64) {
2856 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2857 APInt ADDC = ADDI->getAPIntValue();
2858 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2859 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2860 // immediate for an add, but it is legal if its top c2 bits are set,
2861 // transform the ADD so the immediate doesn't need to be materialized
2863 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2864 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2865 SRLI->getZExtValue());
2866 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2868 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2871 DAG.getNode(ISD::ADD, DL, VT,
2872 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2873 CombineTo(N0.getNode(), NewAdd);
2874 // Return N so it doesn't get rechecked!
2875 return SDValue(LocReference, 0);
2886 SDValue DAGCombiner::visitAND(SDNode *N) {
2887 SDValue N0 = N->getOperand(0);
2888 SDValue N1 = N->getOperand(1);
2889 EVT VT = N1.getValueType();
2892 if (VT.isVector()) {
2893 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2896 // fold (and x, 0) -> 0, vector edition
2897 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2898 // do not return N0, because undef node may exist in N0
2899 return DAG.getConstant(
2900 APInt::getNullValue(
2901 N0.getValueType().getScalarType().getSizeInBits()),
2902 SDLoc(N), N0.getValueType());
2903 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2904 // do not return N1, because undef node may exist in N1
2905 return DAG.getConstant(
2906 APInt::getNullValue(
2907 N1.getValueType().getScalarType().getSizeInBits()),
2908 SDLoc(N), N1.getValueType());
2910 // fold (and x, -1) -> x, vector edition
2911 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2913 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2917 // fold (and c1, c2) -> c1&c2
2918 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2919 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2920 if (N0C && N1C && !N1C->isOpaque())
2921 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2922 // canonicalize constant to RHS
2923 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2924 !isConstantIntBuildVectorOrConstantInt(N1))
2925 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2926 // fold (and x, -1) -> x
2927 if (isAllOnesConstant(N1))
2929 // if (and x, c) is known to be zero, return 0
2930 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2931 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2932 APInt::getAllOnesValue(BitWidth)))
2933 return DAG.getConstant(0, SDLoc(N), VT);
2935 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2937 // fold (and (or x, C), D) -> D if (C & D) == D
2938 if (N1C && N0.getOpcode() == ISD::OR)
2939 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2940 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2942 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2943 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2944 SDValue N0Op0 = N0.getOperand(0);
2945 APInt Mask = ~N1C->getAPIntValue();
2946 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2947 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2948 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2949 N0.getValueType(), N0Op0);
2951 // Replace uses of the AND with uses of the Zero extend node.
2954 // We actually want to replace all uses of the any_extend with the
2955 // zero_extend, to avoid duplicating things. This will later cause this
2956 // AND to be folded.
2957 CombineTo(N0.getNode(), Zext);
2958 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2961 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2962 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2963 // already be zero by virtue of the width of the base type of the load.
2965 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2967 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2968 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2969 N0.getOpcode() == ISD::LOAD) {
2970 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2971 N0 : N0.getOperand(0) );
2973 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2974 // This can be a pure constant or a vector splat, in which case we treat the
2975 // vector as a scalar and use the splat value.
2976 APInt Constant = APInt::getNullValue(1);
2977 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2978 Constant = C->getAPIntValue();
2979 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2980 APInt SplatValue, SplatUndef;
2981 unsigned SplatBitSize;
2983 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2984 SplatBitSize, HasAnyUndefs);
2986 // Undef bits can contribute to a possible optimisation if set, so
2988 SplatValue |= SplatUndef;
2990 // The splat value may be something like "0x00FFFFFF", which means 0 for
2991 // the first vector value and FF for the rest, repeating. We need a mask
2992 // that will apply equally to all members of the vector, so AND all the
2993 // lanes of the constant together.
2994 EVT VT = Vector->getValueType(0);
2995 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2997 // If the splat value has been compressed to a bitlength lower
2998 // than the size of the vector lane, we need to re-expand it to
3000 if (BitWidth > SplatBitSize)
3001 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3002 SplatBitSize < BitWidth;
3003 SplatBitSize = SplatBitSize * 2)
3004 SplatValue |= SplatValue.shl(SplatBitSize);
3006 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3007 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3008 if (SplatBitSize % BitWidth == 0) {
3009 Constant = APInt::getAllOnesValue(BitWidth);
3010 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3011 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3016 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3017 // actually legal and isn't going to get expanded, else this is a false
3019 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3020 Load->getValueType(0),
3021 Load->getMemoryVT());
3023 // Resize the constant to the same size as the original memory access before
3024 // extension. If it is still the AllOnesValue then this AND is completely
3027 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3030 switch (Load->getExtensionType()) {
3031 default: B = false; break;
3032 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3034 case ISD::NON_EXTLOAD: B = true; break;
3037 if (B && Constant.isAllOnesValue()) {
3038 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3039 // preserve semantics once we get rid of the AND.
3040 SDValue NewLoad(Load, 0);
3041 if (Load->getExtensionType() == ISD::EXTLOAD) {
3042 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3043 Load->getValueType(0), SDLoc(Load),
3044 Load->getChain(), Load->getBasePtr(),
3045 Load->getOffset(), Load->getMemoryVT(),
3046 Load->getMemOperand());
3047 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3048 if (Load->getNumValues() == 3) {
3049 // PRE/POST_INC loads have 3 values.
3050 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3051 NewLoad.getValue(2) };
3052 CombineTo(Load, To, 3, true);
3054 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3058 // Fold the AND away, taking care not to fold to the old load node if we
3060 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3062 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3066 // fold (and (load x), 255) -> (zextload x, i8)
3067 // fold (and (extload x, i16), 255) -> (zextload x, i8)
3068 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3069 if (N1C && (N0.getOpcode() == ISD::LOAD ||
3070 (N0.getOpcode() == ISD::ANY_EXTEND &&
3071 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3072 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3073 LoadSDNode *LN0 = HasAnyExt
3074 ? cast<LoadSDNode>(N0.getOperand(0))
3075 : cast<LoadSDNode>(N0);
3076 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3077 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3078 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3079 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3080 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3081 EVT LoadedVT = LN0->getMemoryVT();
3082 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3084 if (ExtVT == LoadedVT &&
3085 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3089 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3090 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3091 LN0->getMemOperand());
3093 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3094 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3097 // Do not change the width of a volatile load.
3098 // Do not generate loads of non-round integer types since these can
3099 // be expensive (and would be wrong if the type is not byte sized).
3100 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3101 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3103 EVT PtrType = LN0->getOperand(1).getValueType();
3105 unsigned Alignment = LN0->getAlignment();
3106 SDValue NewPtr = LN0->getBasePtr();
3108 // For big endian targets, we need to add an offset to the pointer
3109 // to load the correct bytes. For little endian systems, we merely
3110 // need to read fewer bytes from the same pointer.
3111 if (DAG.getDataLayout().isBigEndian()) {
3112 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3113 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3114 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3116 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3117 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3118 Alignment = MinAlign(Alignment, PtrOff);
3121 AddToWorklist(NewPtr.getNode());
3124 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3125 LN0->getChain(), NewPtr,
3126 LN0->getPointerInfo(),
3127 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3128 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3130 CombineTo(LN0, Load, Load.getValue(1));
3131 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3137 if (SDValue Combined = visitANDLike(N0, N1, N))
3140 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3141 if (N0.getOpcode() == N1.getOpcode())
3142 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3145 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3146 // fold (and (sra)) -> (and (srl)) when possible.
3147 if (!VT.isVector() &&
3148 SimplifyDemandedBits(SDValue(N, 0)))
3149 return SDValue(N, 0);
3151 // fold (zext_inreg (extload x)) -> (zextload x)
3152 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3153 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3154 EVT MemVT = LN0->getMemoryVT();
3155 // If we zero all the possible extended bits, then we can turn this into
3156 // a zextload if we are running before legalize or the operation is legal.
3157 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3158 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3159 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3160 ((!LegalOperations && !LN0->isVolatile()) ||
3161 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3162 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3163 LN0->getChain(), LN0->getBasePtr(),
3164 MemVT, LN0->getMemOperand());
3166 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3167 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3170 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3171 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3173 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3174 EVT MemVT = LN0->getMemoryVT();
3175 // If we zero all the possible extended bits, then we can turn this into
3176 // a zextload if we are running before legalize or the operation is legal.
3177 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3178 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3179 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3180 ((!LegalOperations && !LN0->isVolatile()) ||
3181 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3182 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3183 LN0->getChain(), LN0->getBasePtr(),
3184 MemVT, LN0->getMemOperand());
3186 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3187 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3190 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3191 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3192 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3193 N0.getOperand(1), false);
3194 if (BSwap.getNode())
3201 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3202 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3203 bool DemandHighBits) {
3204 if (!LegalOperations)
3207 EVT VT = N->getValueType(0);
3208 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3210 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3213 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3214 bool LookPassAnd0 = false;
3215 bool LookPassAnd1 = false;
3216 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3218 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3220 if (N0.getOpcode() == ISD::AND) {
3221 if (!N0.getNode()->hasOneUse())
3223 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3224 if (!N01C || N01C->getZExtValue() != 0xFF00)
3226 N0 = N0.getOperand(0);
3227 LookPassAnd0 = true;
3230 if (N1.getOpcode() == ISD::AND) {
3231 if (!N1.getNode()->hasOneUse())
3233 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3234 if (!N11C || N11C->getZExtValue() != 0xFF)
3236 N1 = N1.getOperand(0);
3237 LookPassAnd1 = true;
3240 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3242 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3244 if (!N0.getNode()->hasOneUse() ||
3245 !N1.getNode()->hasOneUse())
3248 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3249 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3252 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3255 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3256 SDValue N00 = N0->getOperand(0);
3257 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3258 if (!N00.getNode()->hasOneUse())
3260 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3261 if (!N001C || N001C->getZExtValue() != 0xFF)
3263 N00 = N00.getOperand(0);
3264 LookPassAnd0 = true;
3267 SDValue N10 = N1->getOperand(0);
3268 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3269 if (!N10.getNode()->hasOneUse())
3271 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3272 if (!N101C || N101C->getZExtValue() != 0xFF00)
3274 N10 = N10.getOperand(0);
3275 LookPassAnd1 = true;
3281 // Make sure everything beyond the low halfword gets set to zero since the SRL
3282 // 16 will clear the top bits.
3283 unsigned OpSizeInBits = VT.getSizeInBits();
3284 if (DemandHighBits && OpSizeInBits > 16) {
3285 // If the left-shift isn't masked out then the only way this is a bswap is
3286 // if all bits beyond the low 8 are 0. In that case the entire pattern
3287 // reduces to a left shift anyway: leave it for other parts of the combiner.
3291 // However, if the right shift isn't masked out then it might be because
3292 // it's not needed. See if we can spot that too.
3293 if (!LookPassAnd1 &&
3294 !DAG.MaskedValueIsZero(
3295 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3299 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3300 if (OpSizeInBits > 16) {
3302 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3303 DAG.getConstant(OpSizeInBits - 16, DL,
3304 getShiftAmountTy(VT)));
3309 /// Return true if the specified node is an element that makes up a 32-bit
3310 /// packed halfword byteswap.
3311 /// ((x & 0x000000ff) << 8) |
3312 /// ((x & 0x0000ff00) >> 8) |
3313 /// ((x & 0x00ff0000) << 8) |
3314 /// ((x & 0xff000000) >> 8)
3315 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3316 if (!N.getNode()->hasOneUse())
3319 unsigned Opc = N.getOpcode();
3320 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3323 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3328 switch (N1C->getZExtValue()) {
3331 case 0xFF: Num = 0; break;
3332 case 0xFF00: Num = 1; break;
3333 case 0xFF0000: Num = 2; break;
3334 case 0xFF000000: Num = 3; break;
3337 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3338 SDValue N0 = N.getOperand(0);
3339 if (Opc == ISD::AND) {
3340 if (Num == 0 || Num == 2) {
3342 // (x >> 8) & 0xff0000
3343 if (N0.getOpcode() != ISD::SRL)
3345 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3346 if (!C || C->getZExtValue() != 8)
3349 // (x << 8) & 0xff00
3350 // (x << 8) & 0xff000000
3351 if (N0.getOpcode() != ISD::SHL)
3353 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3354 if (!C || C->getZExtValue() != 8)
3357 } else if (Opc == ISD::SHL) {
3359 // (x & 0xff0000) << 8
3360 if (Num != 0 && Num != 2)
3362 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3363 if (!C || C->getZExtValue() != 8)
3365 } else { // Opc == ISD::SRL
3366 // (x & 0xff00) >> 8
3367 // (x & 0xff000000) >> 8
3368 if (Num != 1 && Num != 3)
3370 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3371 if (!C || C->getZExtValue() != 8)
3378 Parts[Num] = N0.getOperand(0).getNode();
3382 /// Match a 32-bit packed halfword bswap. That is
3383 /// ((x & 0x000000ff) << 8) |
3384 /// ((x & 0x0000ff00) >> 8) |
3385 /// ((x & 0x00ff0000) << 8) |
3386 /// ((x & 0xff000000) >> 8)
3387 /// => (rotl (bswap x), 16)
3388 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3389 if (!LegalOperations)
3392 EVT VT = N->getValueType(0);
3395 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3399 // (or (or (and), (and)), (or (and), (and)))
3400 // (or (or (or (and), (and)), (and)), (and))
3401 if (N0.getOpcode() != ISD::OR)
3403 SDValue N00 = N0.getOperand(0);
3404 SDValue N01 = N0.getOperand(1);
3405 SDNode *Parts[4] = {};
3407 if (N1.getOpcode() == ISD::OR &&
3408 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3409 // (or (or (and), (and)), (or (and), (and)))
3410 SDValue N000 = N00.getOperand(0);
3411 if (!isBSwapHWordElement(N000, Parts))
3414 SDValue N001 = N00.getOperand(1);
3415 if (!isBSwapHWordElement(N001, Parts))
3417 SDValue N010 = N01.getOperand(0);
3418 if (!isBSwapHWordElement(N010, Parts))
3420 SDValue N011 = N01.getOperand(1);
3421 if (!isBSwapHWordElement(N011, Parts))
3424 // (or (or (or (and), (and)), (and)), (and))
3425 if (!isBSwapHWordElement(N1, Parts))
3427 if (!isBSwapHWordElement(N01, Parts))
3429 if (N00.getOpcode() != ISD::OR)
3431 SDValue N000 = N00.getOperand(0);
3432 if (!isBSwapHWordElement(N000, Parts))
3434 SDValue N001 = N00.getOperand(1);
3435 if (!isBSwapHWordElement(N001, Parts))
3439 // Make sure the parts are all coming from the same node.
3440 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3444 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3445 SDValue(Parts[0], 0));
3447 // Result of the bswap should be rotated by 16. If it's not legal, then
3448 // do (x << 16) | (x >> 16).
3449 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3450 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3451 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3452 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3453 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3454 return DAG.getNode(ISD::OR, DL, VT,
3455 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3456 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3459 /// This contains all DAGCombine rules which reduce two values combined by
3460 /// an Or operation to a single value \see visitANDLike().
3461 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3462 EVT VT = N1.getValueType();
3463 // fold (or x, undef) -> -1
3464 if (!LegalOperations &&
3465 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3466 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3467 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3468 SDLoc(LocReference), VT);
3470 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3471 SDValue LL, LR, RL, RR, CC0, CC1;
3472 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3473 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3474 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3476 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3477 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3478 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3479 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3480 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3481 LR.getValueType(), LL, RL);
3482 AddToWorklist(ORNode.getNode());
3483 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3485 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3486 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3487 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3488 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3489 LR.getValueType(), LL, RL);
3490 AddToWorklist(ANDNode.getNode());
3491 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3494 // canonicalize equivalent to ll == rl
3495 if (LL == RR && LR == RL) {
3496 Op1 = ISD::getSetCCSwappedOperands(Op1);
3499 if (LL == RL && LR == RR) {
3500 bool isInteger = LL.getValueType().isInteger();
3501 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3502 if (Result != ISD::SETCC_INVALID &&
3503 (!LegalOperations ||
3504 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3505 TLI.isOperationLegal(ISD::SETCC,
3506 getSetCCResultType(N0.getValueType())))))
3507 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3512 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3513 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3514 // Don't increase # computations.
3515 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3516 // We can only do this xform if we know that bits from X that are set in C2
3517 // but not in C1 are already zero. Likewise for Y.
3518 if (const ConstantSDNode *N0O1C =
3519 getAsNonOpaqueConstant(N0.getOperand(1))) {
3520 if (const ConstantSDNode *N1O1C =
3521 getAsNonOpaqueConstant(N1.getOperand(1))) {
3522 // We can only do this xform if we know that bits from X that are set in
3523 // C2 but not in C1 are already zero. Likewise for Y.
3524 const APInt &LHSMask = N0O1C->getAPIntValue();
3525 const APInt &RHSMask = N1O1C->getAPIntValue();
3527 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3528 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3529 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3530 N0.getOperand(0), N1.getOperand(0));
3531 SDLoc DL(LocReference);
3532 return DAG.getNode(ISD::AND, DL, VT, X,
3533 DAG.getConstant(LHSMask | RHSMask, DL, VT));
3539 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3540 if (N0.getOpcode() == ISD::AND &&
3541 N1.getOpcode() == ISD::AND &&
3542 N0.getOperand(0) == N1.getOperand(0) &&
3543 // Don't increase # computations.
3544 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3545 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3546 N0.getOperand(1), N1.getOperand(1));
3547 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3553 SDValue DAGCombiner::visitOR(SDNode *N) {
3554 SDValue N0 = N->getOperand(0);
3555 SDValue N1 = N->getOperand(1);
3556 EVT VT = N1.getValueType();
3559 if (VT.isVector()) {
3560 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3563 // fold (or x, 0) -> x, vector edition
3564 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3566 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3569 // fold (or x, -1) -> -1, vector edition
3570 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3571 // do not return N0, because undef node may exist in N0
3572 return DAG.getConstant(
3573 APInt::getAllOnesValue(
3574 N0.getValueType().getScalarType().getSizeInBits()),
3575 SDLoc(N), N0.getValueType());
3576 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3577 // do not return N1, because undef node may exist in N1
3578 return DAG.getConstant(
3579 APInt::getAllOnesValue(
3580 N1.getValueType().getScalarType().getSizeInBits()),
3581 SDLoc(N), N1.getValueType());
3583 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3584 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3585 // Do this only if the resulting shuffle is legal.
3586 if (isa<ShuffleVectorSDNode>(N0) &&
3587 isa<ShuffleVectorSDNode>(N1) &&
3588 // Avoid folding a node with illegal type.
3589 TLI.isTypeLegal(VT) &&
3590 N0->getOperand(1) == N1->getOperand(1) &&
3591 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3592 bool CanFold = true;
3593 unsigned NumElts = VT.getVectorNumElements();
3594 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3595 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3596 // We construct two shuffle masks:
3597 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3598 // and N1 as the second operand.
3599 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3600 // and N0 as the second operand.
3601 // We do this because OR is commutable and therefore there might be
3602 // two ways to fold this node into a shuffle.
3603 SmallVector<int,4> Mask1;
3604 SmallVector<int,4> Mask2;
3606 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3607 int M0 = SV0->getMaskElt(i);
3608 int M1 = SV1->getMaskElt(i);
3610 // Both shuffle indexes are undef. Propagate Undef.
3611 if (M0 < 0 && M1 < 0) {
3612 Mask1.push_back(M0);
3613 Mask2.push_back(M0);
3617 if (M0 < 0 || M1 < 0 ||
3618 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3619 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3624 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3625 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3629 // Fold this sequence only if the resulting shuffle is 'legal'.
3630 if (TLI.isShuffleMaskLegal(Mask1, VT))
3631 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3632 N1->getOperand(0), &Mask1[0]);
3633 if (TLI.isShuffleMaskLegal(Mask2, VT))
3634 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3635 N0->getOperand(0), &Mask2[0]);
3640 // fold (or c1, c2) -> c1|c2
3641 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3642 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3643 if (N0C && N1C && !N1C->isOpaque())
3644 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3645 // canonicalize constant to RHS
3646 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3647 !isConstantIntBuildVectorOrConstantInt(N1))
3648 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3649 // fold (or x, 0) -> x
3650 if (isNullConstant(N1))
3652 // fold (or x, -1) -> -1
3653 if (isAllOnesConstant(N1))
3655 // fold (or x, c) -> c iff (x & ~c) == 0
3656 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3659 if (SDValue Combined = visitORLike(N0, N1, N))
3662 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3663 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3665 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3669 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3671 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3672 // iff (c1 & c2) == 0.
3673 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3674 isa<ConstantSDNode>(N0.getOperand(1))) {
3675 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3676 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3677 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3680 ISD::AND, SDLoc(N), VT,
3681 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3685 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3686 if (N0.getOpcode() == N1.getOpcode())
3687 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3690 // See if this is some rotate idiom.
3691 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3692 return SDValue(Rot, 0);
3694 // Simplify the operands using demanded-bits information.
3695 if (!VT.isVector() &&
3696 SimplifyDemandedBits(SDValue(N, 0)))
3697 return SDValue(N, 0);
3702 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3703 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3704 if (Op.getOpcode() == ISD::AND) {
3705 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3706 Mask = Op.getOperand(1);
3707 Op = Op.getOperand(0);
3713 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3721 // Return true if we can prove that, whenever Neg and Pos are both in the
3722 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3723 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3725 // (or (shift1 X, Neg), (shift2 X, Pos))
3727 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3728 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3729 // to consider shift amounts with defined behavior.
3730 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3731 // If OpSize is a power of 2 then:
3733 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3734 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3736 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3737 // for the stronger condition:
3739 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3741 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3742 // we can just replace Neg with Neg' for the rest of the function.
3744 // In other cases we check for the even stronger condition:
3746 // Neg == OpSize - Pos [B]
3748 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3749 // behavior if Pos == 0 (and consequently Neg == OpSize).
3751 // We could actually use [A] whenever OpSize is a power of 2, but the
3752 // only extra cases that it would match are those uninteresting ones
3753 // where Neg and Pos are never in range at the same time. E.g. for
3754 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3755 // as well as (sub 32, Pos), but:
3757 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3759 // always invokes undefined behavior for 32-bit X.
3761 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3762 unsigned MaskLoBits = 0;
3763 if (Neg.getOpcode() == ISD::AND &&
3764 isPowerOf2_64(OpSize) &&
3765 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3766 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3767 Neg = Neg.getOperand(0);
3768 MaskLoBits = Log2_64(OpSize);
3771 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3772 if (Neg.getOpcode() != ISD::SUB)
3774 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3777 SDValue NegOp1 = Neg.getOperand(1);
3779 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3780 // Pos'. The truncation is redundant for the purpose of the equality.
3782 Pos.getOpcode() == ISD::AND &&
3783 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3784 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3785 Pos = Pos.getOperand(0);
3787 // The condition we need is now:
3789 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3791 // If NegOp1 == Pos then we need:
3793 // OpSize & Mask == NegC & Mask
3795 // (because "x & Mask" is a truncation and distributes through subtraction).
3798 Width = NegC->getAPIntValue();
3799 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3800 // Then the condition we want to prove becomes:
3802 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3804 // which, again because "x & Mask" is a truncation, becomes:
3806 // NegC & Mask == (OpSize - PosC) & Mask
3807 // OpSize & Mask == (NegC + PosC) & Mask
3808 else if (Pos.getOpcode() == ISD::ADD &&
3809 Pos.getOperand(0) == NegOp1 &&
3810 Pos.getOperand(1).getOpcode() == ISD::Constant)
3811 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3812 NegC->getAPIntValue());
3816 // Now we just need to check that OpSize & Mask == Width & Mask.
3818 // Opsize & Mask is 0 since Mask is Opsize - 1.
3819 return Width.getLoBits(MaskLoBits) == 0;
3820 return Width == OpSize;
3823 // A subroutine of MatchRotate used once we have found an OR of two opposite
3824 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3825 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3826 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3827 // Neg with outer conversions stripped away.
3828 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3829 SDValue Neg, SDValue InnerPos,
3830 SDValue InnerNeg, unsigned PosOpcode,
3831 unsigned NegOpcode, SDLoc DL) {
3832 // fold (or (shl x, (*ext y)),
3833 // (srl x, (*ext (sub 32, y)))) ->
3834 // (rotl x, y) or (rotr x, (sub 32, y))
3836 // fold (or (shl x, (*ext (sub 32, y))),
3837 // (srl x, (*ext y))) ->
3838 // (rotr x, y) or (rotl x, (sub 32, y))
3839 EVT VT = Shifted.getValueType();
3840 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3841 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3842 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3843 HasPos ? Pos : Neg).getNode();
3849 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3850 // idioms for rotate, and if the target supports rotation instructions, generate
3852 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3853 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3854 EVT VT = LHS.getValueType();
3855 if (!TLI.isTypeLegal(VT)) return nullptr;
3857 // The target must have at least one rotate flavor.
3858 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3859 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3860 if (!HasROTL && !HasROTR) return nullptr;
3862 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3863 SDValue LHSShift; // The shift.
3864 SDValue LHSMask; // AND value if any.
3865 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3866 return nullptr; // Not part of a rotate.
3868 SDValue RHSShift; // The shift.
3869 SDValue RHSMask; // AND value if any.
3870 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3871 return nullptr; // Not part of a rotate.
3873 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3874 return nullptr; // Not shifting the same value.
3876 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3877 return nullptr; // Shifts must disagree.
3879 // Canonicalize shl to left side in a shl/srl pair.
3880 if (RHSShift.getOpcode() == ISD::SHL) {
3881 std::swap(LHS, RHS);
3882 std::swap(LHSShift, RHSShift);
3883 std::swap(LHSMask , RHSMask );
3886 unsigned OpSizeInBits = VT.getSizeInBits();
3887 SDValue LHSShiftArg = LHSShift.getOperand(0);
3888 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3889 SDValue RHSShiftArg = RHSShift.getOperand(0);
3890 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3892 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3893 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3894 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3895 RHSShiftAmt.getOpcode() == ISD::Constant) {
3896 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3897 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3898 if ((LShVal + RShVal) != OpSizeInBits)
3901 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3902 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3904 // If there is an AND of either shifted operand, apply it to the result.
3905 if (LHSMask.getNode() || RHSMask.getNode()) {
3906 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3908 if (LHSMask.getNode()) {
3909 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3910 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3912 if (RHSMask.getNode()) {
3913 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3914 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3917 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3920 return Rot.getNode();
3923 // If there is a mask here, and we have a variable shift, we can't be sure
3924 // that we're masking out the right stuff.
3925 if (LHSMask.getNode() || RHSMask.getNode())
3928 // If the shift amount is sign/zext/any-extended just peel it off.
3929 SDValue LExtOp0 = LHSShiftAmt;
3930 SDValue RExtOp0 = RHSShiftAmt;
3931 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3932 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3933 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3934 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3935 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3936 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3937 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3938 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3939 LExtOp0 = LHSShiftAmt.getOperand(0);
3940 RExtOp0 = RHSShiftAmt.getOperand(0);
3943 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3944 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3948 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3949 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3956 SDValue DAGCombiner::visitXOR(SDNode *N) {
3957 SDValue N0 = N->getOperand(0);
3958 SDValue N1 = N->getOperand(1);
3959 EVT VT = N0.getValueType();
3962 if (VT.isVector()) {
3963 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3966 // fold (xor x, 0) -> x, vector edition
3967 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3969 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3973 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3974 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3975 return DAG.getConstant(0, SDLoc(N), VT);
3976 // fold (xor x, undef) -> undef
3977 if (N0.getOpcode() == ISD::UNDEF)
3979 if (N1.getOpcode() == ISD::UNDEF)
3981 // fold (xor c1, c2) -> c1^c2
3982 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3983 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3985 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3986 // canonicalize constant to RHS
3987 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3988 !isConstantIntBuildVectorOrConstantInt(N1))
3989 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3990 // fold (xor x, 0) -> x
3991 if (isNullConstant(N1))
3994 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
3997 // fold !(x cc y) -> (x !cc y)
3998 SDValue LHS, RHS, CC;
3999 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4000 bool isInt = LHS.getValueType().isInteger();
4001 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4004 if (!LegalOperations ||
4005 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4006 switch (N0.getOpcode()) {
4008 llvm_unreachable("Unhandled SetCC Equivalent!");
4010 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4011 case ISD::SELECT_CC:
4012 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4013 N0.getOperand(3), NotCC);
4018 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4019 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4020 N0.getNode()->hasOneUse() &&
4021 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4022 SDValue V = N0.getOperand(0);
4024 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4025 DAG.getConstant(1, DL, V.getValueType()));
4026 AddToWorklist(V.getNode());
4027 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4030 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4031 if (isOneConstant(N1) && VT == MVT::i1 &&
4032 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4033 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4034 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4035 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4036 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4037 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4038 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4039 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4042 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4043 if (isAllOnesConstant(N1) &&
4044 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4045 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4046 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4047 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4048 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4049 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4050 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4051 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4054 // fold (xor (and x, y), y) -> (and (not x), y)
4055 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4056 N0->getOperand(1) == N1) {
4057 SDValue X = N0->getOperand(0);
4058 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4059 AddToWorklist(NotX.getNode());
4060 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4062 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4063 if (N1C && N0.getOpcode() == ISD::XOR) {
4064 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4066 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4067 DAG.getConstant(N1C->getAPIntValue() ^
4068 N00C->getAPIntValue(), DL, VT));
4070 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4072 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4073 DAG.getConstant(N1C->getAPIntValue() ^
4074 N01C->getAPIntValue(), DL, VT));
4077 // fold (xor x, x) -> 0
4079 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4081 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4082 // Here is a concrete example of this equivalence:
4084 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
4085 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4089 // i16 ~1 == 0b1111111111111110
4090 // i16 rol(~1, 14) == 0b1011111111111111
4092 // Some additional tips to help conceptualize this transform:
4093 // - Try to see the operation as placing a single zero in a value of all ones.
4094 // - There exists no value for x which would allow the result to contain zero.
4095 // - Values of x larger than the bitwidth are undefined and do not require a
4096 // consistent result.
4097 // - Pushing the zero left requires shifting one bits in from the right.
4098 // A rotate left of ~1 is a nice way of achieving the desired result.
4099 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4100 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4102 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4106 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4107 if (N0.getOpcode() == N1.getOpcode())
4108 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4111 // Simplify the expression using non-local knowledge.
4112 if (!VT.isVector() &&
4113 SimplifyDemandedBits(SDValue(N, 0)))
4114 return SDValue(N, 0);
4119 /// Handle transforms common to the three shifts, when the shift amount is a
4121 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4122 SDNode *LHS = N->getOperand(0).getNode();
4123 if (!LHS->hasOneUse()) return SDValue();
4125 // We want to pull some binops through shifts, so that we have (and (shift))
4126 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4127 // thing happens with address calculations, so it's important to canonicalize
4129 bool HighBitSet = false; // Can we transform this if the high bit is set?
4131 switch (LHS->getOpcode()) {
4132 default: return SDValue();
4135 HighBitSet = false; // We can only transform sra if the high bit is clear.
4138 HighBitSet = true; // We can only transform sra if the high bit is set.
4141 if (N->getOpcode() != ISD::SHL)
4142 return SDValue(); // only shl(add) not sr[al](add).
4143 HighBitSet = false; // We can only transform sra if the high bit is clear.
4147 // We require the RHS of the binop to be a constant and not opaque as well.
4148 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4149 if (!BinOpCst) return SDValue();
4151 // FIXME: disable this unless the input to the binop is a shift by a constant.
4152 // If it is not a shift, it pessimizes some common cases like:
4154 // void foo(int *X, int i) { X[i & 1235] = 1; }
4155 // int bar(int *X, int i) { return X[i & 255]; }
4156 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4157 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4158 BinOpLHSVal->getOpcode() != ISD::SRA &&
4159 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4160 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4163 EVT VT = N->getValueType(0);
4165 // If this is a signed shift right, and the high bit is modified by the
4166 // logical operation, do not perform the transformation. The highBitSet
4167 // boolean indicates the value of the high bit of the constant which would
4168 // cause it to be modified for this operation.
4169 if (N->getOpcode() == ISD::SRA) {
4170 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4171 if (BinOpRHSSignSet != HighBitSet)
4175 if (!TLI.isDesirableToCommuteWithShift(LHS))
4178 // Fold the constants, shifting the binop RHS by the shift amount.
4179 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4181 LHS->getOperand(1), N->getOperand(1));
4182 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4184 // Create the new shift.
4185 SDValue NewShift = DAG.getNode(N->getOpcode(),
4186 SDLoc(LHS->getOperand(0)),
4187 VT, LHS->getOperand(0), N->getOperand(1));
4189 // Create the new binop.
4190 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4193 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4194 assert(N->getOpcode() == ISD::TRUNCATE);
4195 assert(N->getOperand(0).getOpcode() == ISD::AND);
4197 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4198 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4199 SDValue N01 = N->getOperand(0).getOperand(1);
4201 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4202 if (!N01C->isOpaque()) {
4203 EVT TruncVT = N->getValueType(0);
4204 SDValue N00 = N->getOperand(0).getOperand(0);
4205 APInt TruncC = N01C->getAPIntValue();
4206 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4209 return DAG.getNode(ISD::AND, DL, TruncVT,
4210 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4211 DAG.getConstant(TruncC, DL, TruncVT));
4219 SDValue DAGCombiner::visitRotate(SDNode *N) {
4220 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4221 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4222 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4223 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4224 if (NewOp1.getNode())
4225 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4226 N->getOperand(0), NewOp1);
4231 SDValue DAGCombiner::visitSHL(SDNode *N) {
4232 SDValue N0 = N->getOperand(0);
4233 SDValue N1 = N->getOperand(1);
4234 EVT VT = N0.getValueType();
4235 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4238 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4239 if (VT.isVector()) {
4240 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4243 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4244 // If setcc produces all-one true value then:
4245 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4246 if (N1CV && N1CV->isConstant()) {
4247 if (N0.getOpcode() == ISD::AND) {
4248 SDValue N00 = N0->getOperand(0);
4249 SDValue N01 = N0->getOperand(1);
4250 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4252 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4253 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4254 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4255 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4257 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4260 N1C = isConstOrConstSplat(N1);
4265 // fold (shl c1, c2) -> c1<<c2
4266 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4267 if (N0C && N1C && !N1C->isOpaque())
4268 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4269 // fold (shl 0, x) -> 0
4270 if (isNullConstant(N0))
4272 // fold (shl x, c >= size(x)) -> undef
4273 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4274 return DAG.getUNDEF(VT);
4275 // fold (shl x, 0) -> x
4276 if (N1C && N1C->isNullValue())
4278 // fold (shl undef, x) -> 0
4279 if (N0.getOpcode() == ISD::UNDEF)
4280 return DAG.getConstant(0, SDLoc(N), VT);
4281 // if (shl x, c) is known to be zero, return 0
4282 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4283 APInt::getAllOnesValue(OpSizeInBits)))
4284 return DAG.getConstant(0, SDLoc(N), VT);
4285 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4286 if (N1.getOpcode() == ISD::TRUNCATE &&
4287 N1.getOperand(0).getOpcode() == ISD::AND) {
4288 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4289 if (NewOp1.getNode())
4290 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4293 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4294 return SDValue(N, 0);
4296 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4297 if (N1C && N0.getOpcode() == ISD::SHL) {
4298 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4299 uint64_t c1 = N0C1->getZExtValue();
4300 uint64_t c2 = N1C->getZExtValue();
4302 if (c1 + c2 >= OpSizeInBits)
4303 return DAG.getConstant(0, DL, VT);
4304 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4305 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4309 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4310 // For this to be valid, the second form must not preserve any of the bits
4311 // that are shifted out by the inner shift in the first form. This means
4312 // the outer shift size must be >= the number of bits added by the ext.
4313 // As a corollary, we don't care what kind of ext it is.
4314 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4315 N0.getOpcode() == ISD::ANY_EXTEND ||
4316 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4317 N0.getOperand(0).getOpcode() == ISD::SHL) {
4318 SDValue N0Op0 = N0.getOperand(0);
4319 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4320 uint64_t c1 = N0Op0C1->getZExtValue();
4321 uint64_t c2 = N1C->getZExtValue();
4322 EVT InnerShiftVT = N0Op0.getValueType();
4323 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4324 if (c2 >= OpSizeInBits - InnerShiftSize) {
4326 if (c1 + c2 >= OpSizeInBits)
4327 return DAG.getConstant(0, DL, VT);
4328 return DAG.getNode(ISD::SHL, DL, VT,
4329 DAG.getNode(N0.getOpcode(), DL, VT,
4330 N0Op0->getOperand(0)),
4331 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4336 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4337 // Only fold this if the inner zext has no other uses to avoid increasing
4338 // the total number of instructions.
4339 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4340 N0.getOperand(0).getOpcode() == ISD::SRL) {
4341 SDValue N0Op0 = N0.getOperand(0);
4342 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4343 uint64_t c1 = N0Op0C1->getZExtValue();
4344 if (c1 < VT.getScalarSizeInBits()) {
4345 uint64_t c2 = N1C->getZExtValue();
4347 SDValue NewOp0 = N0.getOperand(0);
4348 EVT CountVT = NewOp0.getOperand(1).getValueType();
4350 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4352 DAG.getConstant(c2, DL, CountVT));
4353 AddToWorklist(NewSHL.getNode());
4354 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4360 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
4361 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2
4362 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4363 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4364 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4365 uint64_t C1 = N0C1->getZExtValue();
4366 uint64_t C2 = N1C->getZExtValue();
4369 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4370 DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4371 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4372 DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4376 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4377 // (and (srl x, (sub c1, c2), MASK)
4378 // Only fold this if the inner shift has no other uses -- if it does, folding
4379 // this will increase the total number of instructions.
4380 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4381 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4382 uint64_t c1 = N0C1->getZExtValue();
4383 if (c1 < OpSizeInBits) {
4384 uint64_t c2 = N1C->getZExtValue();
4385 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4388 Mask = Mask.shl(c2 - c1);
4390 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4391 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4393 Mask = Mask.lshr(c1 - c2);
4395 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4396 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4399 return DAG.getNode(ISD::AND, DL, VT, Shift,
4400 DAG.getConstant(Mask, DL, VT));
4404 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4405 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4406 unsigned BitSize = VT.getScalarSizeInBits();
4408 SDValue HiBitsMask =
4409 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4410 BitSize - N1C->getZExtValue()),
4412 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4416 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4417 // Variant of version done on multiply, except mul by a power of 2 is turned
4420 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4421 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4422 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4423 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4424 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4425 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4428 if (N1C && !N1C->isOpaque())
4429 if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4435 SDValue DAGCombiner::visitSRA(SDNode *N) {
4436 SDValue N0 = N->getOperand(0);
4437 SDValue N1 = N->getOperand(1);
4438 EVT VT = N0.getValueType();
4439 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4442 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4443 if (VT.isVector()) {
4444 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4447 N1C = isConstOrConstSplat(N1);
4450 // fold (sra c1, c2) -> (sra c1, c2)
4451 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4452 if (N0C && N1C && !N1C->isOpaque())
4453 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4454 // fold (sra 0, x) -> 0
4455 if (isNullConstant(N0))
4457 // fold (sra -1, x) -> -1
4458 if (isAllOnesConstant(N0))
4460 // fold (sra x, (setge c, size(x))) -> undef
4461 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4462 return DAG.getUNDEF(VT);
4463 // fold (sra x, 0) -> x
4464 if (N1C && N1C->isNullValue())
4466 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4468 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4469 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4470 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4472 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4473 ExtVT, VT.getVectorNumElements());
4474 if ((!LegalOperations ||
4475 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4476 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4477 N0.getOperand(0), DAG.getValueType(ExtVT));
4480 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4481 if (N1C && N0.getOpcode() == ISD::SRA) {
4482 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4483 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4484 if (Sum >= OpSizeInBits)
4485 Sum = OpSizeInBits - 1;
4487 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4488 DAG.getConstant(Sum, DL, N1.getValueType()));
4492 // fold (sra (shl X, m), (sub result_size, n))
4493 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4494 // result_size - n != m.
4495 // If truncate is free for the target sext(shl) is likely to result in better
4497 if (N0.getOpcode() == ISD::SHL && N1C) {
4498 // Get the two constanst of the shifts, CN0 = m, CN = n.
4499 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4501 LLVMContext &Ctx = *DAG.getContext();
4502 // Determine what the truncate's result bitsize and type would be.
4503 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4506 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4508 // Determine the residual right-shift amount.
4509 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4511 // If the shift is not a no-op (in which case this should be just a sign
4512 // extend already), the truncated to type is legal, sign_extend is legal
4513 // on that type, and the truncate to that type is both legal and free,
4514 // perform the transform.
4515 if ((ShiftAmt > 0) &&
4516 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4517 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4518 TLI.isTruncateFree(VT, TruncVT)) {
4521 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4522 getShiftAmountTy(N0.getOperand(0).getValueType()));
4523 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4524 N0.getOperand(0), Amt);
4525 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4527 return DAG.getNode(ISD::SIGN_EXTEND, DL,
4528 N->getValueType(0), Trunc);
4533 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4534 if (N1.getOpcode() == ISD::TRUNCATE &&
4535 N1.getOperand(0).getOpcode() == ISD::AND) {
4536 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4537 if (NewOp1.getNode())
4538 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4541 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4542 // if c1 is equal to the number of bits the trunc removes
4543 if (N0.getOpcode() == ISD::TRUNCATE &&
4544 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4545 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4546 N0.getOperand(0).hasOneUse() &&
4547 N0.getOperand(0).getOperand(1).hasOneUse() &&
4549 SDValue N0Op0 = N0.getOperand(0);
4550 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4551 unsigned LargeShiftVal = LargeShift->getZExtValue();
4552 EVT LargeVT = N0Op0.getValueType();
4554 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4557 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4558 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4559 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4560 N0Op0.getOperand(0), Amt);
4561 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4566 // Simplify, based on bits shifted out of the LHS.
4567 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4568 return SDValue(N, 0);
4571 // If the sign bit is known to be zero, switch this to a SRL.
4572 if (DAG.SignBitIsZero(N0))
4573 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4575 if (N1C && !N1C->isOpaque())
4576 if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4582 SDValue DAGCombiner::visitSRL(SDNode *N) {
4583 SDValue N0 = N->getOperand(0);
4584 SDValue N1 = N->getOperand(1);
4585 EVT VT = N0.getValueType();
4586 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4589 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4590 if (VT.isVector()) {
4591 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4594 N1C = isConstOrConstSplat(N1);
4597 // fold (srl c1, c2) -> c1 >>u c2
4598 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4599 if (N0C && N1C && !N1C->isOpaque())
4600 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4601 // fold (srl 0, x) -> 0
4602 if (isNullConstant(N0))
4604 // fold (srl x, c >= size(x)) -> undef
4605 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4606 return DAG.getUNDEF(VT);
4607 // fold (srl x, 0) -> x
4608 if (N1C && N1C->isNullValue())
4610 // if (srl x, c) is known to be zero, return 0
4611 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4612 APInt::getAllOnesValue(OpSizeInBits)))
4613 return DAG.getConstant(0, SDLoc(N), VT);
4615 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4616 if (N1C && N0.getOpcode() == ISD::SRL) {
4617 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4618 uint64_t c1 = N01C->getZExtValue();
4619 uint64_t c2 = N1C->getZExtValue();
4621 if (c1 + c2 >= OpSizeInBits)
4622 return DAG.getConstant(0, DL, VT);
4623 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4624 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4628 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4629 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4630 N0.getOperand(0).getOpcode() == ISD::SRL &&
4631 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4633 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4634 uint64_t c2 = N1C->getZExtValue();
4635 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4636 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4637 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4638 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4639 if (c1 + OpSizeInBits == InnerShiftSize) {
4641 if (c1 + c2 >= InnerShiftSize)
4642 return DAG.getConstant(0, DL, VT);
4643 return DAG.getNode(ISD::TRUNCATE, DL, VT,
4644 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4645 N0.getOperand(0)->getOperand(0),
4646 DAG.getConstant(c1 + c2, DL,
4651 // fold (srl (shl x, c), c) -> (and x, cst2)
4652 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4653 unsigned BitSize = N0.getScalarValueSizeInBits();
4654 if (BitSize <= 64) {
4655 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4657 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4658 DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4662 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4663 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4664 // Shifting in all undef bits?
4665 EVT SmallVT = N0.getOperand(0).getValueType();
4666 unsigned BitSize = SmallVT.getScalarSizeInBits();
4667 if (N1C->getZExtValue() >= BitSize)
4668 return DAG.getUNDEF(VT);
4670 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4671 uint64_t ShiftAmt = N1C->getZExtValue();
4673 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4675 DAG.getConstant(ShiftAmt, DL0,
4676 getShiftAmountTy(SmallVT)));
4677 AddToWorklist(SmallShift.getNode());
4678 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4680 return DAG.getNode(ISD::AND, DL, VT,
4681 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4682 DAG.getConstant(Mask, DL, VT));
4686 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4687 // bit, which is unmodified by sra.
4688 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4689 if (N0.getOpcode() == ISD::SRA)
4690 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4693 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4694 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4695 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4696 APInt KnownZero, KnownOne;
4697 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4699 // If any of the input bits are KnownOne, then the input couldn't be all
4700 // zeros, thus the result of the srl will always be zero.
4701 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4703 // If all of the bits input the to ctlz node are known to be zero, then
4704 // the result of the ctlz is "32" and the result of the shift is one.
4705 APInt UnknownBits = ~KnownZero;
4706 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4708 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4709 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4710 // Okay, we know that only that the single bit specified by UnknownBits
4711 // could be set on input to the CTLZ node. If this bit is set, the SRL
4712 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4713 // to an SRL/XOR pair, which is likely to simplify more.
4714 unsigned ShAmt = UnknownBits.countTrailingZeros();
4715 SDValue Op = N0.getOperand(0);
4719 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4720 DAG.getConstant(ShAmt, DL,
4721 getShiftAmountTy(Op.getValueType())));
4722 AddToWorklist(Op.getNode());
4726 return DAG.getNode(ISD::XOR, DL, VT,
4727 Op, DAG.getConstant(1, DL, VT));
4731 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4732 if (N1.getOpcode() == ISD::TRUNCATE &&
4733 N1.getOperand(0).getOpcode() == ISD::AND) {
4734 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4735 if (NewOp1.getNode())
4736 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4739 // fold operands of srl based on knowledge that the low bits are not
4741 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4742 return SDValue(N, 0);
4744 if (N1C && !N1C->isOpaque()) {
4745 SDValue NewSRL = visitShiftByConstant(N, N1C);
4746 if (NewSRL.getNode())
4750 // Attempt to convert a srl of a load into a narrower zero-extending load.
4751 SDValue NarrowLoad = ReduceLoadWidth(N);
4752 if (NarrowLoad.getNode())
4755 // Here is a common situation. We want to optimize:
4758 // %b = and i32 %a, 2
4759 // %c = srl i32 %b, 1
4760 // brcond i32 %c ...
4766 // %c = setcc eq %b, 0
4769 // However when after the source operand of SRL is optimized into AND, the SRL
4770 // itself may not be optimized further. Look for it and add the BRCOND into
4772 if (N->hasOneUse()) {
4773 SDNode *Use = *N->use_begin();
4774 if (Use->getOpcode() == ISD::BRCOND)
4776 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4777 // Also look pass the truncate.
4778 Use = *Use->use_begin();
4779 if (Use->getOpcode() == ISD::BRCOND)
4787 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4788 SDValue N0 = N->getOperand(0);
4789 EVT VT = N->getValueType(0);
4791 // fold (bswap c1) -> c2
4792 if (isConstantIntBuildVectorOrConstantInt(N0))
4793 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4794 // fold (bswap (bswap x)) -> x
4795 if (N0.getOpcode() == ISD::BSWAP)
4796 return N0->getOperand(0);
4800 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4801 SDValue N0 = N->getOperand(0);
4802 EVT VT = N->getValueType(0);
4804 // fold (ctlz c1) -> c2
4805 if (isConstantIntBuildVectorOrConstantInt(N0))
4806 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4810 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4811 SDValue N0 = N->getOperand(0);
4812 EVT VT = N->getValueType(0);
4814 // fold (ctlz_zero_undef c1) -> c2
4815 if (isConstantIntBuildVectorOrConstantInt(N0))
4816 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4820 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4821 SDValue N0 = N->getOperand(0);
4822 EVT VT = N->getValueType(0);
4824 // fold (cttz c1) -> c2
4825 if (isConstantIntBuildVectorOrConstantInt(N0))
4826 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4830 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4831 SDValue N0 = N->getOperand(0);
4832 EVT VT = N->getValueType(0);
4834 // fold (cttz_zero_undef c1) -> c2
4835 if (isConstantIntBuildVectorOrConstantInt(N0))
4836 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4840 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4841 SDValue N0 = N->getOperand(0);
4842 EVT VT = N->getValueType(0);
4844 // fold (ctpop c1) -> c2
4845 if (isConstantIntBuildVectorOrConstantInt(N0))
4846 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4851 /// \brief Generate Min/Max node
4852 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4853 SDValue True, SDValue False,
4854 ISD::CondCode CC, const TargetLowering &TLI,
4855 SelectionDAG &DAG) {
4856 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4866 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4867 if (TLI.isOperationLegal(Opcode, VT))
4868 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4877 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4878 if (TLI.isOperationLegal(Opcode, VT))
4879 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4887 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4888 SDValue N0 = N->getOperand(0);
4889 SDValue N1 = N->getOperand(1);
4890 SDValue N2 = N->getOperand(2);
4891 EVT VT = N->getValueType(0);
4892 EVT VT0 = N0.getValueType();
4894 // fold (select C, X, X) -> X
4897 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4898 // fold (select true, X, Y) -> X
4899 // fold (select false, X, Y) -> Y
4900 return !N0C->isNullValue() ? N1 : N2;
4902 // fold (select C, 1, X) -> (or C, X)
4903 if (VT == MVT::i1 && isOneConstant(N1))
4904 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4905 // fold (select C, 0, 1) -> (xor C, 1)
4906 // We can't do this reliably if integer based booleans have different contents
4907 // to floating point based booleans. This is because we can't tell whether we
4908 // have an integer-based boolean or a floating-point-based boolean unless we
4909 // can find the SETCC that produced it and inspect its operands. This is
4910 // fairly easy if C is the SETCC node, but it can potentially be
4911 // undiscoverable (or not reasonably discoverable). For example, it could be
4912 // in another basic block or it could require searching a complicated
4914 if (VT.isInteger() &&
4915 (VT0 == MVT::i1 || (VT0.isInteger() &&
4916 TLI.getBooleanContents(false, false) ==
4917 TLI.getBooleanContents(false, true) &&
4918 TLI.getBooleanContents(false, false) ==
4919 TargetLowering::ZeroOrOneBooleanContent)) &&
4920 isNullConstant(N1) && isOneConstant(N2)) {
4924 return DAG.getNode(ISD::XOR, DL, VT0,
4925 N0, DAG.getConstant(1, DL, VT0));
4928 XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4929 N0, DAG.getConstant(1, DL0, VT0));
4930 AddToWorklist(XORNode.getNode());
4932 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4933 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4935 // fold (select C, 0, X) -> (and (not C), X)
4936 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4937 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4938 AddToWorklist(NOTNode.getNode());
4939 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4941 // fold (select C, X, 1) -> (or (not C), X)
4942 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
4943 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4944 AddToWorklist(NOTNode.getNode());
4945 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4947 // fold (select C, X, 0) -> (and C, X)
4948 if (VT == MVT::i1 && isNullConstant(N2))
4949 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4950 // fold (select X, X, Y) -> (or X, Y)
4951 // fold (select X, 1, Y) -> (or X, Y)
4952 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
4953 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4954 // fold (select X, Y, X) -> (and X, Y)
4955 // fold (select X, Y, 0) -> (and X, Y)
4956 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
4957 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4959 // If we can fold this based on the true/false value, do so.
4960 if (SimplifySelectOps(N, N1, N2))
4961 return SDValue(N, 0); // Don't revisit N.
4963 // fold selects based on a setcc into other things, such as min/max/abs
4964 if (N0.getOpcode() == ISD::SETCC) {
4965 // select x, y (fcmp lt x, y) -> fminnum x, y
4966 // select x, y (fcmp gt x, y) -> fmaxnum x, y
4968 // This is OK if we don't care about what happens if either operand is a
4972 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4973 // no signed zeros as well as no nans.
4974 const TargetOptions &Options = DAG.getTarget().Options;
4975 if (Options.UnsafeFPMath &&
4976 VT.isFloatingPoint() && N0.hasOneUse() &&
4977 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4978 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4981 combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4982 N1, N2, CC, TLI, DAG);
4987 if ((!LegalOperations &&
4988 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4989 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4990 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4991 N0.getOperand(0), N0.getOperand(1),
4992 N1, N2, N0.getOperand(2));
4993 return SimplifySelect(SDLoc(N), N0, N1, N2);
4996 if (VT0 == MVT::i1) {
4997 if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4998 // select (and Cond0, Cond1), X, Y
4999 // -> select Cond0, (select Cond1, X, Y), Y
5000 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5001 SDValue Cond0 = N0->getOperand(0);
5002 SDValue Cond1 = N0->getOperand(1);
5003 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5004 N1.getValueType(), Cond1, N1, N2);
5005 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5008 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5009 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5010 SDValue Cond0 = N0->getOperand(0);
5011 SDValue Cond1 = N0->getOperand(1);
5012 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5013 N1.getValueType(), Cond1, N1, N2);
5014 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5019 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5020 if (N1->getOpcode() == ISD::SELECT) {
5021 SDValue N1_0 = N1->getOperand(0);
5022 SDValue N1_1 = N1->getOperand(1);
5023 SDValue N1_2 = N1->getOperand(2);
5024 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5025 // Create the actual and node if we can generate good code for it.
5026 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
5027 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5029 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5032 // Otherwise see if we can optimize the "and" to a better pattern.
5033 if (SDValue Combined = visitANDLike(N0, N1_0, N))
5034 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5038 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5039 if (N2->getOpcode() == ISD::SELECT) {
5040 SDValue N2_0 = N2->getOperand(0);
5041 SDValue N2_1 = N2->getOperand(1);
5042 SDValue N2_2 = N2->getOperand(2);
5043 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5044 // Create the actual or node if we can generate good code for it.
5045 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
5046 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5048 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5051 // Otherwise see if we can optimize to a better pattern.
5052 if (SDValue Combined = visitORLike(N0, N2_0, N))
5053 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5063 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5066 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5068 // Split the inputs.
5069 SDValue Lo, Hi, LL, LH, RL, RH;
5070 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5071 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5073 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5074 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5076 return std::make_pair(Lo, Hi);
5079 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5080 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5081 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5083 SDValue Cond = N->getOperand(0);
5084 SDValue LHS = N->getOperand(1);
5085 SDValue RHS = N->getOperand(2);
5086 EVT VT = N->getValueType(0);
5087 int NumElems = VT.getVectorNumElements();
5088 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5089 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5090 Cond.getOpcode() == ISD::BUILD_VECTOR);
5092 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5093 // binary ones here.
5094 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5097 // We're sure we have an even number of elements due to the
5098 // concat_vectors we have as arguments to vselect.
5099 // Skip BV elements until we find one that's not an UNDEF
5100 // After we find an UNDEF element, keep looping until we get to half the
5101 // length of the BV and see if all the non-undef nodes are the same.
5102 ConstantSDNode *BottomHalf = nullptr;
5103 for (int i = 0; i < NumElems / 2; ++i) {
5104 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5107 if (BottomHalf == nullptr)
5108 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5109 else if (Cond->getOperand(i).getNode() != BottomHalf)
5113 // Do the same for the second half of the BuildVector
5114 ConstantSDNode *TopHalf = nullptr;
5115 for (int i = NumElems / 2; i < NumElems; ++i) {
5116 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5119 if (TopHalf == nullptr)
5120 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5121 else if (Cond->getOperand(i).getNode() != TopHalf)
5125 assert(TopHalf && BottomHalf &&
5126 "One half of the selector was all UNDEFs and the other was all the "
5127 "same value. This should have been addressed before this function.");
5129 ISD::CONCAT_VECTORS, dl, VT,
5130 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5131 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5134 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5136 if (Level >= AfterLegalizeTypes)
5139 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5140 SDValue Mask = MSC->getMask();
5141 SDValue Data = MSC->getValue();
5144 // If the MSCATTER data type requires splitting and the mask is provided by a
5145 // SETCC, then split both nodes and its operands before legalization. This
5146 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5147 // and enables future optimizations (e.g. min/max pattern matching on X86).
5148 if (Mask.getOpcode() != ISD::SETCC)
5151 // Check if any splitting is required.
5152 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5153 TargetLowering::TypeSplitVector)
5155 SDValue MaskLo, MaskHi, Lo, Hi;
5156 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5159 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5161 SDValue Chain = MSC->getChain();
5163 EVT MemoryVT = MSC->getMemoryVT();
5164 unsigned Alignment = MSC->getOriginalAlignment();
5166 EVT LoMemVT, HiMemVT;
5167 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5169 SDValue DataLo, DataHi;
5170 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5172 SDValue BasePtr = MSC->getBasePtr();
5173 SDValue IndexLo, IndexHi;
5174 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5176 MachineMemOperand *MMO = DAG.getMachineFunction().
5177 getMachineMemOperand(MSC->getPointerInfo(),
5178 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5179 Alignment, MSC->getAAInfo(), MSC->getRanges());
5181 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5182 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5185 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5186 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5189 AddToWorklist(Lo.getNode());
5190 AddToWorklist(Hi.getNode());
5192 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5195 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5197 if (Level >= AfterLegalizeTypes)
5200 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5201 SDValue Mask = MST->getMask();
5202 SDValue Data = MST->getValue();
5205 // If the MSTORE data type requires splitting and the mask is provided by a
5206 // SETCC, then split both nodes and its operands before legalization. This
5207 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5208 // and enables future optimizations (e.g. min/max pattern matching on X86).
5209 if (Mask.getOpcode() == ISD::SETCC) {
5211 // Check if any splitting is required.
5212 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5213 TargetLowering::TypeSplitVector)
5216 SDValue MaskLo, MaskHi, Lo, Hi;
5217 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5220 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5222 SDValue Chain = MST->getChain();
5223 SDValue Ptr = MST->getBasePtr();
5225 EVT MemoryVT = MST->getMemoryVT();
5226 unsigned Alignment = MST->getOriginalAlignment();
5228 // if Alignment is equal to the vector size,
5229 // take the half of it for the second part
5230 unsigned SecondHalfAlignment =
5231 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5232 Alignment/2 : Alignment;
5234 EVT LoMemVT, HiMemVT;
5235 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5237 SDValue DataLo, DataHi;
5238 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5240 MachineMemOperand *MMO = DAG.getMachineFunction().
5241 getMachineMemOperand(MST->getPointerInfo(),
5242 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5243 Alignment, MST->getAAInfo(), MST->getRanges());
5245 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5246 MST->isTruncatingStore());
5248 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5249 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5250 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5252 MMO = DAG.getMachineFunction().
5253 getMachineMemOperand(MST->getPointerInfo(),
5254 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5255 SecondHalfAlignment, MST->getAAInfo(),
5258 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5259 MST->isTruncatingStore());
5261 AddToWorklist(Lo.getNode());
5262 AddToWorklist(Hi.getNode());
5264 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5269 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5271 if (Level >= AfterLegalizeTypes)
5274 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5275 SDValue Mask = MGT->getMask();
5278 // If the MGATHER result requires splitting and the mask is provided by a
5279 // SETCC, then split both nodes and its operands before legalization. This
5280 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5281 // and enables future optimizations (e.g. min/max pattern matching on X86).
5283 if (Mask.getOpcode() != ISD::SETCC)
5286 EVT VT = N->getValueType(0);
5288 // Check if any splitting is required.
5289 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5290 TargetLowering::TypeSplitVector)
5293 SDValue MaskLo, MaskHi, Lo, Hi;
5294 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5296 SDValue Src0 = MGT->getValue();
5297 SDValue Src0Lo, Src0Hi;
5298 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5301 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5303 SDValue Chain = MGT->getChain();
5304 EVT MemoryVT = MGT->getMemoryVT();
5305 unsigned Alignment = MGT->getOriginalAlignment();
5307 EVT LoMemVT, HiMemVT;
5308 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5310 SDValue BasePtr = MGT->getBasePtr();
5311 SDValue Index = MGT->getIndex();
5312 SDValue IndexLo, IndexHi;
5313 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5315 MachineMemOperand *MMO = DAG.getMachineFunction().
5316 getMachineMemOperand(MGT->getPointerInfo(),
5317 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5318 Alignment, MGT->getAAInfo(), MGT->getRanges());
5320 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5321 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5324 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5325 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5328 AddToWorklist(Lo.getNode());
5329 AddToWorklist(Hi.getNode());
5331 // Build a factor node to remember that this load is independent of the
5333 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5336 // Legalized the chain result - switch anything that used the old chain to
5338 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5340 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5342 SDValue RetOps[] = { GatherRes, Chain };
5343 return DAG.getMergeValues(RetOps, DL);
5346 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5348 if (Level >= AfterLegalizeTypes)
5351 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5352 SDValue Mask = MLD->getMask();
5355 // If the MLOAD result requires splitting and the mask is provided by a
5356 // SETCC, then split both nodes and its operands before legalization. This
5357 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5358 // and enables future optimizations (e.g. min/max pattern matching on X86).
5360 if (Mask.getOpcode() == ISD::SETCC) {
5361 EVT VT = N->getValueType(0);
5363 // Check if any splitting is required.
5364 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5365 TargetLowering::TypeSplitVector)
5368 SDValue MaskLo, MaskHi, Lo, Hi;
5369 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5371 SDValue Src0 = MLD->getSrc0();
5372 SDValue Src0Lo, Src0Hi;
5373 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5376 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5378 SDValue Chain = MLD->getChain();
5379 SDValue Ptr = MLD->getBasePtr();
5380 EVT MemoryVT = MLD->getMemoryVT();
5381 unsigned Alignment = MLD->getOriginalAlignment();
5383 // if Alignment is equal to the vector size,
5384 // take the half of it for the second part
5385 unsigned SecondHalfAlignment =
5386 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5387 Alignment/2 : Alignment;
5389 EVT LoMemVT, HiMemVT;
5390 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5392 MachineMemOperand *MMO = DAG.getMachineFunction().
5393 getMachineMemOperand(MLD->getPointerInfo(),
5394 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5395 Alignment, MLD->getAAInfo(), MLD->getRanges());
5397 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5400 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5401 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5402 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5404 MMO = DAG.getMachineFunction().
5405 getMachineMemOperand(MLD->getPointerInfo(),
5406 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5407 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5409 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5412 AddToWorklist(Lo.getNode());
5413 AddToWorklist(Hi.getNode());
5415 // Build a factor node to remember that this load is independent of the
5417 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5420 // Legalized the chain result - switch anything that used the old chain to
5422 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5424 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5426 SDValue RetOps[] = { LoadRes, Chain };
5427 return DAG.getMergeValues(RetOps, DL);
5432 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5433 SDValue N0 = N->getOperand(0);
5434 SDValue N1 = N->getOperand(1);
5435 SDValue N2 = N->getOperand(2);
5438 // Canonicalize integer abs.
5439 // vselect (setg[te] X, 0), X, -X ->
5440 // vselect (setgt X, -1), X, -X ->
5441 // vselect (setl[te] X, 0), -X, X ->
5442 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5443 if (N0.getOpcode() == ISD::SETCC) {
5444 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5445 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5447 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5449 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5450 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5451 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5452 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5453 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5454 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5455 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5458 EVT VT = LHS.getValueType();
5459 SDValue Shift = DAG.getNode(
5460 ISD::SRA, DL, VT, LHS,
5461 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5462 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5463 AddToWorklist(Shift.getNode());
5464 AddToWorklist(Add.getNode());
5465 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5469 if (SimplifySelectOps(N, N1, N2))
5470 return SDValue(N, 0); // Don't revisit N.
5472 // If the VSELECT result requires splitting and the mask is provided by a
5473 // SETCC, then split both nodes and its operands before legalization. This
5474 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5475 // and enables future optimizations (e.g. min/max pattern matching on X86).
5476 if (N0.getOpcode() == ISD::SETCC) {
5477 EVT VT = N->getValueType(0);
5479 // Check if any splitting is required.
5480 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5481 TargetLowering::TypeSplitVector)
5484 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5485 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5486 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5487 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5489 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5490 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5492 // Add the new VSELECT nodes to the work list in case they need to be split
5494 AddToWorklist(Lo.getNode());
5495 AddToWorklist(Hi.getNode());
5497 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5500 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5501 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5503 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5504 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5507 // The ConvertSelectToConcatVector function is assuming both the above
5508 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5510 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5511 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5512 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5513 SDValue CV = ConvertSelectToConcatVector(N, DAG);
5521 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5522 SDValue N0 = N->getOperand(0);
5523 SDValue N1 = N->getOperand(1);
5524 SDValue N2 = N->getOperand(2);
5525 SDValue N3 = N->getOperand(3);
5526 SDValue N4 = N->getOperand(4);
5527 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5529 // fold select_cc lhs, rhs, x, x, cc -> x
5533 // Determine if the condition we're dealing with is constant
5534 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5535 N0, N1, CC, SDLoc(N), false);
5536 if (SCC.getNode()) {
5537 AddToWorklist(SCC.getNode());
5539 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5540 if (!SCCC->isNullValue())
5541 return N2; // cond always true -> true val
5543 return N3; // cond always false -> false val
5544 } else if (SCC->getOpcode() == ISD::UNDEF) {
5545 // When the condition is UNDEF, just return the first operand. This is
5546 // coherent the DAG creation, no setcc node is created in this case
5548 } else if (SCC.getOpcode() == ISD::SETCC) {
5549 // Fold to a simpler select_cc
5550 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5551 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5556 // If we can fold this based on the true/false value, do so.
5557 if (SimplifySelectOps(N, N2, N3))
5558 return SDValue(N, 0); // Don't revisit N.
5560 // fold select_cc into other things, such as min/max/abs
5561 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5564 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5565 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5566 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5570 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5571 /// a build_vector of constants.
5572 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5573 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5574 /// Vector extends are not folded if operations are legal; this is to
5575 /// avoid introducing illegal build_vector dag nodes.
5576 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5577 SelectionDAG &DAG, bool LegalTypes,
5578 bool LegalOperations) {
5579 unsigned Opcode = N->getOpcode();
5580 SDValue N0 = N->getOperand(0);
5581 EVT VT = N->getValueType(0);
5583 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5584 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5585 && "Expected EXTEND dag node in input!");
5587 // fold (sext c1) -> c1
5588 // fold (zext c1) -> c1
5589 // fold (aext c1) -> c1
5590 if (isa<ConstantSDNode>(N0))
5591 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5593 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5594 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5595 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5596 EVT SVT = VT.getScalarType();
5597 if (!(VT.isVector() &&
5598 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5599 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5602 // We can fold this node into a build_vector.
5603 unsigned VTBits = SVT.getSizeInBits();
5604 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5605 SmallVector<SDValue, 8> Elts;
5606 unsigned NumElts = VT.getVectorNumElements();
5609 for (unsigned i=0; i != NumElts; ++i) {
5610 SDValue Op = N0->getOperand(i);
5611 if (Op->getOpcode() == ISD::UNDEF) {
5612 Elts.push_back(DAG.getUNDEF(SVT));
5617 // Get the constant value and if needed trunc it to the size of the type.
5618 // Nodes like build_vector might have constants wider than the scalar type.
5619 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5620 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5621 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5623 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5626 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5629 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5630 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5631 // transformation. Returns true if extension are possible and the above
5632 // mentioned transformation is profitable.
5633 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5635 SmallVectorImpl<SDNode *> &ExtendNodes,
5636 const TargetLowering &TLI) {
5637 bool HasCopyToRegUses = false;
5638 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5639 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5640 UE = N0.getNode()->use_end();
5645 if (UI.getUse().getResNo() != N0.getResNo())
5647 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5648 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5649 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5650 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5651 // Sign bits will be lost after a zext.
5654 for (unsigned i = 0; i != 2; ++i) {
5655 SDValue UseOp = User->getOperand(i);
5658 if (!isa<ConstantSDNode>(UseOp))
5663 ExtendNodes.push_back(User);
5666 // If truncates aren't free and there are users we can't
5667 // extend, it isn't worthwhile.
5670 // Remember if this value is live-out.
5671 if (User->getOpcode() == ISD::CopyToReg)
5672 HasCopyToRegUses = true;
5675 if (HasCopyToRegUses) {
5676 bool BothLiveOut = false;
5677 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5679 SDUse &Use = UI.getUse();
5680 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5686 // Both unextended and extended values are live out. There had better be
5687 // a good reason for the transformation.
5688 return ExtendNodes.size();
5693 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5694 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5695 ISD::NodeType ExtType) {
5696 // Extend SetCC uses if necessary.
5697 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5698 SDNode *SetCC = SetCCs[i];
5699 SmallVector<SDValue, 4> Ops;
5701 for (unsigned j = 0; j != 2; ++j) {
5702 SDValue SOp = SetCC->getOperand(j);
5704 Ops.push_back(ExtLoad);
5706 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5709 Ops.push_back(SetCC->getOperand(2));
5710 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5714 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5715 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5716 SDValue N0 = N->getOperand(0);
5717 EVT DstVT = N->getValueType(0);
5718 EVT SrcVT = N0.getValueType();
5720 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5721 N->getOpcode() == ISD::ZERO_EXTEND) &&
5722 "Unexpected node type (not an extend)!");
5724 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5725 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5726 // (v8i32 (sext (v8i16 (load x))))
5728 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5729 // (v4i32 (sextload (x + 16)))))
5730 // Where uses of the original load, i.e.:
5732 // are replaced with:
5734 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5735 // (v4i32 (sextload (x + 16)))))))
5737 // This combine is only applicable to illegal, but splittable, vectors.
5738 // All legal types, and illegal non-vector types, are handled elsewhere.
5739 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5741 if (N0->getOpcode() != ISD::LOAD)
5744 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5746 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5747 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5748 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5751 SmallVector<SDNode *, 4> SetCCs;
5752 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5755 ISD::LoadExtType ExtType =
5756 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5758 // Try to split the vector types to get down to legal types.
5759 EVT SplitSrcVT = SrcVT;
5760 EVT SplitDstVT = DstVT;
5761 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5762 SplitSrcVT.getVectorNumElements() > 1) {
5763 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5764 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5767 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5771 const unsigned NumSplits =
5772 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5773 const unsigned Stride = SplitSrcVT.getStoreSize();
5774 SmallVector<SDValue, 4> Loads;
5775 SmallVector<SDValue, 4> Chains;
5777 SDValue BasePtr = LN0->getBasePtr();
5778 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5779 const unsigned Offset = Idx * Stride;
5780 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5782 SDValue SplitLoad = DAG.getExtLoad(
5783 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5784 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5785 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5786 Align, LN0->getAAInfo());
5788 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5789 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5791 Loads.push_back(SplitLoad.getValue(0));
5792 Chains.push_back(SplitLoad.getValue(1));
5795 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5796 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5798 CombineTo(N, NewValue);
5800 // Replace uses of the original load (before extension)
5801 // with a truncate of the concatenated sextloaded vectors.
5803 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5804 CombineTo(N0.getNode(), Trunc, NewChain);
5805 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5806 (ISD::NodeType)N->getOpcode());
5807 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5810 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5811 SDValue N0 = N->getOperand(0);
5812 EVT VT = N->getValueType(0);
5814 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5816 return SDValue(Res, 0);
5818 // fold (sext (sext x)) -> (sext x)
5819 // fold (sext (aext x)) -> (sext x)
5820 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5821 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5824 if (N0.getOpcode() == ISD::TRUNCATE) {
5825 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5826 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5827 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
5828 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5829 if (NarrowLoad.getNode() != N0.getNode()) {
5830 CombineTo(N0.getNode(), NarrowLoad);
5831 // CombineTo deleted the truncate, if needed, but not what's under it.
5834 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5837 // See if the value being truncated is already sign extended. If so, just
5838 // eliminate the trunc/sext pair.
5839 SDValue Op = N0.getOperand(0);
5840 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5841 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5842 unsigned DestBits = VT.getScalarType().getSizeInBits();
5843 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5845 if (OpBits == DestBits) {
5846 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5847 // bits, it is already ready.
5848 if (NumSignBits > DestBits-MidBits)
5850 } else if (OpBits < DestBits) {
5851 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5852 // bits, just sext from i32.
5853 if (NumSignBits > OpBits-MidBits)
5854 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5856 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5857 // bits, just truncate to i32.
5858 if (NumSignBits > OpBits-MidBits)
5859 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5862 // fold (sext (truncate x)) -> (sextinreg x).
5863 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5864 N0.getValueType())) {
5865 if (OpBits < DestBits)
5866 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5867 else if (OpBits > DestBits)
5868 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5869 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5870 DAG.getValueType(N0.getValueType()));
5874 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5875 // Only generate vector extloads when 1) they're legal, and 2) they are
5876 // deemed desirable by the target.
5877 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5878 ((!LegalOperations && !VT.isVector() &&
5879 !cast<LoadSDNode>(N0)->isVolatile()) ||
5880 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5881 bool DoXform = true;
5882 SmallVector<SDNode*, 4> SetCCs;
5883 if (!N0.hasOneUse())
5884 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5886 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5888 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5889 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5891 LN0->getBasePtr(), N0.getValueType(),
5892 LN0->getMemOperand());
5893 CombineTo(N, ExtLoad);
5894 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5895 N0.getValueType(), ExtLoad);
5896 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5897 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5899 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5903 // fold (sext (load x)) to multiple smaller sextloads.
5904 // Only on illegal but splittable vectors.
5905 if (SDValue ExtLoad = CombineExtLoad(N))
5908 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5909 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5910 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5911 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5912 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5913 EVT MemVT = LN0->getMemoryVT();
5914 if ((!LegalOperations && !LN0->isVolatile()) ||
5915 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5916 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5918 LN0->getBasePtr(), MemVT,
5919 LN0->getMemOperand());
5920 CombineTo(N, ExtLoad);
5921 CombineTo(N0.getNode(),
5922 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5923 N0.getValueType(), ExtLoad),
5924 ExtLoad.getValue(1));
5925 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5929 // fold (sext (and/or/xor (load x), cst)) ->
5930 // (and/or/xor (sextload x), (sext cst))
5931 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5932 N0.getOpcode() == ISD::XOR) &&
5933 isa<LoadSDNode>(N0.getOperand(0)) &&
5934 N0.getOperand(1).getOpcode() == ISD::Constant &&
5935 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5936 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5937 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5938 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5939 bool DoXform = true;
5940 SmallVector<SDNode*, 4> SetCCs;
5941 if (!N0.hasOneUse())
5942 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5945 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5946 LN0->getChain(), LN0->getBasePtr(),
5948 LN0->getMemOperand());
5949 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5950 Mask = Mask.sext(VT.getSizeInBits());
5952 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5953 ExtLoad, DAG.getConstant(Mask, DL, VT));
5954 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5955 SDLoc(N0.getOperand(0)),
5956 N0.getOperand(0).getValueType(), ExtLoad);
5958 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5959 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5961 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5966 if (N0.getOpcode() == ISD::SETCC) {
5967 EVT N0VT = N0.getOperand(0).getValueType();
5968 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5969 // Only do this before legalize for now.
5970 if (VT.isVector() && !LegalOperations &&
5971 TLI.getBooleanContents(N0VT) ==
5972 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5973 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5974 // of the same size as the compared operands. Only optimize sext(setcc())
5975 // if this is the case.
5976 EVT SVT = getSetCCResultType(N0VT);
5978 // We know that the # elements of the results is the same as the
5979 // # elements of the compare (and the # elements of the compare result
5980 // for that matter). Check to see that they are the same size. If so,
5981 // we know that the element size of the sext'd result matches the
5982 // element size of the compare operands.
5983 if (VT.getSizeInBits() == SVT.getSizeInBits())
5984 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5986 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5988 // If the desired elements are smaller or larger than the source
5989 // elements we can use a matching integer vector type and then
5990 // truncate/sign extend
5991 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5992 if (SVT == MatchingVectorType) {
5993 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5994 N0.getOperand(0), N0.getOperand(1),
5995 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5996 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6000 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6001 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6004 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6006 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6007 NegOne, DAG.getConstant(0, DL, VT),
6008 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6009 if (SCC.getNode()) return SCC;
6011 if (!VT.isVector()) {
6012 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6013 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
6015 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6016 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6017 N0.getOperand(0), N0.getOperand(1), CC);
6018 return DAG.getSelect(DL, VT, SetCC,
6019 NegOne, DAG.getConstant(0, DL, VT));
6024 // fold (sext x) -> (zext x) if the sign bit is known zero.
6025 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6026 DAG.SignBitIsZero(N0))
6027 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6032 // isTruncateOf - If N is a truncate of some other value, return true, record
6033 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6034 // This function computes KnownZero to avoid a duplicated call to
6035 // computeKnownBits in the caller.
6036 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6039 if (N->getOpcode() == ISD::TRUNCATE) {
6040 Op = N->getOperand(0);
6041 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6045 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6046 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6049 SDValue Op0 = N->getOperand(0);
6050 SDValue Op1 = N->getOperand(1);
6051 assert(Op0.getValueType() == Op1.getValueType());
6053 if (isNullConstant(Op0))
6055 else if (isNullConstant(Op1))
6060 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6062 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6068 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6069 SDValue N0 = N->getOperand(0);
6070 EVT VT = N->getValueType(0);
6072 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6074 return SDValue(Res, 0);
6076 // fold (zext (zext x)) -> (zext x)
6077 // fold (zext (aext x)) -> (zext x)
6078 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6079 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6082 // fold (zext (truncate x)) -> (zext x) or
6083 // (zext (truncate x)) -> (truncate x)
6084 // This is valid when the truncated bits of x are already zero.
6085 // FIXME: We should extend this to work for vectors too.
6088 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6089 APInt TruncatedBits =
6090 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6091 APInt(Op.getValueSizeInBits(), 0) :
6092 APInt::getBitsSet(Op.getValueSizeInBits(),
6093 N0.getValueSizeInBits(),
6094 std::min(Op.getValueSizeInBits(),
6095 VT.getSizeInBits()));
6096 if (TruncatedBits == (KnownZero & TruncatedBits)) {
6097 if (VT.bitsGT(Op.getValueType()))
6098 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6099 if (VT.bitsLT(Op.getValueType()))
6100 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6106 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6107 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6108 if (N0.getOpcode() == ISD::TRUNCATE) {
6109 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6110 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6111 if (NarrowLoad.getNode() != N0.getNode()) {
6112 CombineTo(N0.getNode(), NarrowLoad);
6113 // CombineTo deleted the truncate, if needed, but not what's under it.
6116 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6120 // fold (zext (truncate x)) -> (and x, mask)
6121 if (N0.getOpcode() == ISD::TRUNCATE &&
6122 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
6124 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6125 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6126 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6127 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6128 if (NarrowLoad.getNode() != N0.getNode()) {
6129 CombineTo(N0.getNode(), NarrowLoad);
6130 // CombineTo deleted the truncate, if needed, but not what's under it.
6133 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6136 SDValue Op = N0.getOperand(0);
6137 if (Op.getValueType().bitsLT(VT)) {
6138 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6139 AddToWorklist(Op.getNode());
6140 } else if (Op.getValueType().bitsGT(VT)) {
6141 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6142 AddToWorklist(Op.getNode());
6144 return DAG.getZeroExtendInReg(Op, SDLoc(N),
6145 N0.getValueType().getScalarType());
6148 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6149 // if either of the casts is not free.
6150 if (N0.getOpcode() == ISD::AND &&
6151 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6152 N0.getOperand(1).getOpcode() == ISD::Constant &&
6153 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6154 N0.getValueType()) ||
6155 !TLI.isZExtFree(N0.getValueType(), VT))) {
6156 SDValue X = N0.getOperand(0).getOperand(0);
6157 if (X.getValueType().bitsLT(VT)) {
6158 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6159 } else if (X.getValueType().bitsGT(VT)) {
6160 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6162 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6163 Mask = Mask.zext(VT.getSizeInBits());
6165 return DAG.getNode(ISD::AND, DL, VT,
6166 X, DAG.getConstant(Mask, DL, VT));
6169 // fold (zext (load x)) -> (zext (truncate (zextload x)))
6170 // Only generate vector extloads when 1) they're legal, and 2) they are
6171 // deemed desirable by the target.
6172 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6173 ((!LegalOperations && !VT.isVector() &&
6174 !cast<LoadSDNode>(N0)->isVolatile()) ||
6175 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6176 bool DoXform = true;
6177 SmallVector<SDNode*, 4> SetCCs;
6178 if (!N0.hasOneUse())
6179 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6181 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6183 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6184 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6186 LN0->getBasePtr(), N0.getValueType(),
6187 LN0->getMemOperand());
6188 CombineTo(N, ExtLoad);
6189 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6190 N0.getValueType(), ExtLoad);
6191 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6193 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6195 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6199 // fold (zext (load x)) to multiple smaller zextloads.
6200 // Only on illegal but splittable vectors.
6201 if (SDValue ExtLoad = CombineExtLoad(N))
6204 // fold (zext (and/or/xor (load x), cst)) ->
6205 // (and/or/xor (zextload x), (zext cst))
6206 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6207 N0.getOpcode() == ISD::XOR) &&
6208 isa<LoadSDNode>(N0.getOperand(0)) &&
6209 N0.getOperand(1).getOpcode() == ISD::Constant &&
6210 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6211 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6212 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6213 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6214 bool DoXform = true;
6215 SmallVector<SDNode*, 4> SetCCs;
6216 if (!N0.hasOneUse())
6217 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6220 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6221 LN0->getChain(), LN0->getBasePtr(),
6223 LN0->getMemOperand());
6224 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6225 Mask = Mask.zext(VT.getSizeInBits());
6227 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6228 ExtLoad, DAG.getConstant(Mask, DL, VT));
6229 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6230 SDLoc(N0.getOperand(0)),
6231 N0.getOperand(0).getValueType(), ExtLoad);
6233 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6234 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6236 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6241 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6242 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6243 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6244 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6245 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6246 EVT MemVT = LN0->getMemoryVT();
6247 if ((!LegalOperations && !LN0->isVolatile()) ||
6248 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6249 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6251 LN0->getBasePtr(), MemVT,
6252 LN0->getMemOperand());
6253 CombineTo(N, ExtLoad);
6254 CombineTo(N0.getNode(),
6255 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6257 ExtLoad.getValue(1));
6258 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6262 if (N0.getOpcode() == ISD::SETCC) {
6263 if (!LegalOperations && VT.isVector() &&
6264 N0.getValueType().getVectorElementType() == MVT::i1) {
6265 EVT N0VT = N0.getOperand(0).getValueType();
6266 if (getSetCCResultType(N0VT) == N0.getValueType())
6269 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6270 // Only do this before legalize for now.
6271 EVT EltVT = VT.getVectorElementType();
6273 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6274 DAG.getConstant(1, DL, EltVT));
6275 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6276 // We know that the # elements of the results is the same as the
6277 // # elements of the compare (and the # elements of the compare result
6278 // for that matter). Check to see that they are the same size. If so,
6279 // we know that the element size of the sext'd result matches the
6280 // element size of the compare operands.
6281 return DAG.getNode(ISD::AND, DL, VT,
6282 DAG.getSetCC(DL, VT, N0.getOperand(0),
6284 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6285 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6288 // If the desired elements are smaller or larger than the source
6289 // elements we can use a matching integer vector type and then
6290 // truncate/sign extend
6291 EVT MatchingElementType =
6292 EVT::getIntegerVT(*DAG.getContext(),
6293 N0VT.getScalarType().getSizeInBits());
6294 EVT MatchingVectorType =
6295 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6296 N0VT.getVectorNumElements());
6298 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6300 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6301 return DAG.getNode(ISD::AND, DL, VT,
6302 DAG.getSExtOrTrunc(VsetCC, DL, VT),
6303 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6306 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6309 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6310 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6311 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6312 if (SCC.getNode()) return SCC;
6315 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6316 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6317 isa<ConstantSDNode>(N0.getOperand(1)) &&
6318 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6320 SDValue ShAmt = N0.getOperand(1);
6321 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6322 if (N0.getOpcode() == ISD::SHL) {
6323 SDValue InnerZExt = N0.getOperand(0);
6324 // If the original shl may be shifting out bits, do not perform this
6326 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6327 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6328 if (ShAmtVal > KnownZeroBits)
6334 // Ensure that the shift amount is wide enough for the shifted value.
6335 if (VT.getSizeInBits() >= 256)
6336 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6338 return DAG.getNode(N0.getOpcode(), DL, VT,
6339 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6346 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6347 SDValue N0 = N->getOperand(0);
6348 EVT VT = N->getValueType(0);
6350 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6352 return SDValue(Res, 0);
6354 // fold (aext (aext x)) -> (aext x)
6355 // fold (aext (zext x)) -> (zext x)
6356 // fold (aext (sext x)) -> (sext x)
6357 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6358 N0.getOpcode() == ISD::ZERO_EXTEND ||
6359 N0.getOpcode() == ISD::SIGN_EXTEND)
6360 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6362 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6363 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6364 if (N0.getOpcode() == ISD::TRUNCATE) {
6365 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6366 if (NarrowLoad.getNode()) {
6367 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6368 if (NarrowLoad.getNode() != N0.getNode()) {
6369 CombineTo(N0.getNode(), NarrowLoad);
6370 // CombineTo deleted the truncate, if needed, but not what's under it.
6373 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6377 // fold (aext (truncate x))
6378 if (N0.getOpcode() == ISD::TRUNCATE) {
6379 SDValue TruncOp = N0.getOperand(0);
6380 if (TruncOp.getValueType() == VT)
6381 return TruncOp; // x iff x size == zext size.
6382 if (TruncOp.getValueType().bitsGT(VT))
6383 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6384 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6387 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6388 // if the trunc is not free.
6389 if (N0.getOpcode() == ISD::AND &&
6390 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6391 N0.getOperand(1).getOpcode() == ISD::Constant &&
6392 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6393 N0.getValueType())) {
6394 SDValue X = N0.getOperand(0).getOperand(0);
6395 if (X.getValueType().bitsLT(VT)) {
6396 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6397 } else if (X.getValueType().bitsGT(VT)) {
6398 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6400 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6401 Mask = Mask.zext(VT.getSizeInBits());
6403 return DAG.getNode(ISD::AND, DL, VT,
6404 X, DAG.getConstant(Mask, DL, VT));
6407 // fold (aext (load x)) -> (aext (truncate (extload x)))
6408 // None of the supported targets knows how to perform load and any_ext
6409 // on vectors in one instruction. We only perform this transformation on
6411 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6412 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6413 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6414 bool DoXform = true;
6415 SmallVector<SDNode*, 4> SetCCs;
6416 if (!N0.hasOneUse())
6417 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6419 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6420 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6422 LN0->getBasePtr(), N0.getValueType(),
6423 LN0->getMemOperand());
6424 CombineTo(N, ExtLoad);
6425 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6426 N0.getValueType(), ExtLoad);
6427 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6428 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6430 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6434 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6435 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6436 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6437 if (N0.getOpcode() == ISD::LOAD &&
6438 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6440 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6441 ISD::LoadExtType ExtType = LN0->getExtensionType();
6442 EVT MemVT = LN0->getMemoryVT();
6443 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6444 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6445 VT, LN0->getChain(), LN0->getBasePtr(),
6446 MemVT, LN0->getMemOperand());
6447 CombineTo(N, ExtLoad);
6448 CombineTo(N0.getNode(),
6449 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6450 N0.getValueType(), ExtLoad),
6451 ExtLoad.getValue(1));
6452 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6456 if (N0.getOpcode() == ISD::SETCC) {
6458 // aext(setcc) -> vsetcc
6459 // aext(setcc) -> truncate(vsetcc)
6460 // aext(setcc) -> aext(vsetcc)
6461 // Only do this before legalize for now.
6462 if (VT.isVector() && !LegalOperations) {
6463 EVT N0VT = N0.getOperand(0).getValueType();
6464 // We know that the # elements of the results is the same as the
6465 // # elements of the compare (and the # elements of the compare result
6466 // for that matter). Check to see that they are the same size. If so,
6467 // we know that the element size of the sext'd result matches the
6468 // element size of the compare operands.
6469 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6470 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6472 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6473 // If the desired elements are smaller or larger than the source
6474 // elements we can use a matching integer vector type and then
6475 // truncate/any extend
6477 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6479 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6481 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6482 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6486 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6489 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6490 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6491 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6499 /// See if the specified operand can be simplified with the knowledge that only
6500 /// the bits specified by Mask are used. If so, return the simpler operand,
6501 /// otherwise return a null SDValue.
6502 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6503 switch (V.getOpcode()) {
6505 case ISD::Constant: {
6506 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6507 assert(CV && "Const value should be ConstSDNode.");
6508 const APInt &CVal = CV->getAPIntValue();
6509 APInt NewVal = CVal & Mask;
6511 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6516 // If the LHS or RHS don't contribute bits to the or, drop them.
6517 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6518 return V.getOperand(1);
6519 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6520 return V.getOperand(0);
6523 // Only look at single-use SRLs.
6524 if (!V.getNode()->hasOneUse())
6526 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6527 // See if we can recursively simplify the LHS.
6528 unsigned Amt = RHSC->getZExtValue();
6530 // Watch out for shift count overflow though.
6531 if (Amt >= Mask.getBitWidth()) break;
6532 APInt NewMask = Mask << Amt;
6533 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6534 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6535 SimplifyLHS, V.getOperand(1));
6541 /// If the result of a wider load is shifted to right of N bits and then
6542 /// truncated to a narrower type and where N is a multiple of number of bits of
6543 /// the narrower type, transform it to a narrower load from address + N / num of
6544 /// bits of new type. If the result is to be extended, also fold the extension
6545 /// to form a extending load.
6546 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6547 unsigned Opc = N->getOpcode();
6549 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6550 SDValue N0 = N->getOperand(0);
6551 EVT VT = N->getValueType(0);
6554 // This transformation isn't valid for vector loads.
6558 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6560 if (Opc == ISD::SIGN_EXTEND_INREG) {
6561 ExtType = ISD::SEXTLOAD;
6562 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6563 } else if (Opc == ISD::SRL) {
6564 // Another special-case: SRL is basically zero-extending a narrower value.
6565 ExtType = ISD::ZEXTLOAD;
6567 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6568 if (!N01) return SDValue();
6569 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6570 VT.getSizeInBits() - N01->getZExtValue());
6572 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6575 unsigned EVTBits = ExtVT.getSizeInBits();
6577 // Do not generate loads of non-round integer types since these can
6578 // be expensive (and would be wrong if the type is not byte sized).
6579 if (!ExtVT.isRound())
6583 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6584 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6585 ShAmt = N01->getZExtValue();
6586 // Is the shift amount a multiple of size of VT?
6587 if ((ShAmt & (EVTBits-1)) == 0) {
6588 N0 = N0.getOperand(0);
6589 // Is the load width a multiple of size of VT?
6590 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6594 // At this point, we must have a load or else we can't do the transform.
6595 if (!isa<LoadSDNode>(N0)) return SDValue();
6597 // Because a SRL must be assumed to *need* to zero-extend the high bits
6598 // (as opposed to anyext the high bits), we can't combine the zextload
6599 // lowering of SRL and an sextload.
6600 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6603 // If the shift amount is larger than the input type then we're not
6604 // accessing any of the loaded bytes. If the load was a zextload/extload
6605 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6606 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6611 // If the load is shifted left (and the result isn't shifted back right),
6612 // we can fold the truncate through the shift.
6613 unsigned ShLeftAmt = 0;
6614 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6615 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6616 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6617 ShLeftAmt = N01->getZExtValue();
6618 N0 = N0.getOperand(0);
6622 // If we haven't found a load, we can't narrow it. Don't transform one with
6623 // multiple uses, this would require adding a new load.
6624 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6627 // Don't change the width of a volatile load.
6628 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6629 if (LN0->isVolatile())
6632 // Verify that we are actually reducing a load width here.
6633 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6636 // For the transform to be legal, the load must produce only two values
6637 // (the value loaded and the chain). Don't transform a pre-increment
6638 // load, for example, which produces an extra value. Otherwise the
6639 // transformation is not equivalent, and the downstream logic to replace
6640 // uses gets things wrong.
6641 if (LN0->getNumValues() > 2)
6644 // If the load that we're shrinking is an extload and we're not just
6645 // discarding the extension we can't simply shrink the load. Bail.
6646 // TODO: It would be possible to merge the extensions in some cases.
6647 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6648 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6651 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6654 EVT PtrType = N0.getOperand(1).getValueType();
6656 if (PtrType == MVT::Untyped || PtrType.isExtended())
6657 // It's not possible to generate a constant of extended or untyped type.
6660 // For big endian targets, we need to adjust the offset to the pointer to
6661 // load the correct bytes.
6662 if (DAG.getDataLayout().isBigEndian()) {
6663 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6664 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6665 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6668 uint64_t PtrOff = ShAmt / 8;
6669 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6671 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6672 PtrType, LN0->getBasePtr(),
6673 DAG.getConstant(PtrOff, DL, PtrType));
6674 AddToWorklist(NewPtr.getNode());
6677 if (ExtType == ISD::NON_EXTLOAD)
6678 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6679 LN0->getPointerInfo().getWithOffset(PtrOff),
6680 LN0->isVolatile(), LN0->isNonTemporal(),
6681 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6683 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6684 LN0->getPointerInfo().getWithOffset(PtrOff),
6685 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6686 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6688 // Replace the old load's chain with the new load's chain.
6689 WorklistRemover DeadNodes(*this);
6690 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6692 // Shift the result left, if we've swallowed a left shift.
6693 SDValue Result = Load;
6694 if (ShLeftAmt != 0) {
6695 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6696 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6698 // If the shift amount is as large as the result size (but, presumably,
6699 // no larger than the source) then the useful bits of the result are
6700 // zero; we can't simply return the shortened shift, because the result
6701 // of that operation is undefined.
6703 if (ShLeftAmt >= VT.getSizeInBits())
6704 Result = DAG.getConstant(0, DL, VT);
6706 Result = DAG.getNode(ISD::SHL, DL, VT,
6707 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6710 // Return the new loaded value.
6714 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6715 SDValue N0 = N->getOperand(0);
6716 SDValue N1 = N->getOperand(1);
6717 EVT VT = N->getValueType(0);
6718 EVT EVT = cast<VTSDNode>(N1)->getVT();
6719 unsigned VTBits = VT.getScalarType().getSizeInBits();
6720 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6722 // fold (sext_in_reg c1) -> c1
6723 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6724 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6726 // If the input is already sign extended, just drop the extension.
6727 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6730 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6731 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6732 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6733 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6734 N0.getOperand(0), N1);
6736 // fold (sext_in_reg (sext x)) -> (sext x)
6737 // fold (sext_in_reg (aext x)) -> (sext x)
6738 // if x is small enough.
6739 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6740 SDValue N00 = N0.getOperand(0);
6741 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6742 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6743 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6746 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6747 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6748 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6750 // fold operands of sext_in_reg based on knowledge that the top bits are not
6752 if (SimplifyDemandedBits(SDValue(N, 0)))
6753 return SDValue(N, 0);
6755 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6756 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6757 if (SDValue NarrowLoad = ReduceLoadWidth(N))
6760 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6761 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6762 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6763 if (N0.getOpcode() == ISD::SRL) {
6764 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6765 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6766 // We can turn this into an SRA iff the input to the SRL is already sign
6768 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6769 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6770 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6771 N0.getOperand(0), N0.getOperand(1));
6775 // fold (sext_inreg (extload x)) -> (sextload x)
6776 if (ISD::isEXTLoad(N0.getNode()) &&
6777 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6778 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6779 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6780 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6781 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6782 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6784 LN0->getBasePtr(), EVT,
6785 LN0->getMemOperand());
6786 CombineTo(N, ExtLoad);
6787 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6788 AddToWorklist(ExtLoad.getNode());
6789 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6791 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6792 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6794 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6795 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6796 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6797 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6798 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6800 LN0->getBasePtr(), EVT,
6801 LN0->getMemOperand());
6802 CombineTo(N, ExtLoad);
6803 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6804 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6807 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6808 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6809 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6810 N0.getOperand(1), false);
6811 if (BSwap.getNode())
6812 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6816 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6817 // into a build_vector.
6818 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6819 SmallVector<SDValue, 8> Elts;
6820 unsigned NumElts = N0->getNumOperands();
6821 unsigned ShAmt = VTBits - EVTBits;
6823 for (unsigned i = 0; i != NumElts; ++i) {
6824 SDValue Op = N0->getOperand(i);
6825 if (Op->getOpcode() == ISD::UNDEF) {
6830 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6831 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6832 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6833 SDLoc(Op), Op.getValueType()));
6836 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6842 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6843 SDValue N0 = N->getOperand(0);
6844 EVT VT = N->getValueType(0);
6846 if (N0.getOpcode() == ISD::UNDEF)
6847 return DAG.getUNDEF(VT);
6849 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6851 return SDValue(Res, 0);
6856 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6857 SDValue N0 = N->getOperand(0);
6858 EVT VT = N->getValueType(0);
6859 bool isLE = DAG.getDataLayout().isLittleEndian();
6862 if (N0.getValueType() == N->getValueType(0))
6864 // fold (truncate c1) -> c1
6865 if (isConstantIntBuildVectorOrConstantInt(N0))
6866 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6867 // fold (truncate (truncate x)) -> (truncate x)
6868 if (N0.getOpcode() == ISD::TRUNCATE)
6869 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6870 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6871 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6872 N0.getOpcode() == ISD::SIGN_EXTEND ||
6873 N0.getOpcode() == ISD::ANY_EXTEND) {
6874 if (N0.getOperand(0).getValueType().bitsLT(VT))
6875 // if the source is smaller than the dest, we still need an extend
6876 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6878 if (N0.getOperand(0).getValueType().bitsGT(VT))
6879 // if the source is larger than the dest, than we just need the truncate
6880 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6881 // if the source and dest are the same type, we can drop both the extend
6882 // and the truncate.
6883 return N0.getOperand(0);
6886 // Fold extract-and-trunc into a narrow extract. For example:
6887 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6888 // i32 y = TRUNCATE(i64 x)
6890 // v16i8 b = BITCAST (v2i64 val)
6891 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6893 // Note: We only run this optimization after type legalization (which often
6894 // creates this pattern) and before operation legalization after which
6895 // we need to be more careful about the vector instructions that we generate.
6896 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6897 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6899 EVT VecTy = N0.getOperand(0).getValueType();
6900 EVT ExTy = N0.getValueType();
6901 EVT TrTy = N->getValueType(0);
6903 unsigned NumElem = VecTy.getVectorNumElements();
6904 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6906 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6907 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6909 SDValue EltNo = N0->getOperand(1);
6910 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6911 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6912 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
6913 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6915 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6916 NVT, N0.getOperand(0));
6919 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6921 DAG.getConstant(Index, DL, IndexTy));
6925 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6926 if (N0.getOpcode() == ISD::SELECT) {
6927 EVT SrcVT = N0.getValueType();
6928 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6929 TLI.isTruncateFree(SrcVT, VT)) {
6931 SDValue Cond = N0.getOperand(0);
6932 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6933 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6934 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6938 // Fold a series of buildvector, bitcast, and truncate if possible.
6940 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6941 // (2xi32 (buildvector x, y)).
6942 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6943 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6944 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6945 N0.getOperand(0).hasOneUse()) {
6947 SDValue BuildVect = N0.getOperand(0);
6948 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6949 EVT TruncVecEltTy = VT.getVectorElementType();
6951 // Check that the element types match.
6952 if (BuildVectEltTy == TruncVecEltTy) {
6953 // Now we only need to compute the offset of the truncated elements.
6954 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6955 unsigned TruncVecNumElts = VT.getVectorNumElements();
6956 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6958 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6959 "Invalid number of elements");
6961 SmallVector<SDValue, 8> Opnds;
6962 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6963 Opnds.push_back(BuildVect.getOperand(i));
6965 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6969 // See if we can simplify the input to this truncate through knowledge that
6970 // only the low bits are being used.
6971 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6972 // Currently we only perform this optimization on scalars because vectors
6973 // may have different active low bits.
6974 if (!VT.isVector()) {
6976 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6977 VT.getSizeInBits()));
6978 if (Shorter.getNode())
6979 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6981 // fold (truncate (load x)) -> (smaller load x)
6982 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6983 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6984 if (SDValue Reduced = ReduceLoadWidth(N))
6987 // Handle the case where the load remains an extending load even
6988 // after truncation.
6989 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6990 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6991 if (!LN0->isVolatile() &&
6992 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6993 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6994 VT, LN0->getChain(), LN0->getBasePtr(),
6996 LN0->getMemOperand());
6997 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7002 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7003 // where ... are all 'undef'.
7004 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7005 SmallVector<EVT, 8> VTs;
7008 unsigned NumDefs = 0;
7010 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7011 SDValue X = N0.getOperand(i);
7012 if (X.getOpcode() != ISD::UNDEF) {
7017 // Stop if more than one members are non-undef.
7020 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7021 VT.getVectorElementType(),
7022 X.getValueType().getVectorNumElements()));
7026 return DAG.getUNDEF(VT);
7029 assert(V.getNode() && "The single defined operand is empty!");
7030 SmallVector<SDValue, 8> Opnds;
7031 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7033 Opnds.push_back(DAG.getUNDEF(VTs[i]));
7036 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7037 AddToWorklist(NV.getNode());
7038 Opnds.push_back(NV);
7040 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7044 // Simplify the operands using demanded-bits information.
7045 if (!VT.isVector() &&
7046 SimplifyDemandedBits(SDValue(N, 0)))
7047 return SDValue(N, 0);
7052 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7053 SDValue Elt = N->getOperand(i);
7054 if (Elt.getOpcode() != ISD::MERGE_VALUES)
7055 return Elt.getNode();
7056 return Elt.getOperand(Elt.getResNo()).getNode();
7059 /// build_pair (load, load) -> load
7060 /// if load locations are consecutive.
7061 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7062 assert(N->getOpcode() == ISD::BUILD_PAIR);
7064 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7065 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7066 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7067 LD1->getAddressSpace() != LD2->getAddressSpace())
7069 EVT LD1VT = LD1->getValueType(0);
7071 if (ISD::isNON_EXTLoad(LD2) &&
7073 // If both are volatile this would reduce the number of volatile loads.
7074 // If one is volatile it might be ok, but play conservative and bail out.
7075 !LD1->isVolatile() &&
7076 !LD2->isVolatile() &&
7077 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7078 unsigned Align = LD1->getAlignment();
7079 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7080 VT.getTypeForEVT(*DAG.getContext()));
7082 if (NewAlign <= Align &&
7083 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7084 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7085 LD1->getBasePtr(), LD1->getPointerInfo(),
7086 false, false, false, Align);
7092 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7093 SDValue N0 = N->getOperand(0);
7094 EVT VT = N->getValueType(0);
7096 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7097 // Only do this before legalize, since afterward the target may be depending
7098 // on the bitconvert.
7099 // First check to see if this is all constant.
7101 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7103 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7105 EVT DestEltVT = N->getValueType(0).getVectorElementType();
7106 assert(!DestEltVT.isVector() &&
7107 "Element type of vector ValueType must not be vector!");
7109 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7112 // If the input is a constant, let getNode fold it.
7113 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7114 // If we can't allow illegal operations, we need to check that this is just
7115 // a fp -> int or int -> conversion and that the resulting operation will
7117 if (!LegalOperations ||
7118 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7119 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7120 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7121 TLI.isOperationLegal(ISD::Constant, VT)))
7122 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7125 // (conv (conv x, t1), t2) -> (conv x, t2)
7126 if (N0.getOpcode() == ISD::BITCAST)
7127 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7130 // fold (conv (load x)) -> (load (conv*)x)
7131 // If the resultant load doesn't need a higher alignment than the original!
7132 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7133 // Do not change the width of a volatile load.
7134 !cast<LoadSDNode>(N0)->isVolatile() &&
7135 // Do not remove the cast if the types differ in endian layout.
7136 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7137 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7138 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7139 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7140 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7141 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7142 VT.getTypeForEVT(*DAG.getContext()));
7143 unsigned OrigAlign = LN0->getAlignment();
7145 if (Align <= OrigAlign) {
7146 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7147 LN0->getBasePtr(), LN0->getPointerInfo(),
7148 LN0->isVolatile(), LN0->isNonTemporal(),
7149 LN0->isInvariant(), OrigAlign,
7151 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7156 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7157 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7158 // This often reduces constant pool loads.
7159 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7160 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7161 N0.getNode()->hasOneUse() && VT.isInteger() &&
7162 !VT.isVector() && !N0.getValueType().isVector()) {
7163 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7165 AddToWorklist(NewConv.getNode());
7168 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7169 if (N0.getOpcode() == ISD::FNEG)
7170 return DAG.getNode(ISD::XOR, DL, VT,
7171 NewConv, DAG.getConstant(SignBit, DL, VT));
7172 assert(N0.getOpcode() == ISD::FABS);
7173 return DAG.getNode(ISD::AND, DL, VT,
7174 NewConv, DAG.getConstant(~SignBit, DL, VT));
7177 // fold (bitconvert (fcopysign cst, x)) ->
7178 // (or (and (bitconvert x), sign), (and cst, (not sign)))
7179 // Note that we don't handle (copysign x, cst) because this can always be
7180 // folded to an fneg or fabs.
7181 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7182 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7183 VT.isInteger() && !VT.isVector()) {
7184 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7185 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7186 if (isTypeLegal(IntXVT)) {
7187 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7188 IntXVT, N0.getOperand(1));
7189 AddToWorklist(X.getNode());
7191 // If X has a different width than the result/lhs, sext it or truncate it.
7192 unsigned VTWidth = VT.getSizeInBits();
7193 if (OrigXWidth < VTWidth) {
7194 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7195 AddToWorklist(X.getNode());
7196 } else if (OrigXWidth > VTWidth) {
7197 // To get the sign bit in the right place, we have to shift it right
7198 // before truncating.
7200 X = DAG.getNode(ISD::SRL, DL,
7201 X.getValueType(), X,
7202 DAG.getConstant(OrigXWidth-VTWidth, DL,
7204 AddToWorklist(X.getNode());
7205 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7206 AddToWorklist(X.getNode());
7209 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7210 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7211 X, DAG.getConstant(SignBit, SDLoc(X), VT));
7212 AddToWorklist(X.getNode());
7214 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7215 VT, N0.getOperand(0));
7216 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7217 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7218 AddToWorklist(Cst.getNode());
7220 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7224 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7225 if (N0.getOpcode() == ISD::BUILD_PAIR)
7226 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7229 // Remove double bitcasts from shuffles - this is often a legacy of
7230 // XformToShuffleWithZero being used to combine bitmaskings (of
7231 // float vectors bitcast to integer vectors) into shuffles.
7232 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7233 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7234 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7235 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7236 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7237 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7239 // If operands are a bitcast, peek through if it casts the original VT.
7240 // If operands are a constant, just bitcast back to original VT.
7241 auto PeekThroughBitcast = [&](SDValue Op) {
7242 if (Op.getOpcode() == ISD::BITCAST &&
7243 Op.getOperand(0).getValueType() == VT)
7244 return SDValue(Op.getOperand(0));
7245 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7246 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7247 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7251 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7252 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7257 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7258 SmallVector<int, 8> NewMask;
7259 for (int M : SVN->getMask())
7260 for (int i = 0; i != MaskScale; ++i)
7261 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7263 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7265 std::swap(SV0, SV1);
7266 ShuffleVectorSDNode::commuteMask(NewMask);
7267 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7271 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7277 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7278 EVT VT = N->getValueType(0);
7279 return CombineConsecutiveLoads(N, VT);
7282 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7283 /// operands. DstEltVT indicates the destination element value type.
7284 SDValue DAGCombiner::
7285 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7286 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7288 // If this is already the right type, we're done.
7289 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7291 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7292 unsigned DstBitSize = DstEltVT.getSizeInBits();
7294 // If this is a conversion of N elements of one type to N elements of another
7295 // type, convert each element. This handles FP<->INT cases.
7296 if (SrcBitSize == DstBitSize) {
7297 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7298 BV->getValueType(0).getVectorNumElements());
7300 // Due to the FP element handling below calling this routine recursively,
7301 // we can end up with a scalar-to-vector node here.
7302 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7303 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7304 DAG.getNode(ISD::BITCAST, SDLoc(BV),
7305 DstEltVT, BV->getOperand(0)));
7307 SmallVector<SDValue, 8> Ops;
7308 for (SDValue Op : BV->op_values()) {
7309 // If the vector element type is not legal, the BUILD_VECTOR operands
7310 // are promoted and implicitly truncated. Make that explicit here.
7311 if (Op.getValueType() != SrcEltVT)
7312 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7313 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7315 AddToWorklist(Ops.back().getNode());
7317 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7320 // Otherwise, we're growing or shrinking the elements. To avoid having to
7321 // handle annoying details of growing/shrinking FP values, we convert them to
7323 if (SrcEltVT.isFloatingPoint()) {
7324 // Convert the input float vector to a int vector where the elements are the
7326 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7327 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7331 // Now we know the input is an integer vector. If the output is a FP type,
7332 // convert to integer first, then to FP of the right size.
7333 if (DstEltVT.isFloatingPoint()) {
7334 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7335 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7337 // Next, convert to FP elements of the same size.
7338 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7343 // Okay, we know the src/dst types are both integers of differing types.
7344 // Handling growing first.
7345 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7346 if (SrcBitSize < DstBitSize) {
7347 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7349 SmallVector<SDValue, 8> Ops;
7350 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7351 i += NumInputsPerOutput) {
7352 bool isLE = DAG.getDataLayout().isLittleEndian();
7353 APInt NewBits = APInt(DstBitSize, 0);
7354 bool EltIsUndef = true;
7355 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7356 // Shift the previously computed bits over.
7357 NewBits <<= SrcBitSize;
7358 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7359 if (Op.getOpcode() == ISD::UNDEF) continue;
7362 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7363 zextOrTrunc(SrcBitSize).zext(DstBitSize);
7367 Ops.push_back(DAG.getUNDEF(DstEltVT));
7369 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7372 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7373 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7376 // Finally, this must be the case where we are shrinking elements: each input
7377 // turns into multiple outputs.
7378 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7379 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7380 NumOutputsPerInput*BV->getNumOperands());
7381 SmallVector<SDValue, 8> Ops;
7383 for (const SDValue &Op : BV->op_values()) {
7384 if (Op.getOpcode() == ISD::UNDEF) {
7385 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7389 APInt OpVal = cast<ConstantSDNode>(Op)->
7390 getAPIntValue().zextOrTrunc(SrcBitSize);
7392 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7393 APInt ThisVal = OpVal.trunc(DstBitSize);
7394 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7395 OpVal = OpVal.lshr(DstBitSize);
7398 // For big endian targets, swap the order of the pieces of each element.
7399 if (DAG.getDataLayout().isBigEndian())
7400 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7403 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7406 /// Try to perform FMA combining on a given FADD node.
7407 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7408 SDValue N0 = N->getOperand(0);
7409 SDValue N1 = N->getOperand(1);
7410 EVT VT = N->getValueType(0);
7413 const TargetOptions &Options = DAG.getTarget().Options;
7414 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7415 Options.UnsafeFPMath);
7417 // Floating-point multiply-add with intermediate rounding.
7418 bool HasFMAD = (LegalOperations &&
7419 TLI.isOperationLegal(ISD::FMAD, VT));
7421 // Floating-point multiply-add without intermediate rounding.
7422 bool HasFMA = ((!LegalOperations ||
7423 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7424 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7427 // No valid opcode, do not combine.
7428 if (!HasFMAD && !HasFMA)
7431 // Always prefer FMAD to FMA for precision.
7432 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7433 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7434 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7436 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7437 if (N0.getOpcode() == ISD::FMUL &&
7438 (Aggressive || N0->hasOneUse())) {
7439 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7440 N0.getOperand(0), N0.getOperand(1), N1);
7443 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7444 // Note: Commutes FADD operands.
7445 if (N1.getOpcode() == ISD::FMUL &&
7446 (Aggressive || N1->hasOneUse())) {
7447 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7448 N1.getOperand(0), N1.getOperand(1), N0);
7451 // Look through FP_EXTEND nodes to do more combining.
7452 if (UnsafeFPMath && LookThroughFPExt) {
7453 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7454 if (N0.getOpcode() == ISD::FP_EXTEND) {
7455 SDValue N00 = N0.getOperand(0);
7456 if (N00.getOpcode() == ISD::FMUL)
7457 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7458 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7460 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7461 N00.getOperand(1)), N1);
7464 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7465 // Note: Commutes FADD operands.
7466 if (N1.getOpcode() == ISD::FP_EXTEND) {
7467 SDValue N10 = N1.getOperand(0);
7468 if (N10.getOpcode() == ISD::FMUL)
7469 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7470 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7472 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7473 N10.getOperand(1)), N0);
7477 // More folding opportunities when target permits.
7478 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7479 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7480 if (N0.getOpcode() == PreferredFusedOpcode &&
7481 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7482 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7483 N0.getOperand(0), N0.getOperand(1),
7484 DAG.getNode(PreferredFusedOpcode, SL, VT,
7485 N0.getOperand(2).getOperand(0),
7486 N0.getOperand(2).getOperand(1),
7490 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7491 if (N1->getOpcode() == PreferredFusedOpcode &&
7492 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7493 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7494 N1.getOperand(0), N1.getOperand(1),
7495 DAG.getNode(PreferredFusedOpcode, SL, VT,
7496 N1.getOperand(2).getOperand(0),
7497 N1.getOperand(2).getOperand(1),
7501 if (UnsafeFPMath && LookThroughFPExt) {
7502 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7503 // -> (fma x, y, (fma (fpext u), (fpext v), z))
7504 auto FoldFAddFMAFPExtFMul = [&] (
7505 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7506 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7507 DAG.getNode(PreferredFusedOpcode, SL, VT,
7508 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7509 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7512 if (N0.getOpcode() == PreferredFusedOpcode) {
7513 SDValue N02 = N0.getOperand(2);
7514 if (N02.getOpcode() == ISD::FP_EXTEND) {
7515 SDValue N020 = N02.getOperand(0);
7516 if (N020.getOpcode() == ISD::FMUL)
7517 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7518 N020.getOperand(0), N020.getOperand(1),
7523 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7524 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7525 // FIXME: This turns two single-precision and one double-precision
7526 // operation into two double-precision operations, which might not be
7527 // interesting for all targets, especially GPUs.
7528 auto FoldFAddFPExtFMAFMul = [&] (
7529 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7530 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7531 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7532 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7533 DAG.getNode(PreferredFusedOpcode, SL, VT,
7534 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7535 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7538 if (N0.getOpcode() == ISD::FP_EXTEND) {
7539 SDValue N00 = N0.getOperand(0);
7540 if (N00.getOpcode() == PreferredFusedOpcode) {
7541 SDValue N002 = N00.getOperand(2);
7542 if (N002.getOpcode() == ISD::FMUL)
7543 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7544 N002.getOperand(0), N002.getOperand(1),
7549 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7550 // -> (fma y, z, (fma (fpext u), (fpext v), x))
7551 if (N1.getOpcode() == PreferredFusedOpcode) {
7552 SDValue N12 = N1.getOperand(2);
7553 if (N12.getOpcode() == ISD::FP_EXTEND) {
7554 SDValue N120 = N12.getOperand(0);
7555 if (N120.getOpcode() == ISD::FMUL)
7556 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7557 N120.getOperand(0), N120.getOperand(1),
7562 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7563 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7564 // FIXME: This turns two single-precision and one double-precision
7565 // operation into two double-precision operations, which might not be
7566 // interesting for all targets, especially GPUs.
7567 if (N1.getOpcode() == ISD::FP_EXTEND) {
7568 SDValue N10 = N1.getOperand(0);
7569 if (N10.getOpcode() == PreferredFusedOpcode) {
7570 SDValue N102 = N10.getOperand(2);
7571 if (N102.getOpcode() == ISD::FMUL)
7572 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7573 N102.getOperand(0), N102.getOperand(1),
7583 /// Try to perform FMA combining on a given FSUB node.
7584 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7585 SDValue N0 = N->getOperand(0);
7586 SDValue N1 = N->getOperand(1);
7587 EVT VT = N->getValueType(0);
7590 const TargetOptions &Options = DAG.getTarget().Options;
7591 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7592 Options.UnsafeFPMath);
7594 // Floating-point multiply-add with intermediate rounding.
7595 bool HasFMAD = (LegalOperations &&
7596 TLI.isOperationLegal(ISD::FMAD, VT));
7598 // Floating-point multiply-add without intermediate rounding.
7599 bool HasFMA = ((!LegalOperations ||
7600 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7601 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7604 // No valid opcode, do not combine.
7605 if (!HasFMAD && !HasFMA)
7608 // Always prefer FMAD to FMA for precision.
7609 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7610 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7611 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7613 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7614 if (N0.getOpcode() == ISD::FMUL &&
7615 (Aggressive || N0->hasOneUse())) {
7616 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7617 N0.getOperand(0), N0.getOperand(1),
7618 DAG.getNode(ISD::FNEG, SL, VT, N1));
7621 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7622 // Note: Commutes FSUB operands.
7623 if (N1.getOpcode() == ISD::FMUL &&
7624 (Aggressive || N1->hasOneUse()))
7625 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7626 DAG.getNode(ISD::FNEG, SL, VT,
7628 N1.getOperand(1), N0);
7630 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7631 if (N0.getOpcode() == ISD::FNEG &&
7632 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7633 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7634 SDValue N00 = N0.getOperand(0).getOperand(0);
7635 SDValue N01 = N0.getOperand(0).getOperand(1);
7636 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7637 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7638 DAG.getNode(ISD::FNEG, SL, VT, N1));
7641 // Look through FP_EXTEND nodes to do more combining.
7642 if (UnsafeFPMath && LookThroughFPExt) {
7643 // fold (fsub (fpext (fmul x, y)), z)
7644 // -> (fma (fpext x), (fpext y), (fneg z))
7645 if (N0.getOpcode() == ISD::FP_EXTEND) {
7646 SDValue N00 = N0.getOperand(0);
7647 if (N00.getOpcode() == ISD::FMUL)
7648 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7649 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7651 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7653 DAG.getNode(ISD::FNEG, SL, VT, N1));
7656 // fold (fsub x, (fpext (fmul y, z)))
7657 // -> (fma (fneg (fpext y)), (fpext z), x)
7658 // Note: Commutes FSUB operands.
7659 if (N1.getOpcode() == ISD::FP_EXTEND) {
7660 SDValue N10 = N1.getOperand(0);
7661 if (N10.getOpcode() == ISD::FMUL)
7662 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7663 DAG.getNode(ISD::FNEG, SL, VT,
7664 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7665 N10.getOperand(0))),
7666 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7671 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7672 // -> (fneg (fma (fpext x), (fpext y), z))
7673 // Note: This could be removed with appropriate canonicalization of the
7674 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7675 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7676 // from implementing the canonicalization in visitFSUB.
7677 if (N0.getOpcode() == ISD::FP_EXTEND) {
7678 SDValue N00 = N0.getOperand(0);
7679 if (N00.getOpcode() == ISD::FNEG) {
7680 SDValue N000 = N00.getOperand(0);
7681 if (N000.getOpcode() == ISD::FMUL) {
7682 return DAG.getNode(ISD::FNEG, SL, VT,
7683 DAG.getNode(PreferredFusedOpcode, SL, VT,
7684 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7685 N000.getOperand(0)),
7686 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7687 N000.getOperand(1)),
7693 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7694 // -> (fneg (fma (fpext x)), (fpext y), z)
7695 // Note: This could be removed with appropriate canonicalization of the
7696 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7697 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7698 // from implementing the canonicalization in visitFSUB.
7699 if (N0.getOpcode() == ISD::FNEG) {
7700 SDValue N00 = N0.getOperand(0);
7701 if (N00.getOpcode() == ISD::FP_EXTEND) {
7702 SDValue N000 = N00.getOperand(0);
7703 if (N000.getOpcode() == ISD::FMUL) {
7704 return DAG.getNode(ISD::FNEG, SL, VT,
7705 DAG.getNode(PreferredFusedOpcode, SL, VT,
7706 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7707 N000.getOperand(0)),
7708 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7709 N000.getOperand(1)),
7717 // More folding opportunities when target permits.
7718 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7719 // fold (fsub (fma x, y, (fmul u, v)), z)
7720 // -> (fma x, y (fma u, v, (fneg z)))
7721 if (N0.getOpcode() == PreferredFusedOpcode &&
7722 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7723 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7724 N0.getOperand(0), N0.getOperand(1),
7725 DAG.getNode(PreferredFusedOpcode, SL, VT,
7726 N0.getOperand(2).getOperand(0),
7727 N0.getOperand(2).getOperand(1),
7728 DAG.getNode(ISD::FNEG, SL, VT,
7732 // fold (fsub x, (fma y, z, (fmul u, v)))
7733 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7734 if (N1.getOpcode() == PreferredFusedOpcode &&
7735 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7736 SDValue N20 = N1.getOperand(2).getOperand(0);
7737 SDValue N21 = N1.getOperand(2).getOperand(1);
7738 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7739 DAG.getNode(ISD::FNEG, SL, VT,
7742 DAG.getNode(PreferredFusedOpcode, SL, VT,
7743 DAG.getNode(ISD::FNEG, SL, VT, N20),
7748 if (UnsafeFPMath && LookThroughFPExt) {
7749 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7750 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7751 if (N0.getOpcode() == PreferredFusedOpcode) {
7752 SDValue N02 = N0.getOperand(2);
7753 if (N02.getOpcode() == ISD::FP_EXTEND) {
7754 SDValue N020 = N02.getOperand(0);
7755 if (N020.getOpcode() == ISD::FMUL)
7756 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7757 N0.getOperand(0), N0.getOperand(1),
7758 DAG.getNode(PreferredFusedOpcode, SL, VT,
7759 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7760 N020.getOperand(0)),
7761 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7762 N020.getOperand(1)),
7763 DAG.getNode(ISD::FNEG, SL, VT,
7768 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7769 // -> (fma (fpext x), (fpext y),
7770 // (fma (fpext u), (fpext v), (fneg z)))
7771 // FIXME: This turns two single-precision and one double-precision
7772 // operation into two double-precision operations, which might not be
7773 // interesting for all targets, especially GPUs.
7774 if (N0.getOpcode() == ISD::FP_EXTEND) {
7775 SDValue N00 = N0.getOperand(0);
7776 if (N00.getOpcode() == PreferredFusedOpcode) {
7777 SDValue N002 = N00.getOperand(2);
7778 if (N002.getOpcode() == ISD::FMUL)
7779 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7780 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7782 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7784 DAG.getNode(PreferredFusedOpcode, SL, VT,
7785 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7786 N002.getOperand(0)),
7787 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7788 N002.getOperand(1)),
7789 DAG.getNode(ISD::FNEG, SL, VT,
7794 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7795 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7796 if (N1.getOpcode() == PreferredFusedOpcode &&
7797 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7798 SDValue N120 = N1.getOperand(2).getOperand(0);
7799 if (N120.getOpcode() == ISD::FMUL) {
7800 SDValue N1200 = N120.getOperand(0);
7801 SDValue N1201 = N120.getOperand(1);
7802 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7803 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7805 DAG.getNode(PreferredFusedOpcode, SL, VT,
7806 DAG.getNode(ISD::FNEG, SL, VT,
7807 DAG.getNode(ISD::FP_EXTEND, SL,
7809 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7815 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7816 // -> (fma (fneg (fpext y)), (fpext z),
7817 // (fma (fneg (fpext u)), (fpext v), x))
7818 // FIXME: This turns two single-precision and one double-precision
7819 // operation into two double-precision operations, which might not be
7820 // interesting for all targets, especially GPUs.
7821 if (N1.getOpcode() == ISD::FP_EXTEND &&
7822 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7823 SDValue N100 = N1.getOperand(0).getOperand(0);
7824 SDValue N101 = N1.getOperand(0).getOperand(1);
7825 SDValue N102 = N1.getOperand(0).getOperand(2);
7826 if (N102.getOpcode() == ISD::FMUL) {
7827 SDValue N1020 = N102.getOperand(0);
7828 SDValue N1021 = N102.getOperand(1);
7829 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7830 DAG.getNode(ISD::FNEG, SL, VT,
7831 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7833 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7834 DAG.getNode(PreferredFusedOpcode, SL, VT,
7835 DAG.getNode(ISD::FNEG, SL, VT,
7836 DAG.getNode(ISD::FP_EXTEND, SL,
7838 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7849 SDValue DAGCombiner::visitFADD(SDNode *N) {
7850 SDValue N0 = N->getOperand(0);
7851 SDValue N1 = N->getOperand(1);
7852 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7853 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7854 EVT VT = N->getValueType(0);
7856 const TargetOptions &Options = DAG.getTarget().Options;
7860 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7863 // fold (fadd c1, c2) -> c1 + c2
7865 return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7867 // canonicalize constant to RHS
7868 if (N0CFP && !N1CFP)
7869 return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7871 // fold (fadd A, (fneg B)) -> (fsub A, B)
7872 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7873 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7874 return DAG.getNode(ISD::FSUB, DL, VT, N0,
7875 GetNegatedExpression(N1, DAG, LegalOperations));
7877 // fold (fadd (fneg A), B) -> (fsub B, A)
7878 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7879 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7880 return DAG.getNode(ISD::FSUB, DL, VT, N1,
7881 GetNegatedExpression(N0, DAG, LegalOperations));
7883 // If 'unsafe math' is enabled, fold lots of things.
7884 if (Options.UnsafeFPMath) {
7885 // No FP constant should be created after legalization as Instruction
7886 // Selection pass has a hard time dealing with FP constants.
7887 bool AllowNewConst = (Level < AfterLegalizeDAG);
7889 // fold (fadd A, 0) -> A
7890 if (N1CFP && N1CFP->isZero())
7893 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7894 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7895 isa<ConstantFPSDNode>(N0.getOperand(1)))
7896 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7897 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7899 // If allowed, fold (fadd (fneg x), x) -> 0.0
7900 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7901 return DAG.getConstantFP(0.0, DL, VT);
7903 // If allowed, fold (fadd x, (fneg x)) -> 0.0
7904 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7905 return DAG.getConstantFP(0.0, DL, VT);
7907 // We can fold chains of FADD's of the same value into multiplications.
7908 // This transform is not safe in general because we are reducing the number
7909 // of rounding steps.
7910 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7911 if (N0.getOpcode() == ISD::FMUL) {
7912 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7913 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7915 // (fadd (fmul x, c), x) -> (fmul x, c+1)
7916 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7917 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7918 DAG.getConstantFP(1.0, DL, VT));
7919 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7922 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7923 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7924 N1.getOperand(0) == N1.getOperand(1) &&
7925 N0.getOperand(0) == N1.getOperand(0)) {
7926 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7927 DAG.getConstantFP(2.0, DL, VT));
7928 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
7932 if (N1.getOpcode() == ISD::FMUL) {
7933 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7934 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7936 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7937 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7938 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7939 DAG.getConstantFP(1.0, DL, VT));
7940 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
7943 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7944 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7945 N0.getOperand(0) == N0.getOperand(1) &&
7946 N1.getOperand(0) == N0.getOperand(0)) {
7947 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7948 DAG.getConstantFP(2.0, DL, VT));
7949 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
7953 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7954 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7955 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7956 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7957 (N0.getOperand(0) == N1)) {
7958 return DAG.getNode(ISD::FMUL, DL, VT,
7959 N1, DAG.getConstantFP(3.0, DL, VT));
7963 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7964 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7965 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7966 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7967 N1.getOperand(0) == N0) {
7968 return DAG.getNode(ISD::FMUL, DL, VT,
7969 N0, DAG.getConstantFP(3.0, DL, VT));
7973 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7974 if (AllowNewConst &&
7975 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7976 N0.getOperand(0) == N0.getOperand(1) &&
7977 N1.getOperand(0) == N1.getOperand(1) &&
7978 N0.getOperand(0) == N1.getOperand(0)) {
7979 return DAG.getNode(ISD::FMUL, DL, VT,
7980 N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
7983 } // enable-unsafe-fp-math
7985 // FADD -> FMA combines:
7986 SDValue Fused = visitFADDForFMACombine(N);
7988 AddToWorklist(Fused.getNode());
7995 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7996 SDValue N0 = N->getOperand(0);
7997 SDValue N1 = N->getOperand(1);
7998 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7999 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8000 EVT VT = N->getValueType(0);
8002 const TargetOptions &Options = DAG.getTarget().Options;
8006 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8009 // fold (fsub c1, c2) -> c1-c2
8011 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
8013 // fold (fsub A, (fneg B)) -> (fadd A, B)
8014 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8015 return DAG.getNode(ISD::FADD, dl, VT, N0,
8016 GetNegatedExpression(N1, DAG, LegalOperations));
8018 // If 'unsafe math' is enabled, fold lots of things.
8019 if (Options.UnsafeFPMath) {
8021 if (N1CFP && N1CFP->isZero())
8024 // (fsub 0, B) -> -B
8025 if (N0CFP && N0CFP->isZero()) {
8026 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8027 return GetNegatedExpression(N1, DAG, LegalOperations);
8028 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8029 return DAG.getNode(ISD::FNEG, dl, VT, N1);
8032 // (fsub x, x) -> 0.0
8034 return DAG.getConstantFP(0.0f, dl, VT);
8036 // (fsub x, (fadd x, y)) -> (fneg y)
8037 // (fsub x, (fadd y, x)) -> (fneg y)
8038 if (N1.getOpcode() == ISD::FADD) {
8039 SDValue N10 = N1->getOperand(0);
8040 SDValue N11 = N1->getOperand(1);
8042 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8043 return GetNegatedExpression(N11, DAG, LegalOperations);
8045 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8046 return GetNegatedExpression(N10, DAG, LegalOperations);
8050 // FSUB -> FMA combines:
8051 SDValue Fused = visitFSUBForFMACombine(N);
8053 AddToWorklist(Fused.getNode());
8060 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8061 SDValue N0 = N->getOperand(0);
8062 SDValue N1 = N->getOperand(1);
8063 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8064 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8065 EVT VT = N->getValueType(0);
8067 const TargetOptions &Options = DAG.getTarget().Options;
8070 if (VT.isVector()) {
8071 // This just handles C1 * C2 for vectors. Other vector folds are below.
8072 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8076 // fold (fmul c1, c2) -> c1*c2
8078 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
8080 // canonicalize constant to RHS
8081 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8082 !isConstantFPBuildVectorOrConstantFP(N1))
8083 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
8085 // fold (fmul A, 1.0) -> A
8086 if (N1CFP && N1CFP->isExactlyValue(1.0))
8089 if (Options.UnsafeFPMath) {
8090 // fold (fmul A, 0) -> 0
8091 if (N1CFP && N1CFP->isZero())
8094 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8095 if (N0.getOpcode() == ISD::FMUL) {
8096 // Fold scalars or any vector constants (not just splats).
8097 // This fold is done in general by InstCombine, but extra fmul insts
8098 // may have been generated during lowering.
8099 SDValue N00 = N0.getOperand(0);
8100 SDValue N01 = N0.getOperand(1);
8101 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8102 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8103 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8105 // Check 1: Make sure that the first operand of the inner multiply is NOT
8106 // a constant. Otherwise, we may induce infinite looping.
8107 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8108 // Check 2: Make sure that the second operand of the inner multiply and
8109 // the second operand of the outer multiply are constants.
8110 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8111 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8112 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8113 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
8118 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8119 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8120 // during an early run of DAGCombiner can prevent folding with fmuls
8121 // inserted during lowering.
8122 if (N0.getOpcode() == ISD::FADD &&
8123 (N0.getOperand(0) == N0.getOperand(1)) &&
8125 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8126 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8127 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
8131 // fold (fmul X, 2.0) -> (fadd X, X)
8132 if (N1CFP && N1CFP->isExactlyValue(+2.0))
8133 return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
8135 // fold (fmul X, -1.0) -> (fneg X)
8136 if (N1CFP && N1CFP->isExactlyValue(-1.0))
8137 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8138 return DAG.getNode(ISD::FNEG, DL, VT, N0);
8140 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8141 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8142 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8143 // Both can be negated for free, check to see if at least one is cheaper
8145 if (LHSNeg == 2 || RHSNeg == 2)
8146 return DAG.getNode(ISD::FMUL, DL, VT,
8147 GetNegatedExpression(N0, DAG, LegalOperations),
8148 GetNegatedExpression(N1, DAG, LegalOperations));
8155 SDValue DAGCombiner::visitFMA(SDNode *N) {
8156 SDValue N0 = N->getOperand(0);
8157 SDValue N1 = N->getOperand(1);
8158 SDValue N2 = N->getOperand(2);
8159 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8160 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8161 EVT VT = N->getValueType(0);
8163 const TargetOptions &Options = DAG.getTarget().Options;
8165 // Constant fold FMA.
8166 if (isa<ConstantFPSDNode>(N0) &&
8167 isa<ConstantFPSDNode>(N1) &&
8168 isa<ConstantFPSDNode>(N2)) {
8169 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8172 if (Options.UnsafeFPMath) {
8173 if (N0CFP && N0CFP->isZero())
8175 if (N1CFP && N1CFP->isZero())
8178 if (N0CFP && N0CFP->isExactlyValue(1.0))
8179 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8180 if (N1CFP && N1CFP->isExactlyValue(1.0))
8181 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8183 // Canonicalize (fma c, x, y) -> (fma x, c, y)
8184 if (N0CFP && !N1CFP)
8185 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8187 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8188 if (Options.UnsafeFPMath && N1CFP &&
8189 N2.getOpcode() == ISD::FMUL &&
8190 N0 == N2.getOperand(0) &&
8191 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8192 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8193 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8197 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8198 if (Options.UnsafeFPMath &&
8199 N0.getOpcode() == ISD::FMUL && N1CFP &&
8200 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8201 return DAG.getNode(ISD::FMA, dl, VT,
8203 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8207 // (fma x, 1, y) -> (fadd x, y)
8208 // (fma x, -1, y) -> (fadd (fneg x), y)
8210 if (N1CFP->isExactlyValue(1.0))
8211 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8213 if (N1CFP->isExactlyValue(-1.0) &&
8214 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8215 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8216 AddToWorklist(RHSNeg.getNode());
8217 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8221 // (fma x, c, x) -> (fmul x, (c+1))
8222 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8223 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8224 DAG.getNode(ISD::FADD, dl, VT,
8225 N1, DAG.getConstantFP(1.0, dl, VT)));
8227 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8228 if (Options.UnsafeFPMath && N1CFP &&
8229 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8230 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8231 DAG.getNode(ISD::FADD, dl, VT,
8232 N1, DAG.getConstantFP(-1.0, dl, VT)));
8238 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8239 SDValue N0 = N->getOperand(0);
8240 SDValue N1 = N->getOperand(1);
8241 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8242 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8243 EVT VT = N->getValueType(0);
8245 const TargetOptions &Options = DAG.getTarget().Options;
8249 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8252 // fold (fdiv c1, c2) -> c1/c2
8254 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8256 if (Options.UnsafeFPMath) {
8257 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8259 // Compute the reciprocal 1.0 / c2.
8260 APFloat N1APF = N1CFP->getValueAPF();
8261 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8262 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8263 // Only do the transform if the reciprocal is a legal fp immediate that
8264 // isn't too nasty (eg NaN, denormal, ...).
8265 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8266 (!LegalOperations ||
8267 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8268 // backend)... we should handle this gracefully after Legalize.
8269 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8270 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8271 TLI.isFPImmLegal(Recip, VT)))
8272 return DAG.getNode(ISD::FMUL, DL, VT, N0,
8273 DAG.getConstantFP(Recip, DL, VT));
8276 // If this FDIV is part of a reciprocal square root, it may be folded
8277 // into a target-specific square root estimate instruction.
8278 if (N1.getOpcode() == ISD::FSQRT) {
8279 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8280 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8282 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8283 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8284 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8285 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8286 AddToWorklist(RV.getNode());
8287 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8289 } else if (N1.getOpcode() == ISD::FP_ROUND &&
8290 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8291 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8292 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8293 AddToWorklist(RV.getNode());
8294 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8296 } else if (N1.getOpcode() == ISD::FMUL) {
8297 // Look through an FMUL. Even though this won't remove the FDIV directly,
8298 // it's still worthwhile to get rid of the FSQRT if possible.
8301 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8302 SqrtOp = N1.getOperand(0);
8303 OtherOp = N1.getOperand(1);
8304 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8305 SqrtOp = N1.getOperand(1);
8306 OtherOp = N1.getOperand(0);
8308 if (SqrtOp.getNode()) {
8309 // We found a FSQRT, so try to make this fold:
8310 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8311 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8312 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8313 AddToWorklist(RV.getNode());
8314 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8319 // Fold into a reciprocal estimate and multiply instead of a real divide.
8320 if (SDValue RV = BuildReciprocalEstimate(N1)) {
8321 AddToWorklist(RV.getNode());
8322 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8326 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8327 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8328 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8329 // Both can be negated for free, check to see if at least one is cheaper
8331 if (LHSNeg == 2 || RHSNeg == 2)
8332 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8333 GetNegatedExpression(N0, DAG, LegalOperations),
8334 GetNegatedExpression(N1, DAG, LegalOperations));
8338 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8340 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8341 // Notice that this is not always beneficial. One reason is different target
8342 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8343 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8344 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8345 if (Options.UnsafeFPMath) {
8346 // Skip if current node is a reciprocal.
8347 if (N0CFP && N0CFP->isExactlyValue(1.0))
8350 SmallVector<SDNode *, 4> Users;
8351 // Find all FDIV users of the same divisor.
8352 for (auto *U : N1->uses()) {
8353 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8357 if (TLI.combineRepeatedFPDivisors(Users.size())) {
8358 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8359 // FIXME: This optimization requires some level of fast-math, so the
8360 // created reciprocal node should at least have the 'allowReciprocal'
8361 // fast-math-flag set.
8362 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8364 // Dividend / Divisor -> Dividend * Reciprocal
8365 for (auto *U : Users) {
8366 SDValue Dividend = U->getOperand(0);
8367 if (Dividend != FPOne) {
8368 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8370 CombineTo(U, NewNode);
8371 } else if (U != Reciprocal.getNode()) {
8372 // In the absence of fast-math-flags, this user node is always the
8373 // same node as Reciprocal, but with FMF they may be different nodes.
8374 CombineTo(U, Reciprocal);
8377 return SDValue(N, 0); // N was replaced.
8384 SDValue DAGCombiner::visitFREM(SDNode *N) {
8385 SDValue N0 = N->getOperand(0);
8386 SDValue N1 = N->getOperand(1);
8387 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8388 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8389 EVT VT = N->getValueType(0);
8391 // fold (frem c1, c2) -> fmod(c1,c2)
8393 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8398 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8399 if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8402 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8403 SDValue RV = BuildRsqrtEstimate(N->getOperand(0));
8407 EVT VT = RV.getValueType();
8409 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8410 AddToWorklist(RV.getNode());
8412 // Unfortunately, RV is now NaN if the input was exactly 0.
8413 // Select out this case and force the answer to 0.
8414 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8415 EVT CCVT = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8416 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8417 AddToWorklist(ZeroCmp.getNode());
8418 AddToWorklist(RV.getNode());
8420 return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8424 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8425 SDValue N0 = N->getOperand(0);
8426 SDValue N1 = N->getOperand(1);
8427 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8428 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8429 EVT VT = N->getValueType(0);
8431 if (N0CFP && N1CFP) // Constant fold
8432 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8435 const APFloat& V = N1CFP->getValueAPF();
8436 // copysign(x, c1) -> fabs(x) iff ispos(c1)
8437 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8438 if (!V.isNegative()) {
8439 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8440 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8442 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8443 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8444 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8448 // copysign(fabs(x), y) -> copysign(x, y)
8449 // copysign(fneg(x), y) -> copysign(x, y)
8450 // copysign(copysign(x,z), y) -> copysign(x, y)
8451 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8452 N0.getOpcode() == ISD::FCOPYSIGN)
8453 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8454 N0.getOperand(0), N1);
8456 // copysign(x, abs(y)) -> abs(x)
8457 if (N1.getOpcode() == ISD::FABS)
8458 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8460 // copysign(x, copysign(y,z)) -> copysign(x, z)
8461 if (N1.getOpcode() == ISD::FCOPYSIGN)
8462 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8463 N0, N1.getOperand(1));
8465 // copysign(x, fp_extend(y)) -> copysign(x, y)
8466 // copysign(x, fp_round(y)) -> copysign(x, y)
8467 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8468 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8469 N0, N1.getOperand(0));
8474 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8475 SDValue N0 = N->getOperand(0);
8476 EVT VT = N->getValueType(0);
8477 EVT OpVT = N0.getValueType();
8479 // fold (sint_to_fp c1) -> c1fp
8480 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8481 // ...but only if the target supports immediate floating-point values
8482 (!LegalOperations ||
8483 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8484 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8486 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8487 // but UINT_TO_FP is legal on this target, try to convert.
8488 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8489 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8490 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8491 if (DAG.SignBitIsZero(N0))
8492 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8495 // The next optimizations are desirable only if SELECT_CC can be lowered.
8496 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8497 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8498 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8500 (!LegalOperations ||
8501 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8504 { N0.getOperand(0), N0.getOperand(1),
8505 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8507 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8510 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8511 // (select_cc x, y, 1.0, 0.0,, cc)
8512 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8513 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8514 (!LegalOperations ||
8515 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8518 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8519 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8520 N0.getOperand(0).getOperand(2) };
8521 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8528 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8529 SDValue N0 = N->getOperand(0);
8530 EVT VT = N->getValueType(0);
8531 EVT OpVT = N0.getValueType();
8533 // fold (uint_to_fp c1) -> c1fp
8534 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8535 // ...but only if the target supports immediate floating-point values
8536 (!LegalOperations ||
8537 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8538 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8540 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8541 // but SINT_TO_FP is legal on this target, try to convert.
8542 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8543 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8544 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8545 if (DAG.SignBitIsZero(N0))
8546 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8549 // The next optimizations are desirable only if SELECT_CC can be lowered.
8550 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8551 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8553 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8554 (!LegalOperations ||
8555 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8558 { N0.getOperand(0), N0.getOperand(1),
8559 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8561 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8568 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8569 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8570 SDValue N0 = N->getOperand(0);
8571 EVT VT = N->getValueType(0);
8573 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8576 SDValue Src = N0.getOperand(0);
8577 EVT SrcVT = Src.getValueType();
8578 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8579 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8581 // We can safely assume the conversion won't overflow the output range,
8582 // because (for example) (uint8_t)18293.f is undefined behavior.
8584 // Since we can assume the conversion won't overflow, our decision as to
8585 // whether the input will fit in the float should depend on the minimum
8586 // of the input range and output range.
8588 // This means this is also safe for a signed input and unsigned output, since
8589 // a negative input would lead to undefined behavior.
8590 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8591 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8592 unsigned ActualSize = std::min(InputSize, OutputSize);
8593 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8595 // We can only fold away the float conversion if the input range can be
8596 // represented exactly in the float range.
8597 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8598 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8599 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8601 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8603 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8604 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8607 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8612 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8613 SDValue N0 = N->getOperand(0);
8614 EVT VT = N->getValueType(0);
8616 // fold (fp_to_sint c1fp) -> c1
8617 if (isConstantFPBuildVectorOrConstantFP(N0))
8618 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8620 return FoldIntToFPToInt(N, DAG);
8623 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8624 SDValue N0 = N->getOperand(0);
8625 EVT VT = N->getValueType(0);
8627 // fold (fp_to_uint c1fp) -> c1
8628 if (isConstantFPBuildVectorOrConstantFP(N0))
8629 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8631 return FoldIntToFPToInt(N, DAG);
8634 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8635 SDValue N0 = N->getOperand(0);
8636 SDValue N1 = N->getOperand(1);
8637 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8638 EVT VT = N->getValueType(0);
8640 // fold (fp_round c1fp) -> c1fp
8642 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8644 // fold (fp_round (fp_extend x)) -> x
8645 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8646 return N0.getOperand(0);
8648 // fold (fp_round (fp_round x)) -> (fp_round x)
8649 if (N0.getOpcode() == ISD::FP_ROUND) {
8650 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8651 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8652 // If the first fp_round isn't a value preserving truncation, it might
8653 // introduce a tie in the second fp_round, that wouldn't occur in the
8654 // single-step fp_round we want to fold to.
8655 // In other words, double rounding isn't the same as rounding.
8656 // Also, this is a value preserving truncation iff both fp_round's are.
8657 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8659 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8660 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8664 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8665 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8666 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8667 N0.getOperand(0), N1);
8668 AddToWorklist(Tmp.getNode());
8669 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8670 Tmp, N0.getOperand(1));
8676 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8677 SDValue N0 = N->getOperand(0);
8678 EVT VT = N->getValueType(0);
8679 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8680 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8682 // fold (fp_round_inreg c1fp) -> c1fp
8683 if (N0CFP && isTypeLegal(EVT)) {
8685 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8686 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8692 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8693 SDValue N0 = N->getOperand(0);
8694 EVT VT = N->getValueType(0);
8696 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8697 if (N->hasOneUse() &&
8698 N->use_begin()->getOpcode() == ISD::FP_ROUND)
8701 // fold (fp_extend c1fp) -> c1fp
8702 if (isConstantFPBuildVectorOrConstantFP(N0))
8703 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8705 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8706 if (N0.getOpcode() == ISD::FP16_TO_FP &&
8707 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8708 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8710 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8712 if (N0.getOpcode() == ISD::FP_ROUND
8713 && N0.getNode()->getConstantOperandVal(1) == 1) {
8714 SDValue In = N0.getOperand(0);
8715 if (In.getValueType() == VT) return In;
8716 if (VT.bitsLT(In.getValueType()))
8717 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8718 In, N0.getOperand(1));
8719 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8722 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8723 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8724 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8725 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8726 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8728 LN0->getBasePtr(), N0.getValueType(),
8729 LN0->getMemOperand());
8730 CombineTo(N, ExtLoad);
8731 CombineTo(N0.getNode(),
8732 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8733 N0.getValueType(), ExtLoad,
8734 DAG.getIntPtrConstant(1, SDLoc(N0))),
8735 ExtLoad.getValue(1));
8736 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8742 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8743 SDValue N0 = N->getOperand(0);
8744 EVT VT = N->getValueType(0);
8746 // fold (fceil c1) -> fceil(c1)
8747 if (isConstantFPBuildVectorOrConstantFP(N0))
8748 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8753 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8754 SDValue N0 = N->getOperand(0);
8755 EVT VT = N->getValueType(0);
8757 // fold (ftrunc c1) -> ftrunc(c1)
8758 if (isConstantFPBuildVectorOrConstantFP(N0))
8759 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8764 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8765 SDValue N0 = N->getOperand(0);
8766 EVT VT = N->getValueType(0);
8768 // fold (ffloor c1) -> ffloor(c1)
8769 if (isConstantFPBuildVectorOrConstantFP(N0))
8770 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8775 // FIXME: FNEG and FABS have a lot in common; refactor.
8776 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8777 SDValue N0 = N->getOperand(0);
8778 EVT VT = N->getValueType(0);
8780 // Constant fold FNEG.
8781 if (isConstantFPBuildVectorOrConstantFP(N0))
8782 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8784 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8785 &DAG.getTarget().Options))
8786 return GetNegatedExpression(N0, DAG, LegalOperations);
8788 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8789 // constant pool values.
8790 if (!TLI.isFNegFree(VT) &&
8791 N0.getOpcode() == ISD::BITCAST &&
8792 N0.getNode()->hasOneUse()) {
8793 SDValue Int = N0.getOperand(0);
8794 EVT IntVT = Int.getValueType();
8795 if (IntVT.isInteger() && !IntVT.isVector()) {
8797 if (N0.getValueType().isVector()) {
8798 // For a vector, get a mask such as 0x80... per scalar element
8800 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8801 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8803 // For a scalar, just generate 0x80...
8804 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8807 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8808 DAG.getConstant(SignMask, DL0, IntVT));
8809 AddToWorklist(Int.getNode());
8810 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8814 // (fneg (fmul c, x)) -> (fmul -c, x)
8815 if (N0.getOpcode() == ISD::FMUL &&
8816 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
8817 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8819 APFloat CVal = CFP1->getValueAPF();
8821 if (Level >= AfterLegalizeDAG &&
8822 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8823 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8825 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8826 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8833 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8834 SDValue N0 = N->getOperand(0);
8835 SDValue N1 = N->getOperand(1);
8836 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8837 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8839 if (N0CFP && N1CFP) {
8840 const APFloat &C0 = N0CFP->getValueAPF();
8841 const APFloat &C1 = N1CFP->getValueAPF();
8842 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8846 EVT VT = N->getValueType(0);
8847 // Canonicalize to constant on RHS.
8848 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8854 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8855 SDValue N0 = N->getOperand(0);
8856 SDValue N1 = N->getOperand(1);
8857 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8858 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8860 if (N0CFP && N1CFP) {
8861 const APFloat &C0 = N0CFP->getValueAPF();
8862 const APFloat &C1 = N1CFP->getValueAPF();
8863 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8867 EVT VT = N->getValueType(0);
8868 // Canonicalize to constant on RHS.
8869 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8875 SDValue DAGCombiner::visitFABS(SDNode *N) {
8876 SDValue N0 = N->getOperand(0);
8877 EVT VT = N->getValueType(0);
8879 // fold (fabs c1) -> fabs(c1)
8880 if (isConstantFPBuildVectorOrConstantFP(N0))
8881 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8883 // fold (fabs (fabs x)) -> (fabs x)
8884 if (N0.getOpcode() == ISD::FABS)
8885 return N->getOperand(0);
8887 // fold (fabs (fneg x)) -> (fabs x)
8888 // fold (fabs (fcopysign x, y)) -> (fabs x)
8889 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8890 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8892 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8893 // constant pool values.
8894 if (!TLI.isFAbsFree(VT) &&
8895 N0.getOpcode() == ISD::BITCAST &&
8896 N0.getNode()->hasOneUse()) {
8897 SDValue Int = N0.getOperand(0);
8898 EVT IntVT = Int.getValueType();
8899 if (IntVT.isInteger() && !IntVT.isVector()) {
8901 if (N0.getValueType().isVector()) {
8902 // For a vector, get a mask such as 0x7f... per scalar element
8904 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8905 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8907 // For a scalar, just generate 0x7f...
8908 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8911 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8912 DAG.getConstant(SignMask, DL, IntVT));
8913 AddToWorklist(Int.getNode());
8914 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8921 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8922 SDValue Chain = N->getOperand(0);
8923 SDValue N1 = N->getOperand(1);
8924 SDValue N2 = N->getOperand(2);
8926 // If N is a constant we could fold this into a fallthrough or unconditional
8927 // branch. However that doesn't happen very often in normal code, because
8928 // Instcombine/SimplifyCFG should have handled the available opportunities.
8929 // If we did this folding here, it would be necessary to update the
8930 // MachineBasicBlock CFG, which is awkward.
8932 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8934 if (N1.getOpcode() == ISD::SETCC &&
8935 TLI.isOperationLegalOrCustom(ISD::BR_CC,
8936 N1.getOperand(0).getValueType())) {
8937 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8938 Chain, N1.getOperand(2),
8939 N1.getOperand(0), N1.getOperand(1), N2);
8942 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8943 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8944 (N1.getOperand(0).hasOneUse() &&
8945 N1.getOperand(0).getOpcode() == ISD::SRL))) {
8946 SDNode *Trunc = nullptr;
8947 if (N1.getOpcode() == ISD::TRUNCATE) {
8948 // Look pass the truncate.
8949 Trunc = N1.getNode();
8950 N1 = N1.getOperand(0);
8953 // Match this pattern so that we can generate simpler code:
8956 // %b = and i32 %a, 2
8957 // %c = srl i32 %b, 1
8958 // brcond i32 %c ...
8963 // %b = and i32 %a, 2
8964 // %c = setcc eq %b, 0
8967 // This applies only when the AND constant value has one bit set and the
8968 // SRL constant is equal to the log2 of the AND constant. The back-end is
8969 // smart enough to convert the result into a TEST/JMP sequence.
8970 SDValue Op0 = N1.getOperand(0);
8971 SDValue Op1 = N1.getOperand(1);
8973 if (Op0.getOpcode() == ISD::AND &&
8974 Op1.getOpcode() == ISD::Constant) {
8975 SDValue AndOp1 = Op0.getOperand(1);
8977 if (AndOp1.getOpcode() == ISD::Constant) {
8978 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8980 if (AndConst.isPowerOf2() &&
8981 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8985 getSetCCResultType(Op0.getValueType()),
8986 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
8989 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
8990 MVT::Other, Chain, SetCC, N2);
8991 // Don't add the new BRCond into the worklist or else SimplifySelectCC
8992 // will convert it back to (X & C1) >> C2.
8993 CombineTo(N, NewBRCond, false);
8994 // Truncate is dead.
8996 deleteAndRecombine(Trunc);
8997 // Replace the uses of SRL with SETCC
8998 WorklistRemover DeadNodes(*this);
8999 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9000 deleteAndRecombine(N1.getNode());
9001 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9007 // Restore N1 if the above transformation doesn't match.
9008 N1 = N->getOperand(1);
9011 // Transform br(xor(x, y)) -> br(x != y)
9012 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9013 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9014 SDNode *TheXor = N1.getNode();
9015 SDValue Op0 = TheXor->getOperand(0);
9016 SDValue Op1 = TheXor->getOperand(1);
9017 if (Op0.getOpcode() == Op1.getOpcode()) {
9018 // Avoid missing important xor optimizations.
9019 SDValue Tmp = visitXOR(TheXor);
9020 if (Tmp.getNode()) {
9021 if (Tmp.getNode() != TheXor) {
9022 DEBUG(dbgs() << "\nReplacing.8 ";
9024 dbgs() << "\nWith: ";
9025 Tmp.getNode()->dump(&DAG);
9027 WorklistRemover DeadNodes(*this);
9028 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9029 deleteAndRecombine(TheXor);
9030 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9031 MVT::Other, Chain, Tmp, N2);
9034 // visitXOR has changed XOR's operands or replaced the XOR completely,
9036 return SDValue(N, 0);
9040 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9042 if (isOneConstant(Op0) && Op0.hasOneUse() &&
9043 Op0.getOpcode() == ISD::XOR) {
9044 TheXor = Op0.getNode();
9048 EVT SetCCVT = N1.getValueType();
9050 SetCCVT = getSetCCResultType(SetCCVT);
9051 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9054 Equal ? ISD::SETEQ : ISD::SETNE);
9055 // Replace the uses of XOR with SETCC
9056 WorklistRemover DeadNodes(*this);
9057 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9058 deleteAndRecombine(N1.getNode());
9059 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9060 MVT::Other, Chain, SetCC, N2);
9067 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9069 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9070 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9071 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9073 // If N is a constant we could fold this into a fallthrough or unconditional
9074 // branch. However that doesn't happen very often in normal code, because
9075 // Instcombine/SimplifyCFG should have handled the available opportunities.
9076 // If we did this folding here, it would be necessary to update the
9077 // MachineBasicBlock CFG, which is awkward.
9079 // Use SimplifySetCC to simplify SETCC's.
9080 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9081 CondLHS, CondRHS, CC->get(), SDLoc(N),
9083 if (Simp.getNode()) AddToWorklist(Simp.getNode());
9085 // fold to a simpler setcc
9086 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9087 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9088 N->getOperand(0), Simp.getOperand(2),
9089 Simp.getOperand(0), Simp.getOperand(1),
9095 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9096 /// and that N may be folded in the load / store addressing mode.
9097 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9099 const TargetLowering &TLI) {
9103 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
9104 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9106 VT = LD->getMemoryVT();
9107 AS = LD->getAddressSpace();
9108 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
9109 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9111 VT = ST->getMemoryVT();
9112 AS = ST->getAddressSpace();
9116 TargetLowering::AddrMode AM;
9117 if (N->getOpcode() == ISD::ADD) {
9118 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9121 AM.BaseOffs = Offset->getSExtValue();
9125 } else if (N->getOpcode() == ISD::SUB) {
9126 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9129 AM.BaseOffs = -Offset->getSExtValue();
9136 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9137 VT.getTypeForEVT(*DAG.getContext()), AS);
9140 /// Try turning a load/store into a pre-indexed load/store when the base
9141 /// pointer is an add or subtract and it has other uses besides the load/store.
9142 /// After the transformation, the new indexed load/store has effectively folded
9143 /// the add/subtract in and all of its other uses are redirected to the
9145 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9146 if (Level < AfterLegalizeDAG)
9152 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9153 if (LD->isIndexed())
9155 VT = LD->getMemoryVT();
9156 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9157 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9159 Ptr = LD->getBasePtr();
9160 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9161 if (ST->isIndexed())
9163 VT = ST->getMemoryVT();
9164 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9165 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9167 Ptr = ST->getBasePtr();
9173 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9174 // out. There is no reason to make this a preinc/predec.
9175 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9176 Ptr.getNode()->hasOneUse())
9179 // Ask the target to do addressing mode selection.
9182 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9183 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9186 // Backends without true r+i pre-indexed forms may need to pass a
9187 // constant base with a variable offset so that constant coercion
9188 // will work with the patterns in canonical form.
9189 bool Swapped = false;
9190 if (isa<ConstantSDNode>(BasePtr)) {
9191 std::swap(BasePtr, Offset);
9195 // Don't create a indexed load / store with zero offset.
9196 if (isNullConstant(Offset))
9199 // Try turning it into a pre-indexed load / store except when:
9200 // 1) The new base ptr is a frame index.
9201 // 2) If N is a store and the new base ptr is either the same as or is a
9202 // predecessor of the value being stored.
9203 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9204 // that would create a cycle.
9205 // 4) All uses are load / store ops that use it as old base ptr.
9207 // Check #1. Preinc'ing a frame index would require copying the stack pointer
9208 // (plus the implicit offset) to a register to preinc anyway.
9209 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9214 SDValue Val = cast<StoreSDNode>(N)->getValue();
9215 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9219 // If the offset is a constant, there may be other adds of constants that
9220 // can be folded with this one. We should do this to avoid having to keep
9221 // a copy of the original base pointer.
9222 SmallVector<SDNode *, 16> OtherUses;
9223 if (isa<ConstantSDNode>(Offset))
9224 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9225 UE = BasePtr.getNode()->use_end();
9227 SDUse &Use = UI.getUse();
9228 // Skip the use that is Ptr and uses of other results from BasePtr's
9229 // node (important for nodes that return multiple results).
9230 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9233 if (Use.getUser()->isPredecessorOf(N))
9236 if (Use.getUser()->getOpcode() != ISD::ADD &&
9237 Use.getUser()->getOpcode() != ISD::SUB) {
9242 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9243 if (!isa<ConstantSDNode>(Op1)) {
9248 // FIXME: In some cases, we can be smarter about this.
9249 if (Op1.getValueType() != Offset.getValueType()) {
9254 OtherUses.push_back(Use.getUser());
9258 std::swap(BasePtr, Offset);
9260 // Now check for #3 and #4.
9261 bool RealUse = false;
9263 // Caches for hasPredecessorHelper
9264 SmallPtrSet<const SDNode *, 32> Visited;
9265 SmallVector<const SDNode *, 16> Worklist;
9267 for (SDNode *Use : Ptr.getNode()->uses()) {
9270 if (N->hasPredecessorHelper(Use, Visited, Worklist))
9273 // If Ptr may be folded in addressing mode of other use, then it's
9274 // not profitable to do this transformation.
9275 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9284 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9285 BasePtr, Offset, AM);
9287 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9288 BasePtr, Offset, AM);
9291 DEBUG(dbgs() << "\nReplacing.4 ";
9293 dbgs() << "\nWith: ";
9294 Result.getNode()->dump(&DAG);
9296 WorklistRemover DeadNodes(*this);
9298 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9299 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9301 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9304 // Finally, since the node is now dead, remove it from the graph.
9305 deleteAndRecombine(N);
9308 std::swap(BasePtr, Offset);
9310 // Replace other uses of BasePtr that can be updated to use Ptr
9311 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9312 unsigned OffsetIdx = 1;
9313 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9315 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9316 BasePtr.getNode() && "Expected BasePtr operand");
9318 // We need to replace ptr0 in the following expression:
9319 // x0 * offset0 + y0 * ptr0 = t0
9321 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9323 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9324 // indexed load/store and the expresion that needs to be re-written.
9326 // Therefore, we have:
9327 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9329 ConstantSDNode *CN =
9330 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9332 APInt Offset0 = CN->getAPIntValue();
9333 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9335 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9336 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9337 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9338 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9340 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9342 APInt CNV = Offset0;
9343 if (X0 < 0) CNV = -CNV;
9344 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9345 else CNV = CNV - Offset1;
9347 SDLoc DL(OtherUses[i]);
9349 // We can now generate the new expression.
9350 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9351 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9353 SDValue NewUse = DAG.getNode(Opcode,
9355 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9356 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9357 deleteAndRecombine(OtherUses[i]);
9360 // Replace the uses of Ptr with uses of the updated base value.
9361 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9362 deleteAndRecombine(Ptr.getNode());
9367 /// Try to combine a load/store with a add/sub of the base pointer node into a
9368 /// post-indexed load/store. The transformation folded the add/subtract into the
9369 /// new indexed load/store effectively and all of its uses are redirected to the
9371 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9372 if (Level < AfterLegalizeDAG)
9378 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9379 if (LD->isIndexed())
9381 VT = LD->getMemoryVT();
9382 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9383 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9385 Ptr = LD->getBasePtr();
9386 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9387 if (ST->isIndexed())
9389 VT = ST->getMemoryVT();
9390 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9391 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9393 Ptr = ST->getBasePtr();
9399 if (Ptr.getNode()->hasOneUse())
9402 for (SDNode *Op : Ptr.getNode()->uses()) {
9404 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9409 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9410 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9411 // Don't create a indexed load / store with zero offset.
9412 if (isNullConstant(Offset))
9415 // Try turning it into a post-indexed load / store except when
9416 // 1) All uses are load / store ops that use it as base ptr (and
9417 // it may be folded as addressing mmode).
9418 // 2) Op must be independent of N, i.e. Op is neither a predecessor
9419 // nor a successor of N. Otherwise, if Op is folded that would
9422 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9426 bool TryNext = false;
9427 for (SDNode *Use : BasePtr.getNode()->uses()) {
9428 if (Use == Ptr.getNode())
9431 // If all the uses are load / store addresses, then don't do the
9433 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9434 bool RealUse = false;
9435 for (SDNode *UseUse : Use->uses()) {
9436 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9451 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9452 SDValue Result = isLoad
9453 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9454 BasePtr, Offset, AM)
9455 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9456 BasePtr, Offset, AM);
9459 DEBUG(dbgs() << "\nReplacing.5 ";
9461 dbgs() << "\nWith: ";
9462 Result.getNode()->dump(&DAG);
9464 WorklistRemover DeadNodes(*this);
9466 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9467 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9469 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9472 // Finally, since the node is now dead, remove it from the graph.
9473 deleteAndRecombine(N);
9475 // Replace the uses of Use with uses of the updated base value.
9476 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9477 Result.getValue(isLoad ? 1 : 0));
9478 deleteAndRecombine(Op);
9487 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9488 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9489 ISD::MemIndexedMode AM = LD->getAddressingMode();
9490 assert(AM != ISD::UNINDEXED);
9491 SDValue BP = LD->getOperand(1);
9492 SDValue Inc = LD->getOperand(2);
9494 // Some backends use TargetConstants for load offsets, but don't expect
9495 // TargetConstants in general ADD nodes. We can convert these constants into
9496 // regular Constants (if the constant is not opaque).
9497 assert((Inc.getOpcode() != ISD::TargetConstant ||
9498 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9499 "Cannot split out indexing using opaque target constants");
9500 if (Inc.getOpcode() == ISD::TargetConstant) {
9501 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9502 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9503 ConstInc->getValueType(0));
9507 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9508 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9511 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9512 LoadSDNode *LD = cast<LoadSDNode>(N);
9513 SDValue Chain = LD->getChain();
9514 SDValue Ptr = LD->getBasePtr();
9516 // If load is not volatile and there are no uses of the loaded value (and
9517 // the updated indexed value in case of indexed loads), change uses of the
9518 // chain value into uses of the chain input (i.e. delete the dead load).
9519 if (!LD->isVolatile()) {
9520 if (N->getValueType(1) == MVT::Other) {
9522 if (!N->hasAnyUseOfValue(0)) {
9523 // It's not safe to use the two value CombineTo variant here. e.g.
9524 // v1, chain2 = load chain1, loc
9525 // v2, chain3 = load chain2, loc
9527 // Now we replace use of chain2 with chain1. This makes the second load
9528 // isomorphic to the one we are deleting, and thus makes this load live.
9529 DEBUG(dbgs() << "\nReplacing.6 ";
9531 dbgs() << "\nWith chain: ";
9532 Chain.getNode()->dump(&DAG);
9534 WorklistRemover DeadNodes(*this);
9535 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9538 deleteAndRecombine(N);
9540 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9544 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9546 // If this load has an opaque TargetConstant offset, then we cannot split
9547 // the indexing into an add/sub directly (that TargetConstant may not be
9548 // valid for a different type of node, and we cannot convert an opaque
9549 // target constant into a regular constant).
9550 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9551 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9553 if (!N->hasAnyUseOfValue(0) &&
9554 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9555 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9557 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9558 Index = SplitIndexingFromLoad(LD);
9559 // Try to fold the base pointer arithmetic into subsequent loads and
9561 AddUsersToWorklist(N);
9563 Index = DAG.getUNDEF(N->getValueType(1));
9564 DEBUG(dbgs() << "\nReplacing.7 ";
9566 dbgs() << "\nWith: ";
9567 Undef.getNode()->dump(&DAG);
9568 dbgs() << " and 2 other values\n");
9569 WorklistRemover DeadNodes(*this);
9570 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9571 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9572 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9573 deleteAndRecombine(N);
9574 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9579 // If this load is directly stored, replace the load value with the stored
9581 // TODO: Handle store large -> read small portion.
9582 // TODO: Handle TRUNCSTORE/LOADEXT
9583 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9584 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9585 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9586 if (PrevST->getBasePtr() == Ptr &&
9587 PrevST->getValue().getValueType() == N->getValueType(0))
9588 return CombineTo(N, Chain.getOperand(1), Chain);
9592 // Try to infer better alignment information than the load already has.
9593 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9594 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9595 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9597 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9598 LD->getValueType(0),
9599 Chain, Ptr, LD->getPointerInfo(),
9601 LD->isVolatile(), LD->isNonTemporal(),
9602 LD->isInvariant(), Align, LD->getAAInfo());
9603 if (NewLoad.getNode() != N)
9604 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9609 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9610 : DAG.getSubtarget().useAA();
9612 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9613 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9616 if (UseAA && LD->isUnindexed()) {
9617 // Walk up chain skipping non-aliasing memory nodes.
9618 SDValue BetterChain = FindBetterChain(N, Chain);
9620 // If there is a better chain.
9621 if (Chain != BetterChain) {
9624 // Replace the chain to void dependency.
9625 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9626 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9627 BetterChain, Ptr, LD->getMemOperand());
9629 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9630 LD->getValueType(0),
9631 BetterChain, Ptr, LD->getMemoryVT(),
9632 LD->getMemOperand());
9635 // Create token factor to keep old chain connected.
9636 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9637 MVT::Other, Chain, ReplLoad.getValue(1));
9639 // Make sure the new and old chains are cleaned up.
9640 AddToWorklist(Token.getNode());
9642 // Replace uses with load result and token factor. Don't add users
9644 return CombineTo(N, ReplLoad.getValue(0), Token, false);
9648 // Try transforming N to an indexed load.
9649 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9650 return SDValue(N, 0);
9652 // Try to slice up N to more direct loads if the slices are mapped to
9653 // different register banks or pairing can take place.
9655 return SDValue(N, 0);
9661 /// \brief Helper structure used to slice a load in smaller loads.
9662 /// Basically a slice is obtained from the following sequence:
9663 /// Origin = load Ty1, Base
9664 /// Shift = srl Ty1 Origin, CstTy Amount
9665 /// Inst = trunc Shift to Ty2
9667 /// Then, it will be rewriten into:
9668 /// Slice = load SliceTy, Base + SliceOffset
9669 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9671 /// SliceTy is deduced from the number of bits that are actually used to
9673 struct LoadedSlice {
9674 /// \brief Helper structure used to compute the cost of a slice.
9676 /// Are we optimizing for code size.
9681 unsigned CrossRegisterBanksCopies;
9685 Cost(bool ForCodeSize = false)
9686 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9687 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9689 /// \brief Get the cost of one isolated slice.
9690 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9691 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9692 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9693 EVT TruncType = LS.Inst->getValueType(0);
9694 EVT LoadedType = LS.getLoadedType();
9695 if (TruncType != LoadedType &&
9696 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9700 /// \brief Account for slicing gain in the current cost.
9701 /// Slicing provide a few gains like removing a shift or a
9702 /// truncate. This method allows to grow the cost of the original
9703 /// load with the gain from this slice.
9704 void addSliceGain(const LoadedSlice &LS) {
9705 // Each slice saves a truncate.
9706 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9707 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9708 LS.Inst->getOperand(0).getValueType()))
9710 // If there is a shift amount, this slice gets rid of it.
9713 // If this slice can merge a cross register bank copy, account for it.
9714 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9715 ++CrossRegisterBanksCopies;
9718 Cost &operator+=(const Cost &RHS) {
9720 Truncates += RHS.Truncates;
9721 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9727 bool operator==(const Cost &RHS) const {
9728 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9729 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9730 ZExts == RHS.ZExts && Shift == RHS.Shift;
9733 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9735 bool operator<(const Cost &RHS) const {
9736 // Assume cross register banks copies are as expensive as loads.
9737 // FIXME: Do we want some more target hooks?
9738 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9739 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9740 // Unless we are optimizing for code size, consider the
9741 // expensive operation first.
9742 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9743 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9744 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9745 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9748 bool operator>(const Cost &RHS) const { return RHS < *this; }
9750 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9752 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9754 // The last instruction that represent the slice. This should be a
9755 // truncate instruction.
9757 // The original load instruction.
9759 // The right shift amount in bits from the original load.
9761 // The DAG from which Origin came from.
9762 // This is used to get some contextual information about legal types, etc.
9765 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9766 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9767 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9769 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9770 /// \return Result is \p BitWidth and has used bits set to 1 and
9771 /// not used bits set to 0.
9772 APInt getUsedBits() const {
9773 // Reproduce the trunc(lshr) sequence:
9774 // - Start from the truncated value.
9775 // - Zero extend to the desired bit width.
9777 assert(Origin && "No original load to compare against.");
9778 unsigned BitWidth = Origin->getValueSizeInBits(0);
9779 assert(Inst && "This slice is not bound to an instruction");
9780 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9781 "Extracted slice is bigger than the whole type!");
9782 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9783 UsedBits.setAllBits();
9784 UsedBits = UsedBits.zext(BitWidth);
9789 /// \brief Get the size of the slice to be loaded in bytes.
9790 unsigned getLoadedSize() const {
9791 unsigned SliceSize = getUsedBits().countPopulation();
9792 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9793 return SliceSize / 8;
9796 /// \brief Get the type that will be loaded for this slice.
9797 /// Note: This may not be the final type for the slice.
9798 EVT getLoadedType() const {
9799 assert(DAG && "Missing context");
9800 LLVMContext &Ctxt = *DAG->getContext();
9801 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9804 /// \brief Get the alignment of the load used for this slice.
9805 unsigned getAlignment() const {
9806 unsigned Alignment = Origin->getAlignment();
9807 unsigned Offset = getOffsetFromBase();
9809 Alignment = MinAlign(Alignment, Alignment + Offset);
9813 /// \brief Check if this slice can be rewritten with legal operations.
9814 bool isLegal() const {
9815 // An invalid slice is not legal.
9816 if (!Origin || !Inst || !DAG)
9819 // Offsets are for indexed load only, we do not handle that.
9820 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9823 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9825 // Check that the type is legal.
9826 EVT SliceType = getLoadedType();
9827 if (!TLI.isTypeLegal(SliceType))
9830 // Check that the load is legal for this type.
9831 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9834 // Check that the offset can be computed.
9835 // 1. Check its type.
9836 EVT PtrType = Origin->getBasePtr().getValueType();
9837 if (PtrType == MVT::Untyped || PtrType.isExtended())
9840 // 2. Check that it fits in the immediate.
9841 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9844 // 3. Check that the computation is legal.
9845 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9848 // Check that the zext is legal if it needs one.
9849 EVT TruncateType = Inst->getValueType(0);
9850 if (TruncateType != SliceType &&
9851 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9857 /// \brief Get the offset in bytes of this slice in the original chunk of
9859 /// \pre DAG != nullptr.
9860 uint64_t getOffsetFromBase() const {
9861 assert(DAG && "Missing context.");
9862 bool IsBigEndian = DAG->getDataLayout().isBigEndian();
9863 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9864 uint64_t Offset = Shift / 8;
9865 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9866 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9867 "The size of the original loaded type is not a multiple of a"
9869 // If Offset is bigger than TySizeInBytes, it means we are loading all
9870 // zeros. This should have been optimized before in the process.
9871 assert(TySizeInBytes > Offset &&
9872 "Invalid shift amount for given loaded size");
9874 Offset = TySizeInBytes - Offset - getLoadedSize();
9878 /// \brief Generate the sequence of instructions to load the slice
9879 /// represented by this object and redirect the uses of this slice to
9880 /// this new sequence of instructions.
9881 /// \pre this->Inst && this->Origin are valid Instructions and this
9882 /// object passed the legal check: LoadedSlice::isLegal returned true.
9883 /// \return The last instruction of the sequence used to load the slice.
9884 SDValue loadSlice() const {
9885 assert(Inst && Origin && "Unable to replace a non-existing slice.");
9886 const SDValue &OldBaseAddr = Origin->getBasePtr();
9887 SDValue BaseAddr = OldBaseAddr;
9888 // Get the offset in that chunk of bytes w.r.t. the endianess.
9889 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9890 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9892 // BaseAddr = BaseAddr + Offset.
9893 EVT ArithType = BaseAddr.getValueType();
9895 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9896 DAG->getConstant(Offset, DL, ArithType));
9899 // Create the type of the loaded slice according to its size.
9900 EVT SliceType = getLoadedType();
9902 // Create the load for the slice.
9903 SDValue LastInst = DAG->getLoad(
9904 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9905 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9906 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9907 // If the final type is not the same as the loaded type, this means that
9908 // we have to pad with zero. Create a zero extend for that.
9909 EVT FinalType = Inst->getValueType(0);
9910 if (SliceType != FinalType)
9912 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9916 /// \brief Check if this slice can be merged with an expensive cross register
9917 /// bank copy. E.g.,
9919 /// f = bitcast i32 i to float
9920 bool canMergeExpensiveCrossRegisterBankCopy() const {
9921 if (!Inst || !Inst->hasOneUse())
9923 SDNode *Use = *Inst->use_begin();
9924 if (Use->getOpcode() != ISD::BITCAST)
9926 assert(DAG && "Missing context");
9927 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9928 EVT ResVT = Use->getValueType(0);
9929 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9930 const TargetRegisterClass *ArgRC =
9931 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9932 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9935 // At this point, we know that we perform a cross-register-bank copy.
9936 // Check if it is expensive.
9937 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9938 // Assume bitcasts are cheap, unless both register classes do not
9939 // explicitly share a common sub class.
9940 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9943 // Check if it will be merged with the load.
9944 // 1. Check the alignment constraint.
9945 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
9946 ResVT.getTypeForEVT(*DAG->getContext()));
9948 if (RequiredAlignment > getAlignment())
9951 // 2. Check that the load is a legal operation for that type.
9952 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9955 // 3. Check that we do not have a zext in the way.
9956 if (Inst->getValueType(0) != getLoadedType())
9964 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9965 /// \p UsedBits looks like 0..0 1..1 0..0.
9966 static bool areUsedBitsDense(const APInt &UsedBits) {
9967 // If all the bits are one, this is dense!
9968 if (UsedBits.isAllOnesValue())
9971 // Get rid of the unused bits on the right.
9972 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9973 // Get rid of the unused bits on the left.
9974 if (NarrowedUsedBits.countLeadingZeros())
9975 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9976 // Check that the chunk of bits is completely used.
9977 return NarrowedUsedBits.isAllOnesValue();
9980 /// \brief Check whether or not \p First and \p Second are next to each other
9981 /// in memory. This means that there is no hole between the bits loaded
9982 /// by \p First and the bits loaded by \p Second.
9983 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9984 const LoadedSlice &Second) {
9985 assert(First.Origin == Second.Origin && First.Origin &&
9986 "Unable to match different memory origins.");
9987 APInt UsedBits = First.getUsedBits();
9988 assert((UsedBits & Second.getUsedBits()) == 0 &&
9989 "Slices are not supposed to overlap.");
9990 UsedBits |= Second.getUsedBits();
9991 return areUsedBitsDense(UsedBits);
9994 /// \brief Adjust the \p GlobalLSCost according to the target
9995 /// paring capabilities and the layout of the slices.
9996 /// \pre \p GlobalLSCost should account for at least as many loads as
9997 /// there is in the slices in \p LoadedSlices.
9998 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9999 LoadedSlice::Cost &GlobalLSCost) {
10000 unsigned NumberOfSlices = LoadedSlices.size();
10001 // If there is less than 2 elements, no pairing is possible.
10002 if (NumberOfSlices < 2)
10005 // Sort the slices so that elements that are likely to be next to each
10006 // other in memory are next to each other in the list.
10007 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10008 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10009 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10010 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10012 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10013 // First (resp. Second) is the first (resp. Second) potentially candidate
10014 // to be placed in a paired load.
10015 const LoadedSlice *First = nullptr;
10016 const LoadedSlice *Second = nullptr;
10017 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10018 // Set the beginning of the pair.
10021 Second = &LoadedSlices[CurrSlice];
10023 // If First is NULL, it means we start a new pair.
10024 // Get to the next slice.
10028 EVT LoadedType = First->getLoadedType();
10030 // If the types of the slices are different, we cannot pair them.
10031 if (LoadedType != Second->getLoadedType())
10034 // Check if the target supplies paired loads for this type.
10035 unsigned RequiredAlignment = 0;
10036 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10037 // move to the next pair, this type is hopeless.
10041 // Check if we meet the alignment requirement.
10042 if (RequiredAlignment > First->getAlignment())
10045 // Check that both loads are next to each other in memory.
10046 if (!areSlicesNextToEachOther(*First, *Second))
10049 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10050 --GlobalLSCost.Loads;
10051 // Move to the next pair.
10056 /// \brief Check the profitability of all involved LoadedSlice.
10057 /// Currently, it is considered profitable if there is exactly two
10058 /// involved slices (1) which are (2) next to each other in memory, and
10059 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10061 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10062 /// the elements themselves.
10064 /// FIXME: When the cost model will be mature enough, we can relax
10065 /// constraints (1) and (2).
10066 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10067 const APInt &UsedBits, bool ForCodeSize) {
10068 unsigned NumberOfSlices = LoadedSlices.size();
10069 if (StressLoadSlicing)
10070 return NumberOfSlices > 1;
10073 if (NumberOfSlices != 2)
10077 if (!areUsedBitsDense(UsedBits))
10081 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10082 // The original code has one big load.
10083 OrigCost.Loads = 1;
10084 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10085 const LoadedSlice &LS = LoadedSlices[CurrSlice];
10086 // Accumulate the cost of all the slices.
10087 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10088 GlobalSlicingCost += SliceCost;
10090 // Account as cost in the original configuration the gain obtained
10091 // with the current slices.
10092 OrigCost.addSliceGain(LS);
10095 // If the target supports paired load, adjust the cost accordingly.
10096 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10097 return OrigCost > GlobalSlicingCost;
10100 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10101 /// operations, split it in the various pieces being extracted.
10103 /// This sort of thing is introduced by SROA.
10104 /// This slicing takes care not to insert overlapping loads.
10105 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10106 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10107 if (Level < AfterLegalizeDAG)
10110 LoadSDNode *LD = cast<LoadSDNode>(N);
10111 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10112 !LD->getValueType(0).isInteger())
10115 // Keep track of already used bits to detect overlapping values.
10116 // In that case, we will just abort the transformation.
10117 APInt UsedBits(LD->getValueSizeInBits(0), 0);
10119 SmallVector<LoadedSlice, 4> LoadedSlices;
10121 // Check if this load is used as several smaller chunks of bits.
10122 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10123 // of computation for each trunc.
10124 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10125 UI != UIEnd; ++UI) {
10126 // Skip the uses of the chain.
10127 if (UI.getUse().getResNo() != 0)
10130 SDNode *User = *UI;
10131 unsigned Shift = 0;
10133 // Check if this is a trunc(lshr).
10134 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10135 isa<ConstantSDNode>(User->getOperand(1))) {
10136 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10137 User = *User->use_begin();
10140 // At this point, User is a Truncate, iff we encountered, trunc or
10142 if (User->getOpcode() != ISD::TRUNCATE)
10145 // The width of the type must be a power of 2 and greater than 8-bits.
10146 // Otherwise the load cannot be represented in LLVM IR.
10147 // Moreover, if we shifted with a non-8-bits multiple, the slice
10148 // will be across several bytes. We do not support that.
10149 unsigned Width = User->getValueSizeInBits(0);
10150 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10153 // Build the slice for this chain of computations.
10154 LoadedSlice LS(User, LD, Shift, &DAG);
10155 APInt CurrentUsedBits = LS.getUsedBits();
10157 // Check if this slice overlaps with another.
10158 if ((CurrentUsedBits & UsedBits) != 0)
10160 // Update the bits used globally.
10161 UsedBits |= CurrentUsedBits;
10163 // Check if the new slice would be legal.
10167 // Record the slice.
10168 LoadedSlices.push_back(LS);
10171 // Abort slicing if it does not seem to be profitable.
10172 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10177 // Rewrite each chain to use an independent load.
10178 // By construction, each chain can be represented by a unique load.
10180 // Prepare the argument for the new token factor for all the slices.
10181 SmallVector<SDValue, 8> ArgChains;
10182 for (SmallVectorImpl<LoadedSlice>::const_iterator
10183 LSIt = LoadedSlices.begin(),
10184 LSItEnd = LoadedSlices.end();
10185 LSIt != LSItEnd; ++LSIt) {
10186 SDValue SliceInst = LSIt->loadSlice();
10187 CombineTo(LSIt->Inst, SliceInst, true);
10188 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10189 SliceInst = SliceInst.getOperand(0);
10190 assert(SliceInst->getOpcode() == ISD::LOAD &&
10191 "It takes more than a zext to get to the loaded slice!!");
10192 ArgChains.push_back(SliceInst.getValue(1));
10195 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10197 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10201 /// Check to see if V is (and load (ptr), imm), where the load is having
10202 /// specific bytes cleared out. If so, return the byte size being masked out
10203 /// and the shift amount.
10204 static std::pair<unsigned, unsigned>
10205 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10206 std::pair<unsigned, unsigned> Result(0, 0);
10208 // Check for the structure we're looking for.
10209 if (V->getOpcode() != ISD::AND ||
10210 !isa<ConstantSDNode>(V->getOperand(1)) ||
10211 !ISD::isNormalLoad(V->getOperand(0).getNode()))
10214 // Check the chain and pointer.
10215 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10216 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
10218 // The store should be chained directly to the load or be an operand of a
10220 if (LD == Chain.getNode())
10222 else if (Chain->getOpcode() != ISD::TokenFactor)
10223 return Result; // Fail.
10226 for (const SDValue &ChainOp : Chain->op_values())
10227 if (ChainOp.getNode() == LD) {
10231 if (!isOk) return Result;
10234 // This only handles simple types.
10235 if (V.getValueType() != MVT::i16 &&
10236 V.getValueType() != MVT::i32 &&
10237 V.getValueType() != MVT::i64)
10240 // Check the constant mask. Invert it so that the bits being masked out are
10241 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
10242 // follow the sign bit for uniformity.
10243 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10244 unsigned NotMaskLZ = countLeadingZeros(NotMask);
10245 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
10246 unsigned NotMaskTZ = countTrailingZeros(NotMask);
10247 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
10248 if (NotMaskLZ == 64) return Result; // All zero mask.
10250 // See if we have a continuous run of bits. If so, we have 0*1+0*
10251 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10254 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10255 if (V.getValueType() != MVT::i64 && NotMaskLZ)
10256 NotMaskLZ -= 64-V.getValueSizeInBits();
10258 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10259 switch (MaskedBytes) {
10263 default: return Result; // All one mask, or 5-byte mask.
10266 // Verify that the first bit starts at a multiple of mask so that the access
10267 // is aligned the same as the access width.
10268 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10270 Result.first = MaskedBytes;
10271 Result.second = NotMaskTZ/8;
10276 /// Check to see if IVal is something that provides a value as specified by
10277 /// MaskInfo. If so, replace the specified store with a narrower store of
10278 /// truncated IVal.
10280 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10281 SDValue IVal, StoreSDNode *St,
10283 unsigned NumBytes = MaskInfo.first;
10284 unsigned ByteShift = MaskInfo.second;
10285 SelectionDAG &DAG = DC->getDAG();
10287 // Check to see if IVal is all zeros in the part being masked in by the 'or'
10288 // that uses this. If not, this is not a replacement.
10289 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10290 ByteShift*8, (ByteShift+NumBytes)*8);
10291 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10293 // Check that it is legal on the target to do this. It is legal if the new
10294 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10296 MVT VT = MVT::getIntegerVT(NumBytes*8);
10297 if (!DC->isTypeLegal(VT))
10300 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
10301 // shifted by ByteShift and truncated down to NumBytes.
10304 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10305 DAG.getConstant(ByteShift*8, DL,
10306 DC->getShiftAmountTy(IVal.getValueType())));
10309 // Figure out the offset for the store and the alignment of the access.
10311 unsigned NewAlign = St->getAlignment();
10313 if (DAG.getDataLayout().isLittleEndian())
10314 StOffset = ByteShift;
10316 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10318 SDValue Ptr = St->getBasePtr();
10321 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10322 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10323 NewAlign = MinAlign(NewAlign, StOffset);
10326 // Truncate down to the new size.
10327 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10330 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10331 St->getPointerInfo().getWithOffset(StOffset),
10332 false, false, NewAlign).getNode();
10336 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10337 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10338 /// narrowing the load and store if it would end up being a win for performance
10340 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10341 StoreSDNode *ST = cast<StoreSDNode>(N);
10342 if (ST->isVolatile())
10345 SDValue Chain = ST->getChain();
10346 SDValue Value = ST->getValue();
10347 SDValue Ptr = ST->getBasePtr();
10348 EVT VT = Value.getValueType();
10350 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10353 unsigned Opc = Value.getOpcode();
10355 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10356 // is a byte mask indicating a consecutive number of bytes, check to see if
10357 // Y is known to provide just those bytes. If so, we try to replace the
10358 // load + replace + store sequence with a single (narrower) store, which makes
10360 if (Opc == ISD::OR) {
10361 std::pair<unsigned, unsigned> MaskedLoad;
10362 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10363 if (MaskedLoad.first)
10364 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10365 Value.getOperand(1), ST,this))
10366 return SDValue(NewST, 0);
10368 // Or is commutative, so try swapping X and Y.
10369 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10370 if (MaskedLoad.first)
10371 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10372 Value.getOperand(0), ST,this))
10373 return SDValue(NewST, 0);
10376 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10377 Value.getOperand(1).getOpcode() != ISD::Constant)
10380 SDValue N0 = Value.getOperand(0);
10381 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10382 Chain == SDValue(N0.getNode(), 1)) {
10383 LoadSDNode *LD = cast<LoadSDNode>(N0);
10384 if (LD->getBasePtr() != Ptr ||
10385 LD->getPointerInfo().getAddrSpace() !=
10386 ST->getPointerInfo().getAddrSpace())
10389 // Find the type to narrow it the load / op / store to.
10390 SDValue N1 = Value.getOperand(1);
10391 unsigned BitWidth = N1.getValueSizeInBits();
10392 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10393 if (Opc == ISD::AND)
10394 Imm ^= APInt::getAllOnesValue(BitWidth);
10395 if (Imm == 0 || Imm.isAllOnesValue())
10397 unsigned ShAmt = Imm.countTrailingZeros();
10398 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10399 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10400 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10401 // The narrowing should be profitable, the load/store operation should be
10402 // legal (or custom) and the store size should be equal to the NewVT width.
10403 while (NewBW < BitWidth &&
10404 (NewVT.getStoreSizeInBits() != NewBW ||
10405 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10406 !TLI.isNarrowingProfitable(VT, NewVT))) {
10407 NewBW = NextPowerOf2(NewBW);
10408 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10410 if (NewBW >= BitWidth)
10413 // If the lsb changed does not start at the type bitwidth boundary,
10414 // start at the previous one.
10416 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10417 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10418 std::min(BitWidth, ShAmt + NewBW));
10419 if ((Imm & Mask) == Imm) {
10420 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10421 if (Opc == ISD::AND)
10422 NewImm ^= APInt::getAllOnesValue(NewBW);
10423 uint64_t PtrOff = ShAmt / 8;
10424 // For big endian targets, we need to adjust the offset to the pointer to
10425 // load the correct bytes.
10426 if (DAG.getDataLayout().isBigEndian())
10427 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10429 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10430 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10431 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10434 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10435 Ptr.getValueType(), Ptr,
10436 DAG.getConstant(PtrOff, SDLoc(LD),
10437 Ptr.getValueType()));
10438 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10439 LD->getChain(), NewPtr,
10440 LD->getPointerInfo().getWithOffset(PtrOff),
10441 LD->isVolatile(), LD->isNonTemporal(),
10442 LD->isInvariant(), NewAlign,
10444 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10445 DAG.getConstant(NewImm, SDLoc(Value),
10447 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10449 ST->getPointerInfo().getWithOffset(PtrOff),
10450 false, false, NewAlign);
10452 AddToWorklist(NewPtr.getNode());
10453 AddToWorklist(NewLD.getNode());
10454 AddToWorklist(NewVal.getNode());
10455 WorklistRemover DeadNodes(*this);
10456 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10465 /// For a given floating point load / store pair, if the load value isn't used
10466 /// by any other operations, then consider transforming the pair to integer
10467 /// load / store operations if the target deems the transformation profitable.
10468 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10469 StoreSDNode *ST = cast<StoreSDNode>(N);
10470 SDValue Chain = ST->getChain();
10471 SDValue Value = ST->getValue();
10472 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10473 Value.hasOneUse() &&
10474 Chain == SDValue(Value.getNode(), 1)) {
10475 LoadSDNode *LD = cast<LoadSDNode>(Value);
10476 EVT VT = LD->getMemoryVT();
10477 if (!VT.isFloatingPoint() ||
10478 VT != ST->getMemoryVT() ||
10479 LD->isNonTemporal() ||
10480 ST->isNonTemporal() ||
10481 LD->getPointerInfo().getAddrSpace() != 0 ||
10482 ST->getPointerInfo().getAddrSpace() != 0)
10485 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10486 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10487 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10488 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10489 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10492 unsigned LDAlign = LD->getAlignment();
10493 unsigned STAlign = ST->getAlignment();
10494 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10495 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10496 if (LDAlign < ABIAlign || STAlign < ABIAlign)
10499 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10500 LD->getChain(), LD->getBasePtr(),
10501 LD->getPointerInfo(),
10502 false, false, false, LDAlign);
10504 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10505 NewLD, ST->getBasePtr(),
10506 ST->getPointerInfo(),
10507 false, false, STAlign);
10509 AddToWorklist(NewLD.getNode());
10510 AddToWorklist(NewST.getNode());
10511 WorklistRemover DeadNodes(*this);
10512 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10521 /// Helper struct to parse and store a memory address as base + index + offset.
10522 /// We ignore sign extensions when it is safe to do so.
10523 /// The following two expressions are not equivalent. To differentiate we need
10524 /// to store whether there was a sign extension involved in the index
10526 /// (load (i64 add (i64 copyfromreg %c)
10527 /// (i64 signextend (add (i8 load %index)
10531 /// (load (i64 add (i64 copyfromreg %c)
10532 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
10534 struct BaseIndexOffset {
10538 bool IsIndexSignExt;
10540 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10542 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10543 bool IsIndexSignExt) :
10544 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10546 bool equalBaseIndex(const BaseIndexOffset &Other) {
10547 return Other.Base == Base && Other.Index == Index &&
10548 Other.IsIndexSignExt == IsIndexSignExt;
10551 /// Parses tree in Ptr for base, index, offset addresses.
10552 static BaseIndexOffset match(SDValue Ptr) {
10553 bool IsIndexSignExt = false;
10555 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10556 // instruction, then it could be just the BASE or everything else we don't
10557 // know how to handle. Just use Ptr as BASE and give up.
10558 if (Ptr->getOpcode() != ISD::ADD)
10559 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10561 // We know that we have at least an ADD instruction. Try to pattern match
10562 // the simple case of BASE + OFFSET.
10563 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10564 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10565 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10569 // Inside a loop the current BASE pointer is calculated using an ADD and a
10570 // MUL instruction. In this case Ptr is the actual BASE pointer.
10571 // (i64 add (i64 %array_ptr)
10572 // (i64 mul (i64 %induction_var)
10573 // (i64 %element_size)))
10574 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10575 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10577 // Look at Base + Index + Offset cases.
10578 SDValue Base = Ptr->getOperand(0);
10579 SDValue IndexOffset = Ptr->getOperand(1);
10581 // Skip signextends.
10582 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10583 IndexOffset = IndexOffset->getOperand(0);
10584 IsIndexSignExt = true;
10587 // Either the case of Base + Index (no offset) or something else.
10588 if (IndexOffset->getOpcode() != ISD::ADD)
10589 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10591 // Now we have the case of Base + Index + offset.
10592 SDValue Index = IndexOffset->getOperand(0);
10593 SDValue Offset = IndexOffset->getOperand(1);
10595 if (!isa<ConstantSDNode>(Offset))
10596 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10598 // Ignore signextends.
10599 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10600 Index = Index->getOperand(0);
10601 IsIndexSignExt = true;
10602 } else IsIndexSignExt = false;
10604 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10605 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10610 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10612 ArrayRef<MemOpLink> Stores,
10614 SmallVector<SDValue, 8> BuildVector;
10616 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I)
10617 BuildVector.push_back(cast<StoreSDNode>(Stores[I].MemNode)->getValue());
10619 return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10622 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10623 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10624 unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10625 // Make sure we have something to merge.
10629 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10630 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10631 unsigned LatestNodeUsed = 0;
10633 for (unsigned i=0; i < NumElem; ++i) {
10634 // Find a chain for the new wide-store operand. Notice that some
10635 // of the store nodes that we found may not be selected for inclusion
10636 // in the wide store. The chain we use needs to be the chain of the
10637 // latest store node which is *used* and replaced by the wide store.
10638 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10639 LatestNodeUsed = i;
10642 // The latest Node in the DAG.
10643 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10644 SDLoc DL(StoreNodes[0].MemNode);
10648 // Find a legal type for the vector store.
10649 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10650 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10651 if (IsConstantSrc) {
10652 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Ty);
10654 SmallVector<SDValue, 8> Ops;
10655 for (unsigned i = 0; i < NumElem ; ++i) {
10656 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10657 SDValue Val = St->getValue();
10658 // All of the operands of a BUILD_VECTOR must have the same type.
10659 if (Val.getValueType() != MemVT)
10661 Ops.push_back(Val);
10664 // Build the extracted vector elements back into a vector.
10665 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10668 // We should always use a vector store when merging extracted vector
10669 // elements, so this path implies a store of constants.
10670 assert(IsConstantSrc && "Merged vector elements should use vector store");
10672 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
10673 APInt StoreInt(SizeInBits, 0);
10675 // Construct a single integer constant which is made of the smaller
10676 // constant inputs.
10677 bool IsLE = DAG.getDataLayout().isLittleEndian();
10678 for (unsigned i = 0; i < NumElem ; ++i) {
10679 unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10680 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10681 SDValue Val = St->getValue();
10682 StoreInt <<= ElementSizeBytes * 8;
10683 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10684 StoreInt |= C->getAPIntValue().zext(SizeInBits);
10685 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10686 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
10688 llvm_unreachable("Invalid constant element type");
10692 // Create the new Load and Store operations.
10693 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
10694 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10697 SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10698 FirstInChain->getBasePtr(),
10699 FirstInChain->getPointerInfo(),
10701 FirstInChain->getAlignment());
10703 // Replace the last store with the new store
10704 CombineTo(LatestOp, NewStore);
10705 // Erase all other stores.
10706 for (unsigned i = 0; i < NumElem ; ++i) {
10707 if (StoreNodes[i].MemNode == LatestOp)
10709 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10710 // ReplaceAllUsesWith will replace all uses that existed when it was
10711 // called, but graph optimizations may cause new ones to appear. For
10712 // example, the case in pr14333 looks like
10714 // St's chain -> St -> another store -> X
10716 // And the only difference from St to the other store is the chain.
10717 // When we change it's chain to be St's chain they become identical,
10718 // get CSEed and the net result is that X is now a use of St.
10719 // Since we know that St is redundant, just iterate.
10720 while (!St->use_empty())
10721 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10722 deleteAndRecombine(St);
10728 static bool allowableAlignment(const SelectionDAG &DAG,
10729 const TargetLowering &TLI, EVT EVTTy,
10730 unsigned AS, unsigned Align) {
10731 if (TLI.allowsMisalignedMemoryAccesses(EVTTy, AS, Align))
10734 Type *Ty = EVTTy.getTypeForEVT(*DAG.getContext());
10735 unsigned ABIAlignment = DAG.getDataLayout().getPrefTypeAlignment(Ty);
10736 return (Align >= ABIAlignment);
10739 void DAGCombiner::getStoreMergeAndAliasCandidates(
10740 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
10741 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
10742 // This holds the base pointer, index, and the offset in bytes from the base
10744 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10746 // We must have a base and an offset.
10747 if (!BasePtr.Base.getNode())
10750 // Do not handle stores to undef base pointers.
10751 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10754 // Walk up the chain and look for nodes with offsets from the same
10755 // base pointer. Stop when reaching an instruction with a different kind
10756 // or instruction which has a different base pointer.
10757 EVT MemVT = St->getMemoryVT();
10759 StoreSDNode *Index = St;
10761 // If the chain has more than one use, then we can't reorder the mem ops.
10762 if (Index != St && !SDValue(Index, 0)->hasOneUse())
10765 // Find the base pointer and offset for this memory node.
10766 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10768 // Check that the base pointer is the same as the original one.
10769 if (!Ptr.equalBaseIndex(BasePtr))
10772 // The memory operands must not be volatile.
10773 if (Index->isVolatile() || Index->isIndexed())
10777 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10778 if (St->isTruncatingStore())
10781 // The stored memory type must be the same.
10782 if (Index->getMemoryVT() != MemVT)
10785 // We found a potential memory operand to merge.
10786 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10788 // Find the next memory operand in the chain. If the next operand in the
10789 // chain is a store then move up and continue the scan with the next
10790 // memory operand. If the next operand is a load save it and use alias
10791 // information to check if it interferes with anything.
10792 SDNode *NextInChain = Index->getChain().getNode();
10794 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10795 // We found a store node. Use it for the next iteration.
10798 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10799 if (Ldn->isVolatile()) {
10804 // Save the load node for later. Continue the scan.
10805 AliasLoadNodes.push_back(Ldn);
10806 NextInChain = Ldn->getChain().getNode();
10816 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10817 if (OptLevel == CodeGenOpt::None)
10820 EVT MemVT = St->getMemoryVT();
10821 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10822 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10823 Attribute::NoImplicitFloat);
10825 // This function cannot currently deal with non-byte-sized memory sizes.
10826 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10829 // Don't merge vectors into wider inputs.
10830 if (MemVT.isVector() || !MemVT.isSimple())
10833 // Perform an early exit check. Do not bother looking at stored values that
10834 // are not constants, loads, or extracted vector elements.
10835 SDValue StoredVal = St->getValue();
10836 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10837 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10838 isa<ConstantFPSDNode>(StoredVal);
10839 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10841 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10844 // Only look at ends of store sequences.
10845 SDValue Chain = SDValue(St, 0);
10846 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10849 // Save the LoadSDNodes that we find in the chain.
10850 // We need to make sure that these nodes do not interfere with
10851 // any of the store nodes.
10852 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10854 // Save the StoreSDNodes that we find in the chain.
10855 SmallVector<MemOpLink, 8> StoreNodes;
10857 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
10859 // Check if there is anything to merge.
10860 if (StoreNodes.size() < 2)
10863 // Sort the memory operands according to their distance from the base pointer.
10864 std::sort(StoreNodes.begin(), StoreNodes.end(),
10865 [](MemOpLink LHS, MemOpLink RHS) {
10866 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10867 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10868 LHS.SequenceNum > RHS.SequenceNum);
10871 // Scan the memory operations on the chain and find the first non-consecutive
10872 // store memory address.
10873 unsigned LastConsecutiveStore = 0;
10874 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10875 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10877 // Check that the addresses are consecutive starting from the second
10878 // element in the list of stores.
10880 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10881 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10885 bool Alias = false;
10886 // Check if this store interferes with any of the loads that we found.
10887 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10888 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10892 // We found a load that alias with this store. Stop the sequence.
10896 // Mark this node as useful.
10897 LastConsecutiveStore = i;
10900 // The node with the lowest store address.
10901 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10902 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
10903 unsigned FirstStoreAlign = FirstInChain->getAlignment();
10905 // Store the constants into memory as one consecutive store.
10906 if (IsConstantSrc) {
10907 unsigned LastLegalType = 0;
10908 unsigned LastLegalVectorType = 0;
10909 bool NonZero = false;
10910 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10911 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10912 SDValue StoredVal = St->getValue();
10914 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10915 NonZero |= !C->isNullValue();
10916 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10917 NonZero |= !C->getConstantFPValue()->isNullValue();
10923 // Find a legal type for the constant store.
10924 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
10925 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
10926 if (TLI.isTypeLegal(StoreTy) &&
10927 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS,
10928 FirstStoreAlign)) {
10929 LastLegalType = i+1;
10930 // Or check whether a truncstore is legal.
10931 } else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10932 TargetLowering::TypePromoteInteger) {
10933 EVT LegalizedStoredValueTy =
10934 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10935 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10936 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
10937 FirstStoreAlign)) {
10938 LastLegalType = i + 1;
10942 // Find a legal type for the vector store.
10943 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10944 if (TLI.isTypeLegal(Ty) &&
10945 allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign)) {
10946 LastLegalVectorType = i + 1;
10951 // We only use vectors if the constant is known to be zero or the target
10952 // allows it and the function is not marked with the noimplicitfloat
10955 LastLegalVectorType = 0;
10956 } else if (NonZero && !TLI.storeOfVectorConstantIsCheap(MemVT,
10957 LastLegalVectorType,
10959 LastLegalVectorType = 0;
10962 // Check if we found a legal integer type to store.
10963 if (LastLegalType == 0 && LastLegalVectorType == 0)
10966 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10967 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10969 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10973 // When extracting multiple vector elements, try to store them
10974 // in one vector store rather than a sequence of scalar stores.
10975 if (IsExtractVecEltSrc) {
10976 unsigned NumElem = 0;
10977 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10978 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10979 SDValue StoredVal = St->getValue();
10980 // This restriction could be loosened.
10981 // Bail out if any stored values are not elements extracted from a vector.
10982 // It should be possible to handle mixed sources, but load sources need
10983 // more careful handling (see the block of code below that handles
10984 // consecutive loads).
10985 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10988 // Find a legal type for the vector store.
10989 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10990 if (TLI.isTypeLegal(Ty) &&
10991 allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign))
10995 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10999 // Below we handle the case of multiple consecutive stores that
11000 // come from multiple consecutive loads. We merge them into a single
11001 // wide load and a single wide store.
11003 // Look for load nodes which are used by the stored values.
11004 SmallVector<MemOpLink, 8> LoadNodes;
11006 // Find acceptable loads. Loads need to have the same chain (token factor),
11007 // must not be zext, volatile, indexed, and they must be consecutive.
11008 BaseIndexOffset LdBasePtr;
11009 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11010 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11011 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11014 // Loads must only have one use.
11015 if (!Ld->hasNUsesOfValue(1, 0))
11018 // The memory operands must not be volatile.
11019 if (Ld->isVolatile() || Ld->isIndexed())
11022 // We do not accept ext loads.
11023 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11026 // The stored memory type must be the same.
11027 if (Ld->getMemoryVT() != MemVT)
11030 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11031 // If this is not the first ptr that we check.
11032 if (LdBasePtr.Base.getNode()) {
11033 // The base ptr must be the same.
11034 if (!LdPtr.equalBaseIndex(LdBasePtr))
11037 // Check that all other base pointers are the same as this one.
11041 // We found a potential memory operand to merge.
11042 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11045 if (LoadNodes.size() < 2)
11048 // If we have load/store pair instructions and we only have two values,
11050 unsigned RequiredAlignment;
11051 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11052 St->getAlignment() >= RequiredAlignment)
11055 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11056 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11057 unsigned FirstLoadAlign = FirstLoad->getAlignment();
11059 // Scan the memory operations on the chain and find the first non-consecutive
11060 // load memory address. These variables hold the index in the store node
11062 unsigned LastConsecutiveLoad = 0;
11063 // This variable refers to the size and not index in the array.
11064 unsigned LastLegalVectorType = 0;
11065 unsigned LastLegalIntegerType = 0;
11066 StartAddress = LoadNodes[0].OffsetFromBase;
11067 SDValue FirstChain = FirstLoad->getChain();
11068 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11069 // All loads much share the same chain.
11070 if (LoadNodes[i].MemNode->getChain() != FirstChain)
11073 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11074 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11076 LastConsecutiveLoad = i;
11078 // Find a legal type for the vector store.
11079 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
11080 if (TLI.isTypeLegal(StoreTy) &&
11081 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
11082 allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign)) {
11083 LastLegalVectorType = i + 1;
11086 // Find a legal type for the integer store.
11087 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11088 StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11089 if (TLI.isTypeLegal(StoreTy) &&
11090 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
11091 allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign))
11092 LastLegalIntegerType = i + 1;
11093 // Or check whether a truncstore and extload is legal.
11094 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
11095 TargetLowering::TypePromoteInteger) {
11096 EVT LegalizedStoredValueTy =
11097 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
11098 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11099 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11100 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11101 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11102 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
11103 FirstStoreAlign) &&
11104 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstLoadAS,
11106 LastLegalIntegerType = i+1;
11110 // Only use vector types if the vector type is larger than the integer type.
11111 // If they are the same, use integers.
11112 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11113 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11115 // We add +1 here because the LastXXX variables refer to location while
11116 // the NumElem refers to array/index size.
11117 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11118 NumElem = std::min(LastLegalType, NumElem);
11123 // The latest Node in the DAG.
11124 unsigned LatestNodeUsed = 0;
11125 for (unsigned i=1; i<NumElem; ++i) {
11126 // Find a chain for the new wide-store operand. Notice that some
11127 // of the store nodes that we found may not be selected for inclusion
11128 // in the wide store. The chain we use needs to be the chain of the
11129 // latest store node which is *used* and replaced by the wide store.
11130 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11131 LatestNodeUsed = i;
11134 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11136 // Find if it is better to use vectors or integers to load and store
11140 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
11142 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11143 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11146 SDLoc LoadDL(LoadNodes[0].MemNode);
11147 SDLoc StoreDL(StoreNodes[0].MemNode);
11149 SDValue NewLoad = DAG.getLoad(
11150 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11151 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11153 SDValue NewStore = DAG.getStore(
11154 LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11155 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11157 // Replace one of the loads with the new load.
11158 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11159 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11160 SDValue(NewLoad.getNode(), 1));
11162 // Remove the rest of the load chains.
11163 for (unsigned i = 1; i < NumElem ; ++i) {
11164 // Replace all chain users of the old load nodes with the chain of the new
11166 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11167 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11170 // Replace the last store with the new store.
11171 CombineTo(LatestOp, NewStore);
11172 // Erase all other stores.
11173 for (unsigned i = 0; i < NumElem ; ++i) {
11174 // Remove all Store nodes.
11175 if (StoreNodes[i].MemNode == LatestOp)
11177 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11178 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11179 deleteAndRecombine(St);
11185 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11186 StoreSDNode *ST = cast<StoreSDNode>(N);
11187 SDValue Chain = ST->getChain();
11188 SDValue Value = ST->getValue();
11189 SDValue Ptr = ST->getBasePtr();
11191 // If this is a store of a bit convert, store the input value if the
11192 // resultant store does not need a higher alignment than the original.
11193 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11194 ST->isUnindexed()) {
11195 unsigned OrigAlign = ST->getAlignment();
11196 EVT SVT = Value.getOperand(0).getValueType();
11197 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11198 SVT.getTypeForEVT(*DAG.getContext()));
11199 if (Align <= OrigAlign &&
11200 ((!LegalOperations && !ST->isVolatile()) ||
11201 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11202 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11203 Ptr, ST->getPointerInfo(), ST->isVolatile(),
11204 ST->isNonTemporal(), OrigAlign,
11208 // Turn 'store undef, Ptr' -> nothing.
11209 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11212 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11213 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11214 // NOTE: If the original store is volatile, this transform must not increase
11215 // the number of stores. For example, on x86-32 an f64 can be stored in one
11216 // processor operation but an i64 (which is not legal) requires two. So the
11217 // transform should not be done in this case.
11218 if (Value.getOpcode() != ISD::TargetConstantFP) {
11220 switch (CFP->getSimpleValueType(0).SimpleTy) {
11221 default: llvm_unreachable("Unknown FP type");
11222 case MVT::f16: // We don't do this for these yet.
11228 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11229 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11231 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11232 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11234 return DAG.getStore(Chain, SDLoc(N), Tmp,
11235 Ptr, ST->getMemOperand());
11239 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11240 !ST->isVolatile()) ||
11241 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11243 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11244 getZExtValue(), SDLoc(CFP), MVT::i64);
11245 return DAG.getStore(Chain, SDLoc(N), Tmp,
11246 Ptr, ST->getMemOperand());
11249 if (!ST->isVolatile() &&
11250 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11251 // Many FP stores are not made apparent until after legalize, e.g. for
11252 // argument passing. Since this is so common, custom legalize the
11253 // 64-bit integer store into two 32-bit stores.
11254 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11255 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11256 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11257 if (DAG.getDataLayout().isBigEndian())
11260 unsigned Alignment = ST->getAlignment();
11261 bool isVolatile = ST->isVolatile();
11262 bool isNonTemporal = ST->isNonTemporal();
11263 AAMDNodes AAInfo = ST->getAAInfo();
11267 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11268 Ptr, ST->getPointerInfo(),
11269 isVolatile, isNonTemporal,
11270 ST->getAlignment(), AAInfo);
11271 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11272 DAG.getConstant(4, DL, Ptr.getValueType()));
11273 Alignment = MinAlign(Alignment, 4U);
11274 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11275 Ptr, ST->getPointerInfo().getWithOffset(4),
11276 isVolatile, isNonTemporal,
11277 Alignment, AAInfo);
11278 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11287 // Try to infer better alignment information than the store already has.
11288 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11289 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11290 if (Align > ST->getAlignment()) {
11292 DAG.getTruncStore(Chain, SDLoc(N), Value,
11293 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11294 ST->isVolatile(), ST->isNonTemporal(), Align,
11296 if (NewStore.getNode() != N)
11297 return CombineTo(ST, NewStore, true);
11302 // Try transforming a pair floating point load / store ops to integer
11303 // load / store ops.
11304 SDValue NewST = TransformFPLoadStorePair(N);
11305 if (NewST.getNode())
11308 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11309 : DAG.getSubtarget().useAA();
11311 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11312 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11315 if (UseAA && ST->isUnindexed()) {
11316 // Walk up chain skipping non-aliasing memory nodes.
11317 SDValue BetterChain = FindBetterChain(N, Chain);
11319 // If there is a better chain.
11320 if (Chain != BetterChain) {
11323 // Replace the chain to avoid dependency.
11324 if (ST->isTruncatingStore()) {
11325 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11326 ST->getMemoryVT(), ST->getMemOperand());
11328 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11329 ST->getMemOperand());
11332 // Create token to keep both nodes around.
11333 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11334 MVT::Other, Chain, ReplStore);
11336 // Make sure the new and old chains are cleaned up.
11337 AddToWorklist(Token.getNode());
11339 // Don't add users to work list.
11340 return CombineTo(N, Token, false);
11344 // Try transforming N to an indexed store.
11345 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11346 return SDValue(N, 0);
11348 // FIXME: is there such a thing as a truncating indexed store?
11349 if (ST->isTruncatingStore() && ST->isUnindexed() &&
11350 Value.getValueType().isInteger()) {
11351 // See if we can simplify the input to this truncstore with knowledge that
11352 // only the low bits are being used. For example:
11353 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
11355 GetDemandedBits(Value,
11356 APInt::getLowBitsSet(
11357 Value.getValueType().getScalarType().getSizeInBits(),
11358 ST->getMemoryVT().getScalarType().getSizeInBits()));
11359 AddToWorklist(Value.getNode());
11360 if (Shorter.getNode())
11361 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11362 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11364 // Otherwise, see if we can simplify the operation with
11365 // SimplifyDemandedBits, which only works if the value has a single use.
11366 if (SimplifyDemandedBits(Value,
11367 APInt::getLowBitsSet(
11368 Value.getValueType().getScalarType().getSizeInBits(),
11369 ST->getMemoryVT().getScalarType().getSizeInBits())))
11370 return SDValue(N, 0);
11373 // If this is a load followed by a store to the same location, then the store
11375 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11376 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11377 ST->isUnindexed() && !ST->isVolatile() &&
11378 // There can't be any side effects between the load and store, such as
11379 // a call or store.
11380 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11381 // The store is dead, remove it.
11386 // If this is a store followed by a store with the same value to the same
11387 // location, then the store is dead/noop.
11388 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11389 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11390 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11391 ST1->isUnindexed() && !ST1->isVolatile()) {
11392 // The store is dead, remove it.
11397 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11398 // truncating store. We can do this even if this is already a truncstore.
11399 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11400 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11401 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11402 ST->getMemoryVT())) {
11403 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11404 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11407 // Only perform this optimization before the types are legal, because we
11408 // don't want to perform this optimization on every DAGCombine invocation.
11410 bool EverChanged = false;
11413 // There can be multiple store sequences on the same chain.
11414 // Keep trying to merge store sequences until we are unable to do so
11415 // or until we merge the last store on the chain.
11416 bool Changed = MergeConsecutiveStores(ST);
11417 EverChanged |= Changed;
11418 if (!Changed) break;
11419 } while (ST->getOpcode() != ISD::DELETED_NODE);
11422 return SDValue(N, 0);
11425 return ReduceLoadOpStoreWidth(N);
11428 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11429 SDValue InVec = N->getOperand(0);
11430 SDValue InVal = N->getOperand(1);
11431 SDValue EltNo = N->getOperand(2);
11434 // If the inserted element is an UNDEF, just use the input vector.
11435 if (InVal.getOpcode() == ISD::UNDEF)
11438 EVT VT = InVec.getValueType();
11440 // If we can't generate a legal BUILD_VECTOR, exit
11441 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11444 // Check that we know which element is being inserted
11445 if (!isa<ConstantSDNode>(EltNo))
11447 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11449 // Canonicalize insert_vector_elt dag nodes.
11451 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11452 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11454 // Do this only if the child insert_vector node has one use; also
11455 // do this only if indices are both constants and Idx1 < Idx0.
11456 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11457 && isa<ConstantSDNode>(InVec.getOperand(2))) {
11458 unsigned OtherElt =
11459 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11460 if (Elt < OtherElt) {
11462 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11463 InVec.getOperand(0), InVal, EltNo);
11464 AddToWorklist(NewOp.getNode());
11465 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11466 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11470 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11471 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
11472 // vector elements.
11473 SmallVector<SDValue, 8> Ops;
11474 // Do not combine these two vectors if the output vector will not replace
11475 // the input vector.
11476 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11477 Ops.append(InVec.getNode()->op_begin(),
11478 InVec.getNode()->op_end());
11479 } else if (InVec.getOpcode() == ISD::UNDEF) {
11480 unsigned NElts = VT.getVectorNumElements();
11481 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11486 // Insert the element
11487 if (Elt < Ops.size()) {
11488 // All the operands of BUILD_VECTOR must have the same type;
11489 // we enforce that here.
11490 EVT OpVT = Ops[0].getValueType();
11491 if (InVal.getValueType() != OpVT)
11492 InVal = OpVT.bitsGT(InVal.getValueType()) ?
11493 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11494 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11498 // Return the new vector
11499 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11502 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11503 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11504 EVT ResultVT = EVE->getValueType(0);
11505 EVT VecEltVT = InVecVT.getVectorElementType();
11506 unsigned Align = OriginalLoad->getAlignment();
11507 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
11508 VecEltVT.getTypeForEVT(*DAG.getContext()));
11510 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11515 SDValue NewPtr = OriginalLoad->getBasePtr();
11517 EVT PtrType = NewPtr.getValueType();
11518 MachinePointerInfo MPI;
11520 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11521 int Elt = ConstEltNo->getZExtValue();
11522 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11523 Offset = DAG.getConstant(PtrOff, DL, PtrType);
11524 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11526 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11527 Offset = DAG.getNode(
11528 ISD::MUL, DL, PtrType, Offset,
11529 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11530 MPI = OriginalLoad->getPointerInfo();
11532 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11534 // The replacement we need to do here is a little tricky: we need to
11535 // replace an extractelement of a load with a load.
11536 // Use ReplaceAllUsesOfValuesWith to do the replacement.
11537 // Note that this replacement assumes that the extractvalue is the only
11538 // use of the load; that's okay because we don't want to perform this
11539 // transformation in other cases anyway.
11542 if (ResultVT.bitsGT(VecEltVT)) {
11543 // If the result type of vextract is wider than the load, then issue an
11544 // extending load instead.
11545 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11549 Load = DAG.getExtLoad(
11550 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11551 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11552 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11553 Chain = Load.getValue(1);
11555 Load = DAG.getLoad(
11556 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11557 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11558 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11559 Chain = Load.getValue(1);
11560 if (ResultVT.bitsLT(VecEltVT))
11561 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11563 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11565 WorklistRemover DeadNodes(*this);
11566 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11567 SDValue To[] = { Load, Chain };
11568 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11569 // Since we're explicitly calling ReplaceAllUses, add the new node to the
11570 // worklist explicitly as well.
11571 AddToWorklist(Load.getNode());
11572 AddUsersToWorklist(Load.getNode()); // Add users too
11573 // Make sure to revisit this node to clean it up; it will usually be dead.
11574 AddToWorklist(EVE);
11576 return SDValue(EVE, 0);
11579 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11580 // (vextract (scalar_to_vector val, 0) -> val
11581 SDValue InVec = N->getOperand(0);
11582 EVT VT = InVec.getValueType();
11583 EVT NVT = N->getValueType(0);
11585 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11586 // Check if the result type doesn't match the inserted element type. A
11587 // SCALAR_TO_VECTOR may truncate the inserted element and the
11588 // EXTRACT_VECTOR_ELT may widen the extracted vector.
11589 SDValue InOp = InVec.getOperand(0);
11590 if (InOp.getValueType() != NVT) {
11591 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11592 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11597 SDValue EltNo = N->getOperand(1);
11598 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11600 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11601 // We only perform this optimization before the op legalization phase because
11602 // we may introduce new vector instructions which are not backed by TD
11603 // patterns. For example on AVX, extracting elements from a wide vector
11604 // without using extract_subvector. However, if we can find an underlying
11605 // scalar value, then we can always use that.
11606 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11608 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11609 int NumElem = VT.getVectorNumElements();
11610 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11611 // Find the new index to extract from.
11612 int OrigElt = SVOp->getMaskElt(Elt);
11614 // Extracting an undef index is undef.
11616 return DAG.getUNDEF(NVT);
11618 // Select the right vector half to extract from.
11620 if (OrigElt < NumElem) {
11621 SVInVec = InVec->getOperand(0);
11623 SVInVec = InVec->getOperand(1);
11624 OrigElt -= NumElem;
11627 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11628 SDValue InOp = SVInVec.getOperand(OrigElt);
11629 if (InOp.getValueType() != NVT) {
11630 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11631 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11637 // FIXME: We should handle recursing on other vector shuffles and
11638 // scalar_to_vector here as well.
11640 if (!LegalOperations) {
11641 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
11642 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11643 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11647 bool BCNumEltsChanged = false;
11648 EVT ExtVT = VT.getVectorElementType();
11651 // If the result of load has to be truncated, then it's not necessarily
11653 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11656 if (InVec.getOpcode() == ISD::BITCAST) {
11657 // Don't duplicate a load with other uses.
11658 if (!InVec.hasOneUse())
11661 EVT BCVT = InVec.getOperand(0).getValueType();
11662 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11664 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11665 BCNumEltsChanged = true;
11666 InVec = InVec.getOperand(0);
11667 ExtVT = BCVT.getVectorElementType();
11670 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11671 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11672 ISD::isNormalLoad(InVec.getNode()) &&
11673 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11674 SDValue Index = N->getOperand(1);
11675 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11676 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11680 // Perform only after legalization to ensure build_vector / vector_shuffle
11681 // optimizations have already been done.
11682 if (!LegalOperations) return SDValue();
11684 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11685 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11686 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11689 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11691 LoadSDNode *LN0 = nullptr;
11692 const ShuffleVectorSDNode *SVN = nullptr;
11693 if (ISD::isNormalLoad(InVec.getNode())) {
11694 LN0 = cast<LoadSDNode>(InVec);
11695 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11696 InVec.getOperand(0).getValueType() == ExtVT &&
11697 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11698 // Don't duplicate a load with other uses.
11699 if (!InVec.hasOneUse())
11702 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11703 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11704 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11706 // (load $addr+1*size)
11708 // Don't duplicate a load with other uses.
11709 if (!InVec.hasOneUse())
11712 // If the bit convert changed the number of elements, it is unsafe
11713 // to examine the mask.
11714 if (BCNumEltsChanged)
11717 // Select the input vector, guarding against out of range extract vector.
11718 unsigned NumElems = VT.getVectorNumElements();
11719 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11720 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11722 if (InVec.getOpcode() == ISD::BITCAST) {
11723 // Don't duplicate a load with other uses.
11724 if (!InVec.hasOneUse())
11727 InVec = InVec.getOperand(0);
11729 if (ISD::isNormalLoad(InVec.getNode())) {
11730 LN0 = cast<LoadSDNode>(InVec);
11731 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11732 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11736 // Make sure we found a non-volatile load and the extractelement is
11738 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11741 // If Idx was -1 above, Elt is going to be -1, so just return undef.
11743 return DAG.getUNDEF(LVT);
11745 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11751 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11752 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11753 // We perform this optimization post type-legalization because
11754 // the type-legalizer often scalarizes integer-promoted vectors.
11755 // Performing this optimization before may create bit-casts which
11756 // will be type-legalized to complex code sequences.
11757 // We perform this optimization only before the operation legalizer because we
11758 // may introduce illegal operations.
11759 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11762 unsigned NumInScalars = N->getNumOperands();
11764 EVT VT = N->getValueType(0);
11766 // Check to see if this is a BUILD_VECTOR of a bunch of values
11767 // which come from any_extend or zero_extend nodes. If so, we can create
11768 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11769 // optimizations. We do not handle sign-extend because we can't fill the sign
11771 EVT SourceType = MVT::Other;
11772 bool AllAnyExt = true;
11774 for (unsigned i = 0; i != NumInScalars; ++i) {
11775 SDValue In = N->getOperand(i);
11776 // Ignore undef inputs.
11777 if (In.getOpcode() == ISD::UNDEF) continue;
11779 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
11780 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11782 // Abort if the element is not an extension.
11783 if (!ZeroExt && !AnyExt) {
11784 SourceType = MVT::Other;
11788 // The input is a ZeroExt or AnyExt. Check the original type.
11789 EVT InTy = In.getOperand(0).getValueType();
11791 // Check that all of the widened source types are the same.
11792 if (SourceType == MVT::Other)
11795 else if (InTy != SourceType) {
11796 // Multiple income types. Abort.
11797 SourceType = MVT::Other;
11801 // Check if all of the extends are ANY_EXTENDs.
11802 AllAnyExt &= AnyExt;
11805 // In order to have valid types, all of the inputs must be extended from the
11806 // same source type and all of the inputs must be any or zero extend.
11807 // Scalar sizes must be a power of two.
11808 EVT OutScalarTy = VT.getScalarType();
11809 bool ValidTypes = SourceType != MVT::Other &&
11810 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11811 isPowerOf2_32(SourceType.getSizeInBits());
11813 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11814 // turn into a single shuffle instruction.
11818 bool isLE = DAG.getDataLayout().isLittleEndian();
11819 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11820 assert(ElemRatio > 1 && "Invalid element size ratio");
11821 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11822 DAG.getConstant(0, SDLoc(N), SourceType);
11824 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11825 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11827 // Populate the new build_vector
11828 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11829 SDValue Cast = N->getOperand(i);
11830 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11831 Cast.getOpcode() == ISD::ZERO_EXTEND ||
11832 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11834 if (Cast.getOpcode() == ISD::UNDEF)
11835 In = DAG.getUNDEF(SourceType);
11837 In = Cast->getOperand(0);
11838 unsigned Index = isLE ? (i * ElemRatio) :
11839 (i * ElemRatio + (ElemRatio - 1));
11841 assert(Index < Ops.size() && "Invalid index");
11845 // The type of the new BUILD_VECTOR node.
11846 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11847 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11848 "Invalid vector size");
11849 // Check if the new vector type is legal.
11850 if (!isTypeLegal(VecVT)) return SDValue();
11852 // Make the new BUILD_VECTOR.
11853 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11855 // The new BUILD_VECTOR node has the potential to be further optimized.
11856 AddToWorklist(BV.getNode());
11857 // Bitcast to the desired type.
11858 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11861 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11862 EVT VT = N->getValueType(0);
11864 unsigned NumInScalars = N->getNumOperands();
11867 EVT SrcVT = MVT::Other;
11868 unsigned Opcode = ISD::DELETED_NODE;
11869 unsigned NumDefs = 0;
11871 for (unsigned i = 0; i != NumInScalars; ++i) {
11872 SDValue In = N->getOperand(i);
11873 unsigned Opc = In.getOpcode();
11875 if (Opc == ISD::UNDEF)
11878 // If all scalar values are floats and converted from integers.
11879 if (Opcode == ISD::DELETED_NODE &&
11880 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11887 EVT InVT = In.getOperand(0).getValueType();
11889 // If all scalar values are typed differently, bail out. It's chosen to
11890 // simplify BUILD_VECTOR of integer types.
11891 if (SrcVT == MVT::Other)
11898 // If the vector has just one element defined, it's not worth to fold it into
11899 // a vectorized one.
11903 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11904 && "Should only handle conversion from integer to float.");
11905 assert(SrcVT != MVT::Other && "Cannot determine source type!");
11907 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11909 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11912 // Just because the floating-point vector type is legal does not necessarily
11913 // mean that the corresponding integer vector type is.
11914 if (!isTypeLegal(NVT))
11917 SmallVector<SDValue, 8> Opnds;
11918 for (unsigned i = 0; i != NumInScalars; ++i) {
11919 SDValue In = N->getOperand(i);
11921 if (In.getOpcode() == ISD::UNDEF)
11922 Opnds.push_back(DAG.getUNDEF(SrcVT));
11924 Opnds.push_back(In.getOperand(0));
11926 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11927 AddToWorklist(BV.getNode());
11929 return DAG.getNode(Opcode, dl, VT, BV);
11932 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11933 unsigned NumInScalars = N->getNumOperands();
11935 EVT VT = N->getValueType(0);
11937 // A vector built entirely of undefs is undef.
11938 if (ISD::allOperandsUndef(N))
11939 return DAG.getUNDEF(VT);
11941 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11944 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11947 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11948 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11949 // at most two distinct vectors, turn this into a shuffle node.
11951 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11952 if (!isTypeLegal(VT))
11955 // May only combine to shuffle after legalize if shuffle is legal.
11956 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11959 SDValue VecIn1, VecIn2;
11960 bool UsesZeroVector = false;
11961 for (unsigned i = 0; i != NumInScalars; ++i) {
11962 SDValue Op = N->getOperand(i);
11963 // Ignore undef inputs.
11964 if (Op.getOpcode() == ISD::UNDEF) continue;
11966 // See if we can combine this build_vector into a blend with a zero vector.
11967 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
11968 UsesZeroVector = true;
11972 // If this input is something other than a EXTRACT_VECTOR_ELT with a
11973 // constant index, bail out.
11974 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11975 !isa<ConstantSDNode>(Op.getOperand(1))) {
11976 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11980 // We allow up to two distinct input vectors.
11981 SDValue ExtractedFromVec = Op.getOperand(0);
11982 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11985 if (!VecIn1.getNode()) {
11986 VecIn1 = ExtractedFromVec;
11987 } else if (!VecIn2.getNode() && !UsesZeroVector) {
11988 VecIn2 = ExtractedFromVec;
11990 // Too many inputs.
11991 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11996 // If everything is good, we can make a shuffle operation.
11997 if (VecIn1.getNode()) {
11998 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11999 SmallVector<int, 8> Mask;
12000 for (unsigned i = 0; i != NumInScalars; ++i) {
12001 unsigned Opcode = N->getOperand(i).getOpcode();
12002 if (Opcode == ISD::UNDEF) {
12003 Mask.push_back(-1);
12007 // Operands can also be zero.
12008 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12009 assert(UsesZeroVector &&
12010 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12011 "Unexpected node found!");
12012 Mask.push_back(NumInScalars+i);
12016 // If extracting from the first vector, just use the index directly.
12017 SDValue Extract = N->getOperand(i);
12018 SDValue ExtVal = Extract.getOperand(1);
12019 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12020 if (Extract.getOperand(0) == VecIn1) {
12021 Mask.push_back(ExtIndex);
12025 // Otherwise, use InIdx + InputVecSize
12026 Mask.push_back(InNumElements + ExtIndex);
12029 // Avoid introducing illegal shuffles with zero.
12030 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12033 // We can't generate a shuffle node with mismatched input and output types.
12034 // Attempt to transform a single input vector to the correct type.
12035 if ((VT != VecIn1.getValueType())) {
12036 // If the input vector type has a different base type to the output
12037 // vector type, bail out.
12038 EVT VTElemType = VT.getVectorElementType();
12039 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12040 (VecIn2.getNode() &&
12041 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12044 // If the input vector is too small, widen it.
12045 // We only support widening of vectors which are half the size of the
12046 // output registers. For example XMM->YMM widening on X86 with AVX.
12047 EVT VecInT = VecIn1.getValueType();
12048 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12049 // If we only have one small input, widen it by adding undef values.
12050 if (!VecIn2.getNode())
12051 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12052 DAG.getUNDEF(VecIn1.getValueType()));
12053 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12054 // If we have two small inputs of the same type, try to concat them.
12055 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12056 VecIn2 = SDValue(nullptr, 0);
12059 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12060 // If the input vector is too large, try to split it.
12061 // We don't support having two input vectors that are too large.
12062 // If the zero vector was used, we can not split the vector,
12063 // since we'd need 3 inputs.
12064 if (UsesZeroVector || VecIn2.getNode())
12067 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12070 // Try to replace VecIn1 with two extract_subvectors
12071 // No need to update the masks, they should still be correct.
12072 VecIn2 = DAG.getNode(
12073 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12074 DAG.getConstant(VT.getVectorNumElements(), dl,
12075 TLI.getVectorIdxTy(DAG.getDataLayout())));
12076 VecIn1 = DAG.getNode(
12077 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12078 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12083 if (UsesZeroVector)
12084 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12085 DAG.getConstantFP(0.0, dl, VT);
12087 // If VecIn2 is unused then change it to undef.
12088 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12090 // Check that we were able to transform all incoming values to the same
12092 if (VecIn2.getValueType() != VecIn1.getValueType() ||
12093 VecIn1.getValueType() != VT)
12096 // Return the new VECTOR_SHUFFLE node.
12100 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12106 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12107 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12108 EVT OpVT = N->getOperand(0).getValueType();
12110 // If the operands are legal vectors, leave them alone.
12111 if (TLI.isTypeLegal(OpVT))
12115 EVT VT = N->getValueType(0);
12116 SmallVector<SDValue, 8> Ops;
12118 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12119 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12121 // Keep track of what we encounter.
12122 bool AnyInteger = false;
12123 bool AnyFP = false;
12124 for (const SDValue &Op : N->ops()) {
12125 if (ISD::BITCAST == Op.getOpcode() &&
12126 !Op.getOperand(0).getValueType().isVector())
12127 Ops.push_back(Op.getOperand(0));
12128 else if (ISD::UNDEF == Op.getOpcode())
12129 Ops.push_back(ScalarUndef);
12133 // Note whether we encounter an integer or floating point scalar.
12134 // If it's neither, bail out, it could be something weird like x86mmx.
12135 EVT LastOpVT = Ops.back().getValueType();
12136 if (LastOpVT.isFloatingPoint())
12138 else if (LastOpVT.isInteger())
12144 // If any of the operands is a floating point scalar bitcast to a vector,
12145 // use floating point types throughout, and bitcast everything.
12146 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12148 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12149 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12151 for (SDValue &Op : Ops) {
12152 if (Op.getValueType() == SVT)
12154 if (Op.getOpcode() == ISD::UNDEF)
12157 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12162 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12163 VT.getSizeInBits() / SVT.getSizeInBits());
12164 return DAG.getNode(ISD::BITCAST, DL, VT,
12165 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12168 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12169 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
12170 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
12171 // inputs come from at most two distinct vectors, turn this into a shuffle
12174 // If we only have one input vector, we don't need to do any concatenation.
12175 if (N->getNumOperands() == 1)
12176 return N->getOperand(0);
12178 // Check if all of the operands are undefs.
12179 EVT VT = N->getValueType(0);
12180 if (ISD::allOperandsUndef(N))
12181 return DAG.getUNDEF(VT);
12183 // Optimize concat_vectors where all but the first of the vectors are undef.
12184 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12185 return Op.getOpcode() == ISD::UNDEF;
12187 SDValue In = N->getOperand(0);
12188 assert(In.getValueType().isVector() && "Must concat vectors");
12190 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12191 if (In->getOpcode() == ISD::BITCAST &&
12192 !In->getOperand(0)->getValueType(0).isVector()) {
12193 SDValue Scalar = In->getOperand(0);
12195 // If the bitcast type isn't legal, it might be a trunc of a legal type;
12196 // look through the trunc so we can still do the transform:
12197 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12198 if (Scalar->getOpcode() == ISD::TRUNCATE &&
12199 !TLI.isTypeLegal(Scalar.getValueType()) &&
12200 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12201 Scalar = Scalar->getOperand(0);
12203 EVT SclTy = Scalar->getValueType(0);
12205 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12208 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12209 VT.getSizeInBits() / SclTy.getSizeInBits());
12210 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12213 SDLoc dl = SDLoc(N);
12214 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12215 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12219 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12220 // We have already tested above for an UNDEF only concatenation.
12221 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12222 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12223 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12224 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12226 bool AllBuildVectorsOrUndefs =
12227 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12228 if (AllBuildVectorsOrUndefs) {
12229 SmallVector<SDValue, 8> Opnds;
12230 EVT SVT = VT.getScalarType();
12233 if (!SVT.isFloatingPoint()) {
12234 // If BUILD_VECTOR are from built from integer, they may have different
12235 // operand types. Get the smallest type and truncate all operands to it.
12236 bool FoundMinVT = false;
12237 for (const SDValue &Op : N->ops())
12238 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12239 EVT OpSVT = Op.getOperand(0)->getValueType(0);
12240 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12243 assert(FoundMinVT && "Concat vector type mismatch");
12246 for (const SDValue &Op : N->ops()) {
12247 EVT OpVT = Op.getValueType();
12248 unsigned NumElts = OpVT.getVectorNumElements();
12250 if (ISD::UNDEF == Op.getOpcode())
12251 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12253 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12254 if (SVT.isFloatingPoint()) {
12255 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12256 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12258 for (unsigned i = 0; i != NumElts; ++i)
12260 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12265 assert(VT.getVectorNumElements() == Opnds.size() &&
12266 "Concat vector type mismatch");
12267 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12270 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12271 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12274 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12275 // nodes often generate nop CONCAT_VECTOR nodes.
12276 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12277 // place the incoming vectors at the exact same location.
12278 SDValue SingleSource = SDValue();
12279 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12281 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12282 SDValue Op = N->getOperand(i);
12284 if (Op.getOpcode() == ISD::UNDEF)
12287 // Check if this is the identity extract:
12288 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12291 // Find the single incoming vector for the extract_subvector.
12292 if (SingleSource.getNode()) {
12293 if (Op.getOperand(0) != SingleSource)
12296 SingleSource = Op.getOperand(0);
12298 // Check the source type is the same as the type of the result.
12299 // If not, this concat may extend the vector, so we can not
12300 // optimize it away.
12301 if (SingleSource.getValueType() != N->getValueType(0))
12305 unsigned IdentityIndex = i * PartNumElem;
12306 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12307 // The extract index must be constant.
12311 // Check that we are reading from the identity index.
12312 if (CS->getZExtValue() != IdentityIndex)
12316 if (SingleSource.getNode())
12317 return SingleSource;
12322 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12323 EVT NVT = N->getValueType(0);
12324 SDValue V = N->getOperand(0);
12326 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12328 // (extract_subvec (concat V1, V2, ...), i)
12331 // Only operand 0 is checked as 'concat' assumes all inputs of the same
12333 if (V->getOperand(0).getValueType() != NVT)
12335 unsigned Idx = N->getConstantOperandVal(1);
12336 unsigned NumElems = NVT.getVectorNumElements();
12337 assert((Idx % NumElems) == 0 &&
12338 "IDX in concat is not a multiple of the result vector length.");
12339 return V->getOperand(Idx / NumElems);
12343 if (V->getOpcode() == ISD::BITCAST)
12344 V = V.getOperand(0);
12346 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12348 // Handle only simple case where vector being inserted and vector
12349 // being extracted are of same type, and are half size of larger vectors.
12350 EVT BigVT = V->getOperand(0).getValueType();
12351 EVT SmallVT = V->getOperand(1).getValueType();
12352 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12355 // Only handle cases where both indexes are constants with the same type.
12356 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12357 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12359 if (InsIdx && ExtIdx &&
12360 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12361 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12363 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12365 // indices are equal or bit offsets are equal => V1
12366 // otherwise => (extract_subvec V1, ExtIdx)
12367 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12368 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12369 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12370 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12371 DAG.getNode(ISD::BITCAST, dl,
12372 N->getOperand(0).getValueType(),
12373 V->getOperand(0)), N->getOperand(1));
12380 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12381 SDValue V, SelectionDAG &DAG) {
12383 EVT VT = V.getValueType();
12385 switch (V.getOpcode()) {
12389 case ISD::CONCAT_VECTORS: {
12390 EVT OpVT = V->getOperand(0).getValueType();
12391 int OpSize = OpVT.getVectorNumElements();
12392 SmallBitVector OpUsedElements(OpSize, false);
12393 bool FoundSimplification = false;
12394 SmallVector<SDValue, 4> NewOps;
12395 NewOps.reserve(V->getNumOperands());
12396 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12397 SDValue Op = V->getOperand(i);
12398 bool OpUsed = false;
12399 for (int j = 0; j < OpSize; ++j)
12400 if (UsedElements[i * OpSize + j]) {
12401 OpUsedElements[j] = true;
12405 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12406 : DAG.getUNDEF(OpVT));
12407 FoundSimplification |= Op == NewOps.back();
12408 OpUsedElements.reset();
12410 if (FoundSimplification)
12411 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12415 case ISD::INSERT_SUBVECTOR: {
12416 SDValue BaseV = V->getOperand(0);
12417 SDValue SubV = V->getOperand(1);
12418 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12422 int SubSize = SubV.getValueType().getVectorNumElements();
12423 int Idx = IdxN->getZExtValue();
12424 bool SubVectorUsed = false;
12425 SmallBitVector SubUsedElements(SubSize, false);
12426 for (int i = 0; i < SubSize; ++i)
12427 if (UsedElements[i + Idx]) {
12428 SubVectorUsed = true;
12429 SubUsedElements[i] = true;
12430 UsedElements[i + Idx] = false;
12433 // Now recurse on both the base and sub vectors.
12434 SDValue SimplifiedSubV =
12436 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12437 : DAG.getUNDEF(SubV.getValueType());
12438 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12439 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12440 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12441 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12447 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12448 SDValue N1, SelectionDAG &DAG) {
12449 EVT VT = SVN->getValueType(0);
12450 int NumElts = VT.getVectorNumElements();
12451 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12452 for (int M : SVN->getMask())
12453 if (M >= 0 && M < NumElts)
12454 N0UsedElements[M] = true;
12455 else if (M >= NumElts)
12456 N1UsedElements[M - NumElts] = true;
12458 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12459 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12460 if (S0 == N0 && S1 == N1)
12463 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12466 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12467 // or turn a shuffle of a single concat into simpler shuffle then concat.
12468 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12469 EVT VT = N->getValueType(0);
12470 unsigned NumElts = VT.getVectorNumElements();
12472 SDValue N0 = N->getOperand(0);
12473 SDValue N1 = N->getOperand(1);
12474 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12476 SmallVector<SDValue, 4> Ops;
12477 EVT ConcatVT = N0.getOperand(0).getValueType();
12478 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12479 unsigned NumConcats = NumElts / NumElemsPerConcat;
12481 // Special case: shuffle(concat(A,B)) can be more efficiently represented
12482 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12483 // half vector elements.
12484 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12485 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12486 SVN->getMask().end(), [](int i) { return i == -1; })) {
12487 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12488 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12489 N1 = DAG.getUNDEF(ConcatVT);
12490 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12493 // Look at every vector that's inserted. We're looking for exact
12494 // subvector-sized copies from a concatenated vector
12495 for (unsigned I = 0; I != NumConcats; ++I) {
12496 // Make sure we're dealing with a copy.
12497 unsigned Begin = I * NumElemsPerConcat;
12498 bool AllUndef = true, NoUndef = true;
12499 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12500 if (SVN->getMaskElt(J) >= 0)
12507 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12510 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12511 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12514 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12515 if (FirstElt < N0.getNumOperands())
12516 Ops.push_back(N0.getOperand(FirstElt));
12518 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12520 } else if (AllUndef) {
12521 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12522 } else { // Mixed with general masks and undefs, can't do optimization.
12527 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12530 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12531 EVT VT = N->getValueType(0);
12532 unsigned NumElts = VT.getVectorNumElements();
12534 SDValue N0 = N->getOperand(0);
12535 SDValue N1 = N->getOperand(1);
12537 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12539 // Canonicalize shuffle undef, undef -> undef
12540 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12541 return DAG.getUNDEF(VT);
12543 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12545 // Canonicalize shuffle v, v -> v, undef
12547 SmallVector<int, 8> NewMask;
12548 for (unsigned i = 0; i != NumElts; ++i) {
12549 int Idx = SVN->getMaskElt(i);
12550 if (Idx >= (int)NumElts) Idx -= NumElts;
12551 NewMask.push_back(Idx);
12553 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12557 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
12558 if (N0.getOpcode() == ISD::UNDEF) {
12559 SmallVector<int, 8> NewMask;
12560 for (unsigned i = 0; i != NumElts; ++i) {
12561 int Idx = SVN->getMaskElt(i);
12563 if (Idx >= (int)NumElts)
12566 Idx = -1; // remove reference to lhs
12568 NewMask.push_back(Idx);
12570 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12574 // Remove references to rhs if it is undef
12575 if (N1.getOpcode() == ISD::UNDEF) {
12576 bool Changed = false;
12577 SmallVector<int, 8> NewMask;
12578 for (unsigned i = 0; i != NumElts; ++i) {
12579 int Idx = SVN->getMaskElt(i);
12580 if (Idx >= (int)NumElts) {
12584 NewMask.push_back(Idx);
12587 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12590 // If it is a splat, check if the argument vector is another splat or a
12592 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12593 SDNode *V = N0.getNode();
12595 // If this is a bit convert that changes the element type of the vector but
12596 // not the number of vector elements, look through it. Be careful not to
12597 // look though conversions that change things like v4f32 to v2f64.
12598 if (V->getOpcode() == ISD::BITCAST) {
12599 SDValue ConvInput = V->getOperand(0);
12600 if (ConvInput.getValueType().isVector() &&
12601 ConvInput.getValueType().getVectorNumElements() == NumElts)
12602 V = ConvInput.getNode();
12605 if (V->getOpcode() == ISD::BUILD_VECTOR) {
12606 assert(V->getNumOperands() == NumElts &&
12607 "BUILD_VECTOR has wrong number of operands");
12609 bool AllSame = true;
12610 for (unsigned i = 0; i != NumElts; ++i) {
12611 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12612 Base = V->getOperand(i);
12616 // Splat of <u, u, u, u>, return <u, u, u, u>
12617 if (!Base.getNode())
12619 for (unsigned i = 0; i != NumElts; ++i) {
12620 if (V->getOperand(i) != Base) {
12625 // Splat of <x, x, x, x>, return <x, x, x, x>
12629 // Canonicalize any other splat as a build_vector.
12630 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12631 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12632 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12633 V->getValueType(0), Ops);
12635 // We may have jumped through bitcasts, so the type of the
12636 // BUILD_VECTOR may not match the type of the shuffle.
12637 if (V->getValueType(0) != VT)
12638 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12643 // There are various patterns used to build up a vector from smaller vectors,
12644 // subvectors, or elements. Scan chains of these and replace unused insertions
12645 // or components with undef.
12646 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12649 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12650 Level < AfterLegalizeVectorOps &&
12651 (N1.getOpcode() == ISD::UNDEF ||
12652 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12653 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12654 SDValue V = partitionShuffleOfConcats(N, DAG);
12660 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12661 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12662 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12663 SmallVector<SDValue, 8> Ops;
12664 for (int M : SVN->getMask()) {
12665 SDValue Op = DAG.getUNDEF(VT.getScalarType());
12667 int Idx = M % NumElts;
12668 SDValue &S = (M < (int)NumElts ? N0 : N1);
12669 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12670 Op = S.getOperand(Idx);
12671 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12673 Op = S.getOperand(0);
12675 // Operand can't be combined - bail out.
12681 if (Ops.size() == VT.getVectorNumElements()) {
12682 // BUILD_VECTOR requires all inputs to be of the same type, find the
12683 // maximum type and extend them all.
12684 EVT SVT = VT.getScalarType();
12685 if (SVT.isInteger())
12686 for (SDValue &Op : Ops)
12687 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12688 if (SVT != VT.getScalarType())
12689 for (SDValue &Op : Ops)
12690 Op = TLI.isZExtFree(Op.getValueType(), SVT)
12691 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12692 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12693 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12697 // If this shuffle only has a single input that is a bitcasted shuffle,
12698 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12699 // back to their original types.
12700 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12701 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12702 TLI.isTypeLegal(VT)) {
12704 // Peek through the bitcast only if there is one user.
12706 while (BC0.getOpcode() == ISD::BITCAST) {
12707 if (!BC0.hasOneUse())
12709 BC0 = BC0.getOperand(0);
12712 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12714 return SmallVector<int, 8>(Mask.begin(), Mask.end());
12716 SmallVector<int, 8> NewMask;
12718 for (int s = 0; s != Scale; ++s)
12719 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12723 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12724 EVT SVT = VT.getScalarType();
12725 EVT InnerVT = BC0->getValueType(0);
12726 EVT InnerSVT = InnerVT.getScalarType();
12728 // Determine which shuffle works with the smaller scalar type.
12729 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12730 EVT ScaleSVT = ScaleVT.getScalarType();
12732 if (TLI.isTypeLegal(ScaleVT) &&
12733 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12734 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12736 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12737 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12739 // Scale the shuffle masks to the smaller scalar type.
12740 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12741 SmallVector<int, 8> InnerMask =
12742 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12743 SmallVector<int, 8> OuterMask =
12744 ScaleShuffleMask(SVN->getMask(), OuterScale);
12746 // Merge the shuffle masks.
12747 SmallVector<int, 8> NewMask;
12748 for (int M : OuterMask)
12749 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12751 // Test for shuffle mask legality over both commutations.
12752 SDValue SV0 = BC0->getOperand(0);
12753 SDValue SV1 = BC0->getOperand(1);
12754 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12756 std::swap(SV0, SV1);
12757 ShuffleVectorSDNode::commuteMask(NewMask);
12758 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12762 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12763 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12764 return DAG.getNode(
12765 ISD::BITCAST, SDLoc(N), VT,
12766 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12772 // Canonicalize shuffles according to rules:
12773 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12774 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12775 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12776 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12777 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12778 TLI.isTypeLegal(VT)) {
12779 // The incoming shuffle must be of the same type as the result of the
12780 // current shuffle.
12781 assert(N1->getOperand(0).getValueType() == VT &&
12782 "Shuffle types don't match");
12784 SDValue SV0 = N1->getOperand(0);
12785 SDValue SV1 = N1->getOperand(1);
12786 bool HasSameOp0 = N0 == SV0;
12787 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12788 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12789 // Commute the operands of this shuffle so that next rule
12791 return DAG.getCommutedVectorShuffle(*SVN);
12794 // Try to fold according to rules:
12795 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12796 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12797 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12798 // Don't try to fold shuffles with illegal type.
12799 // Only fold if this shuffle is the only user of the other shuffle.
12800 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12801 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12802 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12804 // The incoming shuffle must be of the same type as the result of the
12805 // current shuffle.
12806 assert(OtherSV->getOperand(0).getValueType() == VT &&
12807 "Shuffle types don't match");
12810 SmallVector<int, 4> Mask;
12811 // Compute the combined shuffle mask for a shuffle with SV0 as the first
12812 // operand, and SV1 as the second operand.
12813 for (unsigned i = 0; i != NumElts; ++i) {
12814 int Idx = SVN->getMaskElt(i);
12816 // Propagate Undef.
12817 Mask.push_back(Idx);
12821 SDValue CurrentVec;
12822 if (Idx < (int)NumElts) {
12823 // This shuffle index refers to the inner shuffle N0. Lookup the inner
12824 // shuffle mask to identify which vector is actually referenced.
12825 Idx = OtherSV->getMaskElt(Idx);
12827 // Propagate Undef.
12828 Mask.push_back(Idx);
12832 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12833 : OtherSV->getOperand(1);
12835 // This shuffle index references an element within N1.
12839 // Simple case where 'CurrentVec' is UNDEF.
12840 if (CurrentVec.getOpcode() == ISD::UNDEF) {
12841 Mask.push_back(-1);
12845 // Canonicalize the shuffle index. We don't know yet if CurrentVec
12846 // will be the first or second operand of the combined shuffle.
12847 Idx = Idx % NumElts;
12848 if (!SV0.getNode() || SV0 == CurrentVec) {
12849 // Ok. CurrentVec is the left hand side.
12850 // Update the mask accordingly.
12852 Mask.push_back(Idx);
12856 // Bail out if we cannot convert the shuffle pair into a single shuffle.
12857 if (SV1.getNode() && SV1 != CurrentVec)
12860 // Ok. CurrentVec is the right hand side.
12861 // Update the mask accordingly.
12863 Mask.push_back(Idx + NumElts);
12866 // Check if all indices in Mask are Undef. In case, propagate Undef.
12867 bool isUndefMask = true;
12868 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12869 isUndefMask &= Mask[i] < 0;
12872 return DAG.getUNDEF(VT);
12874 if (!SV0.getNode())
12875 SV0 = DAG.getUNDEF(VT);
12876 if (!SV1.getNode())
12877 SV1 = DAG.getUNDEF(VT);
12879 // Avoid introducing shuffles with illegal mask.
12880 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12881 ShuffleVectorSDNode::commuteMask(Mask);
12883 if (!TLI.isShuffleMaskLegal(Mask, VT))
12886 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12887 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12888 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12889 std::swap(SV0, SV1);
12892 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12893 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12894 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12895 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12901 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12902 SDValue InVal = N->getOperand(0);
12903 EVT VT = N->getValueType(0);
12905 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12906 // with a VECTOR_SHUFFLE.
12907 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12908 SDValue InVec = InVal->getOperand(0);
12909 SDValue EltNo = InVal->getOperand(1);
12911 // FIXME: We could support implicit truncation if the shuffle can be
12912 // scaled to a smaller vector scalar type.
12913 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12914 if (C0 && VT == InVec.getValueType() &&
12915 VT.getScalarType() == InVal.getValueType()) {
12916 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12917 int Elt = C0->getZExtValue();
12920 if (TLI.isShuffleMaskLegal(NewMask, VT))
12921 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12929 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12930 SDValue N0 = N->getOperand(0);
12931 SDValue N2 = N->getOperand(2);
12933 // If the input vector is a concatenation, and the insert replaces
12934 // one of the halves, we can optimize into a single concat_vectors.
12935 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12936 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12937 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12938 EVT VT = N->getValueType(0);
12940 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12941 // (concat_vectors Z, Y)
12943 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12944 N->getOperand(1), N0.getOperand(1));
12946 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12947 // (concat_vectors X, Z)
12948 if (InsIdx == VT.getVectorNumElements()/2)
12949 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12950 N0.getOperand(0), N->getOperand(1));
12956 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12957 SDValue N0 = N->getOperand(0);
12959 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12960 if (N0->getOpcode() == ISD::FP16_TO_FP)
12961 return N0->getOperand(0);
12966 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12967 /// with the destination vector and a zero vector.
12968 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12969 /// vector_shuffle V, Zero, <0, 4, 2, 4>
12970 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12971 EVT VT = N->getValueType(0);
12972 SDValue LHS = N->getOperand(0);
12973 SDValue RHS = N->getOperand(1);
12976 // Make sure we're not running after operation legalization where it
12977 // may have custom lowered the vector shuffles.
12978 if (LegalOperations)
12981 if (N->getOpcode() != ISD::AND)
12984 if (RHS.getOpcode() == ISD::BITCAST)
12985 RHS = RHS.getOperand(0);
12987 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12988 SmallVector<int, 8> Indices;
12989 unsigned NumElts = RHS.getNumOperands();
12991 for (unsigned i = 0; i != NumElts; ++i) {
12992 SDValue Elt = RHS.getOperand(i);
12993 if (isAllOnesConstant(Elt))
12994 Indices.push_back(i);
12995 else if (isNullConstant(Elt))
12996 Indices.push_back(NumElts+i);
13001 // Let's see if the target supports this vector_shuffle.
13002 EVT RVT = RHS.getValueType();
13003 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
13006 // Return the new VECTOR_SHUFFLE node.
13007 EVT EltVT = RVT.getVectorElementType();
13008 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
13009 DAG.getConstant(0, dl, EltVT));
13010 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps);
13011 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
13012 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
13013 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
13019 /// Visit a binary vector operation, like ADD.
13020 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13021 assert(N->getValueType(0).isVector() &&
13022 "SimplifyVBinOp only works on vectors!");
13024 SDValue LHS = N->getOperand(0);
13025 SDValue RHS = N->getOperand(1);
13027 if (SDValue Shuffle = XformToShuffleWithZero(N))
13030 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
13032 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
13033 RHS.getOpcode() == ISD::BUILD_VECTOR) {
13034 // Check if both vectors are constants. If not bail out.
13035 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
13036 cast<BuildVectorSDNode>(RHS)->isConstant()))
13039 SmallVector<SDValue, 8> Ops;
13040 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
13041 SDValue LHSOp = LHS.getOperand(i);
13042 SDValue RHSOp = RHS.getOperand(i);
13044 // Can't fold divide by zero.
13045 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
13046 N->getOpcode() == ISD::FDIV) {
13047 if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP &&
13048 cast<ConstantFPSDNode>(RHSOp.getNode())->isZero()))
13052 EVT VT = LHSOp.getValueType();
13053 EVT RVT = RHSOp.getValueType();
13055 // Integer BUILD_VECTOR operands may have types larger than the element
13056 // size (e.g., when the element type is not legal). Prior to type
13057 // legalization, the types may not match between the two BUILD_VECTORS.
13058 // Truncate one of the operands to make them match.
13059 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
13060 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
13062 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
13066 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
13068 if (FoldOp.getOpcode() != ISD::UNDEF &&
13069 FoldOp.getOpcode() != ISD::Constant &&
13070 FoldOp.getOpcode() != ISD::ConstantFP)
13072 Ops.push_back(FoldOp);
13073 AddToWorklist(FoldOp.getNode());
13076 if (Ops.size() == LHS.getNumOperands())
13077 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
13080 // Type legalization might introduce new shuffles in the DAG.
13081 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13082 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
13083 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13084 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13085 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13086 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13087 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13088 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13090 if (SVN0->getMask().equals(SVN1->getMask())) {
13091 EVT VT = N->getValueType(0);
13092 SDValue UndefVector = LHS.getOperand(1);
13093 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13094 LHS.getOperand(0), RHS.getOperand(0));
13095 AddUsersToWorklist(N);
13096 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13097 &SVN0->getMask()[0]);
13104 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13105 SDValue N1, SDValue N2){
13106 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13108 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13109 cast<CondCodeSDNode>(N0.getOperand(2))->get());
13111 // If we got a simplified select_cc node back from SimplifySelectCC, then
13112 // break it down into a new SETCC node, and a new SELECT node, and then return
13113 // the SELECT node, since we were called with a SELECT node.
13114 if (SCC.getNode()) {
13115 // Check to see if we got a select_cc back (to turn into setcc/select).
13116 // Otherwise, just return whatever node we got back, like fabs.
13117 if (SCC.getOpcode() == ISD::SELECT_CC) {
13118 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13120 SCC.getOperand(0), SCC.getOperand(1),
13121 SCC.getOperand(4));
13122 AddToWorklist(SETCC.getNode());
13123 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13124 SCC.getOperand(2), SCC.getOperand(3));
13132 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13133 /// being selected between, see if we can simplify the select. Callers of this
13134 /// should assume that TheSelect is deleted if this returns true. As such, they
13135 /// should return the appropriate thing (e.g. the node) back to the top-level of
13136 /// the DAG combiner loop to avoid it being looked at.
13137 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13140 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13141 // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13142 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13143 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13144 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13145 SDValue Sqrt = RHS;
13148 const ConstantFPSDNode *NegZero = nullptr;
13150 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13151 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13152 CmpLHS = TheSelect->getOperand(0);
13153 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13155 // SELECT or VSELECT
13156 SDValue Cmp = TheSelect->getOperand(0);
13157 if (Cmp.getOpcode() == ISD::SETCC) {
13158 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13159 CmpLHS = Cmp.getOperand(0);
13160 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13163 if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13164 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13165 CC == ISD::SETULT || CC == ISD::SETLT)) {
13166 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13167 CombineTo(TheSelect, Sqrt);
13172 // Cannot simplify select with vector condition
13173 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13175 // If this is a select from two identical things, try to pull the operation
13176 // through the select.
13177 if (LHS.getOpcode() != RHS.getOpcode() ||
13178 !LHS.hasOneUse() || !RHS.hasOneUse())
13181 // If this is a load and the token chain is identical, replace the select
13182 // of two loads with a load through a select of the address to load from.
13183 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13184 // constants have been dropped into the constant pool.
13185 if (LHS.getOpcode() == ISD::LOAD) {
13186 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13187 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13189 // Token chains must be identical.
13190 if (LHS.getOperand(0) != RHS.getOperand(0) ||
13191 // Do not let this transformation reduce the number of volatile loads.
13192 LLD->isVolatile() || RLD->isVolatile() ||
13193 // FIXME: If either is a pre/post inc/dec load,
13194 // we'd need to split out the address adjustment.
13195 LLD->isIndexed() || RLD->isIndexed() ||
13196 // If this is an EXTLOAD, the VT's must match.
13197 LLD->getMemoryVT() != RLD->getMemoryVT() ||
13198 // If this is an EXTLOAD, the kind of extension must match.
13199 (LLD->getExtensionType() != RLD->getExtensionType() &&
13200 // The only exception is if one of the extensions is anyext.
13201 LLD->getExtensionType() != ISD::EXTLOAD &&
13202 RLD->getExtensionType() != ISD::EXTLOAD) ||
13203 // FIXME: this discards src value information. This is
13204 // over-conservative. It would be beneficial to be able to remember
13205 // both potential memory locations. Since we are discarding
13206 // src value info, don't do the transformation if the memory
13207 // locations are not in the default address space.
13208 LLD->getPointerInfo().getAddrSpace() != 0 ||
13209 RLD->getPointerInfo().getAddrSpace() != 0 ||
13210 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13211 LLD->getBasePtr().getValueType()))
13214 // Check that the select condition doesn't reach either load. If so,
13215 // folding this will induce a cycle into the DAG. If not, this is safe to
13216 // xform, so create a select of the addresses.
13218 if (TheSelect->getOpcode() == ISD::SELECT) {
13219 SDNode *CondNode = TheSelect->getOperand(0).getNode();
13220 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13221 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13223 // The loads must not depend on one another.
13224 if (LLD->isPredecessorOf(RLD) ||
13225 RLD->isPredecessorOf(LLD))
13227 Addr = DAG.getSelect(SDLoc(TheSelect),
13228 LLD->getBasePtr().getValueType(),
13229 TheSelect->getOperand(0), LLD->getBasePtr(),
13230 RLD->getBasePtr());
13231 } else { // Otherwise SELECT_CC
13232 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13233 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13235 if ((LLD->hasAnyUseOfValue(1) &&
13236 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13237 (RLD->hasAnyUseOfValue(1) &&
13238 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13241 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13242 LLD->getBasePtr().getValueType(),
13243 TheSelect->getOperand(0),
13244 TheSelect->getOperand(1),
13245 LLD->getBasePtr(), RLD->getBasePtr(),
13246 TheSelect->getOperand(4));
13250 // It is safe to replace the two loads if they have different alignments,
13251 // but the new load must be the minimum (most restrictive) alignment of the
13253 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13254 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13255 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13256 Load = DAG.getLoad(TheSelect->getValueType(0),
13258 // FIXME: Discards pointer and AA info.
13259 LLD->getChain(), Addr, MachinePointerInfo(),
13260 LLD->isVolatile(), LLD->isNonTemporal(),
13261 isInvariant, Alignment);
13263 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13264 RLD->getExtensionType() : LLD->getExtensionType(),
13266 TheSelect->getValueType(0),
13267 // FIXME: Discards pointer and AA info.
13268 LLD->getChain(), Addr, MachinePointerInfo(),
13269 LLD->getMemoryVT(), LLD->isVolatile(),
13270 LLD->isNonTemporal(), isInvariant, Alignment);
13273 // Users of the select now use the result of the load.
13274 CombineTo(TheSelect, Load);
13276 // Users of the old loads now use the new load's chain. We know the
13277 // old-load value is dead now.
13278 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13279 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13286 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13287 /// where 'cond' is the comparison specified by CC.
13288 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13289 SDValue N2, SDValue N3,
13290 ISD::CondCode CC, bool NotExtCompare) {
13291 // (x ? y : y) -> y.
13292 if (N2 == N3) return N2;
13294 EVT VT = N2.getValueType();
13295 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13296 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13298 // Determine if the condition we're dealing with is constant
13299 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13300 N0, N1, CC, DL, false);
13301 if (SCC.getNode()) AddToWorklist(SCC.getNode());
13303 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13304 // fold select_cc true, x, y -> x
13305 // fold select_cc false, x, y -> y
13306 return !SCCC->isNullValue() ? N2 : N3;
13309 // Check to see if we can simplify the select into an fabs node
13310 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13311 // Allow either -0.0 or 0.0
13312 if (CFP->isZero()) {
13313 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13314 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13315 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13316 N2 == N3.getOperand(0))
13317 return DAG.getNode(ISD::FABS, DL, VT, N0);
13319 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13320 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13321 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13322 N2.getOperand(0) == N3)
13323 return DAG.getNode(ISD::FABS, DL, VT, N3);
13327 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13328 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13329 // in it. This is a win when the constant is not otherwise available because
13330 // it replaces two constant pool loads with one. We only do this if the FP
13331 // type is known to be legal, because if it isn't, then we are before legalize
13332 // types an we want the other legalization to happen first (e.g. to avoid
13333 // messing with soft float) and if the ConstantFP is not legal, because if
13334 // it is legal, we may not need to store the FP constant in a constant pool.
13335 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13336 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13337 if (TLI.isTypeLegal(N2.getValueType()) &&
13338 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13339 TargetLowering::Legal &&
13340 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13341 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13342 // If both constants have multiple uses, then we won't need to do an
13343 // extra load, they are likely around in registers for other users.
13344 (TV->hasOneUse() || FV->hasOneUse())) {
13345 Constant *Elts[] = {
13346 const_cast<ConstantFP*>(FV->getConstantFPValue()),
13347 const_cast<ConstantFP*>(TV->getConstantFPValue())
13349 Type *FPTy = Elts[0]->getType();
13350 const DataLayout &TD = DAG.getDataLayout();
13352 // Create a ConstantArray of the two constants.
13353 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13355 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
13356 TD.getPrefTypeAlignment(FPTy));
13357 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13359 // Get the offsets to the 0 and 1 element of the array so that we can
13360 // select between them.
13361 SDValue Zero = DAG.getIntPtrConstant(0, DL);
13362 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13363 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13365 SDValue Cond = DAG.getSetCC(DL,
13366 getSetCCResultType(N0.getValueType()),
13368 AddToWorklist(Cond.getNode());
13369 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13371 AddToWorklist(CstOffset.getNode());
13372 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13374 AddToWorklist(CPIdx.getNode());
13375 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13376 MachinePointerInfo::getConstantPool(), false,
13377 false, false, Alignment);
13381 // Check to see if we can perform the "gzip trick", transforming
13382 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13383 if (isNullConstant(N3) && CC == ISD::SETLT &&
13384 (isNullConstant(N1) || // (a < 0) ? b : 0
13385 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0
13386 EVT XType = N0.getValueType();
13387 EVT AType = N2.getValueType();
13388 if (XType.bitsGE(AType)) {
13389 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13390 // single-bit constant.
13391 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13392 unsigned ShCtV = N2C->getAPIntValue().logBase2();
13393 ShCtV = XType.getSizeInBits() - ShCtV - 1;
13394 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13395 getShiftAmountTy(N0.getValueType()));
13396 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13398 AddToWorklist(Shift.getNode());
13400 if (XType.bitsGT(AType)) {
13401 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13402 AddToWorklist(Shift.getNode());
13405 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13408 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13410 DAG.getConstant(XType.getSizeInBits() - 1,
13412 getShiftAmountTy(N0.getValueType())));
13413 AddToWorklist(Shift.getNode());
13415 if (XType.bitsGT(AType)) {
13416 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13417 AddToWorklist(Shift.getNode());
13420 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13424 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13425 // where y is has a single bit set.
13426 // A plaintext description would be, we can turn the SELECT_CC into an AND
13427 // when the condition can be materialized as an all-ones register. Any
13428 // single bit-test can be materialized as an all-ones register with
13429 // shift-left and shift-right-arith.
13430 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13431 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13432 SDValue AndLHS = N0->getOperand(0);
13433 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13434 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13435 // Shift the tested bit over the sign bit.
13436 APInt AndMask = ConstAndRHS->getAPIntValue();
13438 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13439 getShiftAmountTy(AndLHS.getValueType()));
13440 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13442 // Now arithmetic right shift it all the way over, so the result is either
13443 // all-ones, or zero.
13445 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13446 getShiftAmountTy(Shl.getValueType()));
13447 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13449 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13453 // fold select C, 16, 0 -> shl C, 4
13454 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13455 TLI.getBooleanContents(N0.getValueType()) ==
13456 TargetLowering::ZeroOrOneBooleanContent) {
13458 // If the caller doesn't want us to simplify this into a zext of a compare,
13460 if (NotExtCompare && N2C->isOne())
13463 // Get a SetCC of the condition
13464 // NOTE: Don't create a SETCC if it's not legal on this target.
13465 if (!LegalOperations ||
13466 TLI.isOperationLegal(ISD::SETCC,
13467 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13469 // cast from setcc result type to select result type
13471 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13473 if (N2.getValueType().bitsLT(SCC.getValueType()))
13474 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13475 N2.getValueType());
13477 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13478 N2.getValueType(), SCC);
13480 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13481 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13482 N2.getValueType(), SCC);
13485 AddToWorklist(SCC.getNode());
13486 AddToWorklist(Temp.getNode());
13491 // shl setcc result by log2 n2c
13492 return DAG.getNode(
13493 ISD::SHL, DL, N2.getValueType(), Temp,
13494 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13495 getShiftAmountTy(Temp.getValueType())));
13499 // Check to see if this is the equivalent of setcc
13500 // FIXME: Turn all of these into setcc if setcc if setcc is legal
13501 // otherwise, go ahead with the folds.
13502 if (0 && isNullConstant(N3) && isOneConstant(N2)) {
13503 EVT XType = N0.getValueType();
13504 if (!LegalOperations ||
13505 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13506 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13507 if (Res.getValueType() != VT)
13508 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13512 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13513 if (isNullConstant(N1) && CC == ISD::SETEQ &&
13514 (!LegalOperations ||
13515 TLI.isOperationLegal(ISD::CTLZ, XType))) {
13516 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13517 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13518 DAG.getConstant(Log2_32(XType.getSizeInBits()),
13520 getShiftAmountTy(Ctlz.getValueType())));
13522 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13523 if (isNullConstant(N1) && CC == ISD::SETGT) {
13525 SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13526 XType, DAG.getConstant(0, DL, XType), N0);
13527 SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13528 return DAG.getNode(ISD::SRL, DL, XType,
13529 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13530 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13531 getShiftAmountTy(XType)));
13533 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13534 if (isAllOnesConstant(N1) && CC == ISD::SETGT) {
13536 SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13537 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13538 getShiftAmountTy(N0.getValueType())));
13539 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13544 // Check to see if this is an integer abs.
13545 // select_cc setg[te] X, 0, X, -X ->
13546 // select_cc setgt X, -1, X, -X ->
13547 // select_cc setl[te] X, 0, -X, X ->
13548 // select_cc setlt X, 1, -X, X ->
13549 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13551 ConstantSDNode *SubC = nullptr;
13552 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13553 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13554 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13555 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13556 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13557 (N1C->isOne() && CC == ISD::SETLT)) &&
13558 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13559 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13561 EVT XType = N0.getValueType();
13562 if (SubC && SubC->isNullValue() && XType.isInteger()) {
13564 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13566 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13567 getShiftAmountTy(N0.getValueType())));
13568 SDValue Add = DAG.getNode(ISD::ADD, DL,
13570 AddToWorklist(Shift.getNode());
13571 AddToWorklist(Add.getNode());
13572 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13579 /// This is a stub for TargetLowering::SimplifySetCC.
13580 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13581 SDValue N1, ISD::CondCode Cond,
13582 SDLoc DL, bool foldBooleans) {
13583 TargetLowering::DAGCombinerInfo
13584 DagCombineInfo(DAG, Level, false, this);
13585 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13588 /// Given an ISD::SDIV node expressing a divide by constant, return
13589 /// a DAG expression to select that will generate the same value by multiplying
13590 /// by a magic number.
13591 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13592 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13593 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13597 // Avoid division by zero.
13598 if (C->isNullValue())
13601 std::vector<SDNode*> Built;
13603 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13605 for (SDNode *N : Built)
13610 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13611 /// DAG expression that will generate the same value by right shifting.
13612 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13613 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13617 // Avoid division by zero.
13618 if (C->isNullValue())
13621 std::vector<SDNode *> Built;
13622 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13624 for (SDNode *N : Built)
13629 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13630 /// expression that will generate the same value by multiplying by a magic
13632 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13633 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13634 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13638 // Avoid division by zero.
13639 if (C->isNullValue())
13642 std::vector<SDNode*> Built;
13644 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13646 for (SDNode *N : Built)
13651 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13652 if (Level >= AfterLegalizeDAG)
13655 // Expose the DAG combiner to the target combiner implementations.
13656 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13658 unsigned Iterations = 0;
13659 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13661 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13662 // For the reciprocal, we need to find the zero of the function:
13663 // F(X) = A X - 1 [which has a zero at X = 1/A]
13665 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13666 // does not require additional intermediate precision]
13667 EVT VT = Op.getValueType();
13669 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13671 AddToWorklist(Est.getNode());
13673 // Newton iterations: Est = Est + Est (1 - Arg * Est)
13674 for (unsigned i = 0; i < Iterations; ++i) {
13675 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13676 AddToWorklist(NewEst.getNode());
13678 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13679 AddToWorklist(NewEst.getNode());
13681 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13682 AddToWorklist(NewEst.getNode());
13684 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13685 AddToWorklist(Est.getNode());
13694 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13695 /// For the reciprocal sqrt, we need to find the zero of the function:
13696 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13698 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13699 /// As a result, we precompute A/2 prior to the iteration loop.
13700 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13701 unsigned Iterations) {
13702 EVT VT = Arg.getValueType();
13704 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13706 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13707 // this entire sequence requires only one FP constant.
13708 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13709 AddToWorklist(HalfArg.getNode());
13711 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13712 AddToWorklist(HalfArg.getNode());
13714 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13715 for (unsigned i = 0; i < Iterations; ++i) {
13716 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13717 AddToWorklist(NewEst.getNode());
13719 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13720 AddToWorklist(NewEst.getNode());
13722 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13723 AddToWorklist(NewEst.getNode());
13725 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13726 AddToWorklist(Est.getNode());
13731 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13732 /// For the reciprocal sqrt, we need to find the zero of the function:
13733 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13735 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13736 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13737 unsigned Iterations) {
13738 EVT VT = Arg.getValueType();
13740 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13741 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13743 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13744 for (unsigned i = 0; i < Iterations; ++i) {
13745 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13746 AddToWorklist(HalfEst.getNode());
13748 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13749 AddToWorklist(Est.getNode());
13751 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13752 AddToWorklist(Est.getNode());
13754 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13755 AddToWorklist(Est.getNode());
13757 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13758 AddToWorklist(Est.getNode());
13763 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13764 if (Level >= AfterLegalizeDAG)
13767 // Expose the DAG combiner to the target combiner implementations.
13768 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13769 unsigned Iterations = 0;
13770 bool UseOneConstNR = false;
13771 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13772 AddToWorklist(Est.getNode());
13774 Est = UseOneConstNR ?
13775 BuildRsqrtNROneConst(Op, Est, Iterations) :
13776 BuildRsqrtNRTwoConst(Op, Est, Iterations);
13784 /// Return true if base is a frame index, which is known not to alias with
13785 /// anything but itself. Provides base object and offset as results.
13786 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13787 const GlobalValue *&GV, const void *&CV) {
13788 // Assume it is a primitive operation.
13789 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13791 // If it's an adding a simple constant then integrate the offset.
13792 if (Base.getOpcode() == ISD::ADD) {
13793 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13794 Base = Base.getOperand(0);
13795 Offset += C->getZExtValue();
13799 // Return the underlying GlobalValue, and update the Offset. Return false
13800 // for GlobalAddressSDNode since the same GlobalAddress may be represented
13801 // by multiple nodes with different offsets.
13802 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13803 GV = G->getGlobal();
13804 Offset += G->getOffset();
13808 // Return the underlying Constant value, and update the Offset. Return false
13809 // for ConstantSDNodes since the same constant pool entry may be represented
13810 // by multiple nodes with different offsets.
13811 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13812 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13813 : (const void *)C->getConstVal();
13814 Offset += C->getOffset();
13817 // If it's any of the following then it can't alias with anything but itself.
13818 return isa<FrameIndexSDNode>(Base);
13821 /// Return true if there is any possibility that the two addresses overlap.
13822 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13823 // If they are the same then they must be aliases.
13824 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13826 // If they are both volatile then they cannot be reordered.
13827 if (Op0->isVolatile() && Op1->isVolatile()) return true;
13829 // If one operation reads from invariant memory, and the other may store, they
13830 // cannot alias. These should really be checking the equivalent of mayWrite,
13831 // but it only matters for memory nodes other than load /store.
13832 if (Op0->isInvariant() && Op1->writeMem())
13835 if (Op1->isInvariant() && Op0->writeMem())
13838 // Gather base node and offset information.
13839 SDValue Base1, Base2;
13840 int64_t Offset1, Offset2;
13841 const GlobalValue *GV1, *GV2;
13842 const void *CV1, *CV2;
13843 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13844 Base1, Offset1, GV1, CV1);
13845 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13846 Base2, Offset2, GV2, CV2);
13848 // If they have a same base address then check to see if they overlap.
13849 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13850 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13851 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13853 // It is possible for different frame indices to alias each other, mostly
13854 // when tail call optimization reuses return address slots for arguments.
13855 // To catch this case, look up the actual index of frame indices to compute
13856 // the real alias relationship.
13857 if (isFrameIndex1 && isFrameIndex2) {
13858 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13859 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13860 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13861 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13862 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13865 // Otherwise, if we know what the bases are, and they aren't identical, then
13866 // we know they cannot alias.
13867 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13870 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13871 // compared to the size and offset of the access, we may be able to prove they
13872 // do not alias. This check is conservative for now to catch cases created by
13873 // splitting vector types.
13874 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13875 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13876 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13877 Op1->getMemoryVT().getSizeInBits() >> 3) &&
13878 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13879 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13880 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13882 // There is no overlap between these relatively aligned accesses of similar
13883 // size, return no alias.
13884 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13885 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13889 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13891 : DAG.getSubtarget().useAA();
13893 if (CombinerAAOnlyFunc.getNumOccurrences() &&
13894 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13898 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13899 // Use alias analysis information.
13900 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13901 Op1->getSrcValueOffset());
13902 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13903 Op0->getSrcValueOffset() - MinOffset;
13904 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13905 Op1->getSrcValueOffset() - MinOffset;
13906 AliasResult AAResult =
13907 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
13908 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13909 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
13910 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13911 if (AAResult == NoAlias)
13915 // Otherwise we have to assume they alias.
13919 /// Walk up chain skipping non-aliasing memory nodes,
13920 /// looking for aliasing nodes and adding them to the Aliases vector.
13921 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13922 SmallVectorImpl<SDValue> &Aliases) {
13923 SmallVector<SDValue, 8> Chains; // List of chains to visit.
13924 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
13926 // Get alias information for node.
13927 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13930 Chains.push_back(OriginalChain);
13931 unsigned Depth = 0;
13933 // Look at each chain and determine if it is an alias. If so, add it to the
13934 // aliases list. If not, then continue up the chain looking for the next
13936 while (!Chains.empty()) {
13937 SDValue Chain = Chains.pop_back_val();
13939 // For TokenFactor nodes, look at each operand and only continue up the
13940 // chain until we find two aliases. If we've seen two aliases, assume we'll
13941 // find more and revert to original chain since the xform is unlikely to be
13944 // FIXME: The depth check could be made to return the last non-aliasing
13945 // chain we found before we hit a tokenfactor rather than the original
13947 if (Depth > 6 || Aliases.size() == 2) {
13949 Aliases.push_back(OriginalChain);
13953 // Don't bother if we've been before.
13954 if (!Visited.insert(Chain.getNode()).second)
13957 switch (Chain.getOpcode()) {
13958 case ISD::EntryToken:
13959 // Entry token is ideal chain operand, but handled in FindBetterChain.
13964 // Get alias information for Chain.
13965 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13966 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13968 // If chain is alias then stop here.
13969 if (!(IsLoad && IsOpLoad) &&
13970 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13971 Aliases.push_back(Chain);
13973 // Look further up the chain.
13974 Chains.push_back(Chain.getOperand(0));
13980 case ISD::TokenFactor:
13981 // We have to check each of the operands of the token factor for "small"
13982 // token factors, so we queue them up. Adding the operands to the queue
13983 // (stack) in reverse order maintains the original order and increases the
13984 // likelihood that getNode will find a matching token factor (CSE.)
13985 if (Chain.getNumOperands() > 16) {
13986 Aliases.push_back(Chain);
13989 for (unsigned n = Chain.getNumOperands(); n;)
13990 Chains.push_back(Chain.getOperand(--n));
13995 // For all other instructions we will just have to take what we can get.
13996 Aliases.push_back(Chain);
14001 // We need to be careful here to also search for aliases through the
14002 // value operand of a store, etc. Consider the following situation:
14004 // L1 = load Token1, %52
14005 // S1 = store Token1, L1, %51
14006 // L2 = load Token1, %52+8
14007 // S2 = store Token1, L2, %51+8
14008 // Token2 = Token(S1, S2)
14009 // L3 = load Token2, %53
14010 // S3 = store Token2, L3, %52
14011 // L4 = load Token2, %53+8
14012 // S4 = store Token2, L4, %52+8
14013 // If we search for aliases of S3 (which loads address %52), and we look
14014 // only through the chain, then we'll miss the trivial dependence on L1
14015 // (which also loads from %52). We then might change all loads and
14016 // stores to use Token1 as their chain operand, which could result in
14017 // copying %53 into %52 before copying %52 into %51 (which should
14020 // The problem is, however, that searching for such data dependencies
14021 // can become expensive, and the cost is not directly related to the
14022 // chain depth. Instead, we'll rule out such configurations here by
14023 // insisting that we've visited all chain users (except for users
14024 // of the original chain, which is not necessary). When doing this,
14025 // we need to look through nodes we don't care about (otherwise, things
14026 // like register copies will interfere with trivial cases).
14028 SmallVector<const SDNode *, 16> Worklist;
14029 for (const SDNode *N : Visited)
14030 if (N != OriginalChain.getNode())
14031 Worklist.push_back(N);
14033 while (!Worklist.empty()) {
14034 const SDNode *M = Worklist.pop_back_val();
14036 // We have already visited M, and want to make sure we've visited any uses
14037 // of M that we care about. For uses that we've not visisted, and don't
14038 // care about, queue them to the worklist.
14040 for (SDNode::use_iterator UI = M->use_begin(),
14041 UIE = M->use_end(); UI != UIE; ++UI)
14042 if (UI.getUse().getValueType() == MVT::Other &&
14043 Visited.insert(*UI).second) {
14044 if (isa<MemSDNode>(*UI)) {
14045 // We've not visited this use, and we care about it (it could have an
14046 // ordering dependency with the original node).
14048 Aliases.push_back(OriginalChain);
14052 // We've not visited this use, but we don't care about it. Mark it as
14053 // visited and enqueue it to the worklist.
14054 Worklist.push_back(*UI);
14059 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14060 /// (aliasing node.)
14061 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14062 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
14064 // Accumulate all the aliases to this node.
14065 GatherAllAliases(N, OldChain, Aliases);
14067 // If no operands then chain to entry token.
14068 if (Aliases.size() == 0)
14069 return DAG.getEntryNode();
14071 // If a single operand then chain to it. We don't need to revisit it.
14072 if (Aliases.size() == 1)
14075 // Construct a custom tailored token factor.
14076 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14079 /// This is the entry point for the file.
14080 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14081 CodeGenOpt::Level OptLevel) {
14082 /// This is the main entry point to this class.
14083 DAGCombiner(*this, AA, OptLevel).Run(Level);