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 visitIMINMAX(SDNode *N);
249 SDValue visitAND(SDNode *N);
250 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
251 SDValue visitOR(SDNode *N);
252 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
253 SDValue visitXOR(SDNode *N);
254 SDValue SimplifyVBinOp(SDNode *N);
255 SDValue visitSHL(SDNode *N);
256 SDValue visitSRA(SDNode *N);
257 SDValue visitSRL(SDNode *N);
258 SDValue visitRotate(SDNode *N);
259 SDValue visitBSWAP(SDNode *N);
260 SDValue visitCTLZ(SDNode *N);
261 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
262 SDValue visitCTTZ(SDNode *N);
263 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
264 SDValue visitCTPOP(SDNode *N);
265 SDValue visitSELECT(SDNode *N);
266 SDValue visitVSELECT(SDNode *N);
267 SDValue visitSELECT_CC(SDNode *N);
268 SDValue visitSETCC(SDNode *N);
269 SDValue visitSIGN_EXTEND(SDNode *N);
270 SDValue visitZERO_EXTEND(SDNode *N);
271 SDValue visitANY_EXTEND(SDNode *N);
272 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
273 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
274 SDValue visitTRUNCATE(SDNode *N);
275 SDValue visitBITCAST(SDNode *N);
276 SDValue visitBUILD_PAIR(SDNode *N);
277 SDValue visitFADD(SDNode *N);
278 SDValue visitFSUB(SDNode *N);
279 SDValue visitFMUL(SDNode *N);
280 SDValue visitFMA(SDNode *N);
281 SDValue visitFDIV(SDNode *N);
282 SDValue visitFREM(SDNode *N);
283 SDValue visitFSQRT(SDNode *N);
284 SDValue visitFCOPYSIGN(SDNode *N);
285 SDValue visitSINT_TO_FP(SDNode *N);
286 SDValue visitUINT_TO_FP(SDNode *N);
287 SDValue visitFP_TO_SINT(SDNode *N);
288 SDValue visitFP_TO_UINT(SDNode *N);
289 SDValue visitFP_ROUND(SDNode *N);
290 SDValue visitFP_ROUND_INREG(SDNode *N);
291 SDValue visitFP_EXTEND(SDNode *N);
292 SDValue visitFNEG(SDNode *N);
293 SDValue visitFABS(SDNode *N);
294 SDValue visitFCEIL(SDNode *N);
295 SDValue visitFTRUNC(SDNode *N);
296 SDValue visitFFLOOR(SDNode *N);
297 SDValue visitFMINNUM(SDNode *N);
298 SDValue visitFMAXNUM(SDNode *N);
299 SDValue visitBRCOND(SDNode *N);
300 SDValue visitBR_CC(SDNode *N);
301 SDValue visitLOAD(SDNode *N);
302 SDValue visitSTORE(SDNode *N);
303 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
304 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
305 SDValue visitBUILD_VECTOR(SDNode *N);
306 SDValue visitCONCAT_VECTORS(SDNode *N);
307 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
308 SDValue visitVECTOR_SHUFFLE(SDNode *N);
309 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
310 SDValue visitINSERT_SUBVECTOR(SDNode *N);
311 SDValue visitMLOAD(SDNode *N);
312 SDValue visitMSTORE(SDNode *N);
313 SDValue visitMGATHER(SDNode *N);
314 SDValue visitMSCATTER(SDNode *N);
315 SDValue visitFP_TO_FP16(SDNode *N);
316 SDValue visitFP16_TO_FP(SDNode *N);
318 SDValue visitFADDForFMACombine(SDNode *N);
319 SDValue visitFSUBForFMACombine(SDNode *N);
321 SDValue XformToShuffleWithZero(SDNode *N);
322 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
324 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
326 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
327 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
328 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
329 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
330 SDValue N3, ISD::CondCode CC,
331 bool NotExtCompare = false);
332 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
333 SDLoc DL, bool foldBooleans = true);
335 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
337 bool isOneUseSetCC(SDValue N) const;
339 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
341 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
342 SDValue CombineExtLoad(SDNode *N);
343 SDValue combineRepeatedFPDivisors(SDNode *N);
344 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
345 SDValue BuildSDIV(SDNode *N);
346 SDValue BuildSDIVPow2(SDNode *N);
347 SDValue BuildUDIV(SDNode *N);
348 SDValue BuildReciprocalEstimate(SDValue Op);
349 SDValue BuildRsqrtEstimate(SDValue Op);
350 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
351 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
352 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
353 bool DemandHighBits = true);
354 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
355 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
356 SDValue InnerPos, SDValue InnerNeg,
357 unsigned PosOpcode, unsigned NegOpcode,
359 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
360 SDValue ReduceLoadWidth(SDNode *N);
361 SDValue ReduceLoadOpStoreWidth(SDNode *N);
362 SDValue TransformFPLoadStorePair(SDNode *N);
363 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
364 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
366 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
368 /// Walk up chain skipping non-aliasing memory nodes,
369 /// looking for aliasing nodes and adding them to the Aliases vector.
370 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
371 SmallVectorImpl<SDValue> &Aliases);
373 /// Return true if there is any possibility that the two addresses overlap.
374 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
376 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
377 /// chain (aliasing node.)
378 SDValue FindBetterChain(SDNode *N, SDValue Chain);
380 /// Holds a pointer to an LSBaseSDNode as well as information on where it
381 /// is located in a sequence of memory operations connected by a chain.
383 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
384 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
385 // Ptr to the mem node.
386 LSBaseSDNode *MemNode;
387 // Offset from the base ptr.
388 int64_t OffsetFromBase;
389 // What is the sequence number of this mem node.
390 // Lowest mem operand in the DAG starts at zero.
391 unsigned SequenceNum;
394 /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
395 /// constant build_vector of the stored constant values in Stores.
396 SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
398 ArrayRef<MemOpLink> Stores,
401 /// This is a helper function for MergeConsecutiveStores. When the source
402 /// elements of the consecutive stores are all constants or all extracted
403 /// vector elements, try to merge them into one larger store.
404 /// \return True if a merged store was created.
405 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
406 EVT MemVT, unsigned NumElem,
407 bool IsConstantSrc, bool UseVector);
409 /// This is a helper function for MergeConsecutiveStores.
410 /// Stores that may be merged are placed in StoreNodes.
411 /// Loads that may alias with those stores are placed in AliasLoadNodes.
412 void getStoreMergeAndAliasCandidates(
413 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
414 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
416 /// Merge consecutive store operations into a wide store.
417 /// This optimization uses wide integers or vectors when possible.
418 /// \return True if some memory operations were changed.
419 bool MergeConsecutiveStores(StoreSDNode *N);
421 /// \brief Try to transform a truncation where C is a constant:
422 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
424 /// \p N needs to be a truncation and its first operand an AND. Other
425 /// requirements are checked by the function (e.g. that trunc is
426 /// single-use) and if missed an empty SDValue is returned.
427 SDValue distributeTruncateThroughAnd(SDNode *N);
430 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
431 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
432 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
433 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
436 /// Runs the dag combiner on all nodes in the work list
437 void Run(CombineLevel AtLevel);
439 SelectionDAG &getDAG() const { return DAG; }
441 /// Returns a type large enough to hold any valid shift amount - before type
442 /// legalization these can be huge.
443 EVT getShiftAmountTy(EVT LHSTy) {
444 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
445 if (LHSTy.isVector())
447 auto &DL = DAG.getDataLayout();
448 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
449 : TLI.getPointerTy(DL);
452 /// This method returns true if we are running before type legalization or
453 /// if the specified VT is legal.
454 bool isTypeLegal(const EVT &VT) {
455 if (!LegalTypes) return true;
456 return TLI.isTypeLegal(VT);
459 /// Convenience wrapper around TargetLowering::getSetCCResultType
460 EVT getSetCCResultType(EVT VT) const {
461 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
468 /// This class is a DAGUpdateListener that removes any deleted
469 /// nodes from the worklist.
470 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
473 explicit WorklistRemover(DAGCombiner &dc)
474 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
476 void NodeDeleted(SDNode *N, SDNode *E) override {
477 DC.removeFromWorklist(N);
482 //===----------------------------------------------------------------------===//
483 // TargetLowering::DAGCombinerInfo implementation
484 //===----------------------------------------------------------------------===//
486 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
487 ((DAGCombiner*)DC)->AddToWorklist(N);
490 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
491 ((DAGCombiner*)DC)->removeFromWorklist(N);
494 SDValue TargetLowering::DAGCombinerInfo::
495 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
496 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
499 SDValue TargetLowering::DAGCombinerInfo::
500 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
501 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
505 SDValue TargetLowering::DAGCombinerInfo::
506 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
507 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
510 void TargetLowering::DAGCombinerInfo::
511 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
512 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
515 //===----------------------------------------------------------------------===//
517 //===----------------------------------------------------------------------===//
519 void DAGCombiner::deleteAndRecombine(SDNode *N) {
520 removeFromWorklist(N);
522 // If the operands of this node are only used by the node, they will now be
523 // dead. Make sure to re-visit them and recursively delete dead nodes.
524 for (const SDValue &Op : N->ops())
525 // For an operand generating multiple values, one of the values may
526 // become dead allowing further simplification (e.g. split index
527 // arithmetic from an indexed load).
528 if (Op->hasOneUse() || Op->getNumValues() > 1)
529 AddToWorklist(Op.getNode());
534 /// Return 1 if we can compute the negated form of the specified expression for
535 /// the same cost as the expression itself, or 2 if we can compute the negated
536 /// form more cheaply than the expression itself.
537 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
538 const TargetLowering &TLI,
539 const TargetOptions *Options,
540 unsigned Depth = 0) {
541 // fneg is removable even if it has multiple uses.
542 if (Op.getOpcode() == ISD::FNEG) return 2;
544 // Don't allow anything with multiple uses.
545 if (!Op.hasOneUse()) return 0;
547 // Don't recurse exponentially.
548 if (Depth > 6) return 0;
550 switch (Op.getOpcode()) {
551 default: return false;
552 case ISD::ConstantFP:
553 // Don't invert constant FP values after legalize. The negated constant
554 // isn't necessarily legal.
555 return LegalOperations ? 0 : 1;
557 // FIXME: determine better conditions for this xform.
558 if (!Options->UnsafeFPMath) return 0;
560 // After operation legalization, it might not be legal to create new FSUBs.
561 if (LegalOperations &&
562 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
565 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
566 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
569 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
570 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
573 // We can't turn -(A-B) into B-A when we honor signed zeros.
574 if (!Options->UnsafeFPMath) return 0;
576 // fold (fneg (fsub A, B)) -> (fsub B, A)
581 if (Options->HonorSignDependentRoundingFPMath()) return 0;
583 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
584 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
588 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
594 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
599 /// If isNegatibleForFree returns true, return the newly negated expression.
600 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
601 bool LegalOperations, unsigned Depth = 0) {
602 const TargetOptions &Options = DAG.getTarget().Options;
603 // fneg is removable even if it has multiple uses.
604 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
606 // Don't allow anything with multiple uses.
607 assert(Op.hasOneUse() && "Unknown reuse!");
609 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
610 switch (Op.getOpcode()) {
611 default: llvm_unreachable("Unknown code");
612 case ISD::ConstantFP: {
613 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
615 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
618 // FIXME: determine better conditions for this xform.
619 assert(Options.UnsafeFPMath);
621 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
622 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
623 DAG.getTargetLoweringInfo(), &Options, Depth+1))
624 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
625 GetNegatedExpression(Op.getOperand(0), DAG,
626 LegalOperations, Depth+1),
628 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
629 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
630 GetNegatedExpression(Op.getOperand(1), DAG,
631 LegalOperations, Depth+1),
634 // We can't turn -(A-B) into B-A when we honor signed zeros.
635 assert(Options.UnsafeFPMath);
637 // fold (fneg (fsub 0, B)) -> B
638 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
640 return Op.getOperand(1);
642 // fold (fneg (fsub A, B)) -> (fsub B, A)
643 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
644 Op.getOperand(1), Op.getOperand(0));
648 assert(!Options.HonorSignDependentRoundingFPMath());
650 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
651 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
652 DAG.getTargetLoweringInfo(), &Options, Depth+1))
653 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
654 GetNegatedExpression(Op.getOperand(0), DAG,
655 LegalOperations, Depth+1),
658 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
659 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
661 GetNegatedExpression(Op.getOperand(1), DAG,
662 LegalOperations, Depth+1));
666 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
667 GetNegatedExpression(Op.getOperand(0), DAG,
668 LegalOperations, Depth+1));
670 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
671 GetNegatedExpression(Op.getOperand(0), DAG,
672 LegalOperations, Depth+1),
677 // Return true if this node is a setcc, or is a select_cc
678 // that selects between the target values used for true and false, making it
679 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
680 // the appropriate nodes based on the type of node we are checking. This
681 // simplifies life a bit for the callers.
682 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
684 if (N.getOpcode() == ISD::SETCC) {
685 LHS = N.getOperand(0);
686 RHS = N.getOperand(1);
687 CC = N.getOperand(2);
691 if (N.getOpcode() != ISD::SELECT_CC ||
692 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
693 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
696 if (TLI.getBooleanContents(N.getValueType()) ==
697 TargetLowering::UndefinedBooleanContent)
700 LHS = N.getOperand(0);
701 RHS = N.getOperand(1);
702 CC = N.getOperand(4);
706 /// Return true if this is a SetCC-equivalent operation with only one use.
707 /// If this is true, it allows the users to invert the operation for free when
708 /// it is profitable to do so.
709 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
711 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
716 /// Returns true if N is a BUILD_VECTOR node whose
717 /// elements are all the same constant or undefined.
718 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
719 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
724 unsigned SplatBitSize;
726 EVT EltVT = N->getValueType(0).getVectorElementType();
727 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
729 EltVT.getSizeInBits() >= SplatBitSize);
732 // \brief Returns the SDNode if it is a constant integer BuildVector
733 // or constant integer.
734 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
735 if (isa<ConstantSDNode>(N))
737 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
742 // \brief Returns the SDNode if it is a constant float BuildVector
743 // or constant float.
744 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
745 if (isa<ConstantFPSDNode>(N))
747 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
752 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
754 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
755 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
758 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
759 BitVector UndefElements;
760 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
762 // BuildVectors can truncate their operands. Ignore that case here.
763 // FIXME: We blindly ignore splats which include undef which is overly
765 if (CN && UndefElements.none() &&
766 CN->getValueType(0) == N.getValueType().getScalarType())
773 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
775 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
776 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
779 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
780 BitVector UndefElements;
781 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
783 if (CN && UndefElements.none())
790 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
791 SDValue N0, SDValue N1) {
792 EVT VT = N0.getValueType();
793 if (N0.getOpcode() == Opc) {
794 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
795 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
796 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
797 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
798 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
801 if (N0.hasOneUse()) {
802 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
804 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
805 if (!OpNode.getNode())
807 AddToWorklist(OpNode.getNode());
808 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
813 if (N1.getOpcode() == Opc) {
814 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
815 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
816 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
817 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
818 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
821 if (N1.hasOneUse()) {
822 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
824 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
825 if (!OpNode.getNode())
827 AddToWorklist(OpNode.getNode());
828 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
836 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
838 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
840 DEBUG(dbgs() << "\nReplacing.1 ";
842 dbgs() << "\nWith: ";
843 To[0].getNode()->dump(&DAG);
844 dbgs() << " and " << NumTo-1 << " other values\n");
845 for (unsigned i = 0, e = NumTo; i != e; ++i)
846 assert((!To[i].getNode() ||
847 N->getValueType(i) == To[i].getValueType()) &&
848 "Cannot combine value to value of different type!");
850 WorklistRemover DeadNodes(*this);
851 DAG.ReplaceAllUsesWith(N, To);
853 // Push the new nodes and any users onto the worklist
854 for (unsigned i = 0, e = NumTo; i != e; ++i) {
855 if (To[i].getNode()) {
856 AddToWorklist(To[i].getNode());
857 AddUsersToWorklist(To[i].getNode());
862 // Finally, if the node is now dead, remove it from the graph. The node
863 // may not be dead if the replacement process recursively simplified to
864 // something else needing this node.
866 deleteAndRecombine(N);
867 return SDValue(N, 0);
871 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
872 // Replace all uses. If any nodes become isomorphic to other nodes and
873 // are deleted, make sure to remove them from our worklist.
874 WorklistRemover DeadNodes(*this);
875 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
877 // Push the new node and any (possibly new) users onto the worklist.
878 AddToWorklist(TLO.New.getNode());
879 AddUsersToWorklist(TLO.New.getNode());
881 // Finally, if the node is now dead, remove it from the graph. The node
882 // may not be dead if the replacement process recursively simplified to
883 // something else needing this node.
884 if (TLO.Old.getNode()->use_empty())
885 deleteAndRecombine(TLO.Old.getNode());
888 /// Check the specified integer node value to see if it can be simplified or if
889 /// things it uses can be simplified by bit propagation. If so, return true.
890 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
891 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
892 APInt KnownZero, KnownOne;
893 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
897 AddToWorklist(Op.getNode());
899 // Replace the old value with the new one.
901 DEBUG(dbgs() << "\nReplacing.2 ";
902 TLO.Old.getNode()->dump(&DAG);
903 dbgs() << "\nWith: ";
904 TLO.New.getNode()->dump(&DAG);
907 CommitTargetLoweringOpt(TLO);
911 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
913 EVT VT = Load->getValueType(0);
914 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
916 DEBUG(dbgs() << "\nReplacing.9 ";
918 dbgs() << "\nWith: ";
919 Trunc.getNode()->dump(&DAG);
921 WorklistRemover DeadNodes(*this);
922 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
923 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
924 deleteAndRecombine(Load);
925 AddToWorklist(Trunc.getNode());
928 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
931 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
932 EVT MemVT = LD->getMemoryVT();
933 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
934 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
936 : LD->getExtensionType();
938 return DAG.getExtLoad(ExtType, dl, PVT,
939 LD->getChain(), LD->getBasePtr(),
940 MemVT, LD->getMemOperand());
943 unsigned Opc = Op.getOpcode();
946 case ISD::AssertSext:
947 return DAG.getNode(ISD::AssertSext, dl, PVT,
948 SExtPromoteOperand(Op.getOperand(0), PVT),
950 case ISD::AssertZext:
951 return DAG.getNode(ISD::AssertZext, dl, PVT,
952 ZExtPromoteOperand(Op.getOperand(0), PVT),
954 case ISD::Constant: {
956 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
957 return DAG.getNode(ExtOpc, dl, PVT, Op);
961 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
963 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
966 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
967 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
969 EVT OldVT = Op.getValueType();
971 bool Replace = false;
972 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
973 if (!NewOp.getNode())
975 AddToWorklist(NewOp.getNode());
978 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
979 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
980 DAG.getValueType(OldVT));
983 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
984 EVT OldVT = Op.getValueType();
986 bool Replace = false;
987 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
988 if (!NewOp.getNode())
990 AddToWorklist(NewOp.getNode());
993 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
994 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
997 /// Promote the specified integer binary operation if the target indicates it is
998 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
999 /// i32 since i16 instructions are longer.
1000 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1001 if (!LegalOperations)
1004 EVT VT = Op.getValueType();
1005 if (VT.isVector() || !VT.isInteger())
1008 // If operation type is 'undesirable', e.g. i16 on x86, consider
1010 unsigned Opc = Op.getOpcode();
1011 if (TLI.isTypeDesirableForOp(Opc, VT))
1015 // Consult target whether it is a good idea to promote this operation and
1016 // what's the right type to promote it to.
1017 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1018 assert(PVT != VT && "Don't know what type to promote to!");
1020 bool Replace0 = false;
1021 SDValue N0 = Op.getOperand(0);
1022 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1026 bool Replace1 = false;
1027 SDValue N1 = Op.getOperand(1);
1032 NN1 = PromoteOperand(N1, PVT, Replace1);
1037 AddToWorklist(NN0.getNode());
1039 AddToWorklist(NN1.getNode());
1042 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1044 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1046 DEBUG(dbgs() << "\nPromoting ";
1047 Op.getNode()->dump(&DAG));
1049 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1050 DAG.getNode(Opc, dl, PVT, NN0, NN1));
1055 /// Promote the specified integer shift operation if the target indicates it is
1056 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1057 /// i32 since i16 instructions are longer.
1058 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1059 if (!LegalOperations)
1062 EVT VT = Op.getValueType();
1063 if (VT.isVector() || !VT.isInteger())
1066 // If operation type is 'undesirable', e.g. i16 on x86, consider
1068 unsigned Opc = Op.getOpcode();
1069 if (TLI.isTypeDesirableForOp(Opc, VT))
1073 // Consult target whether it is a good idea to promote this operation and
1074 // what's the right type to promote it to.
1075 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1076 assert(PVT != VT && "Don't know what type to promote to!");
1078 bool Replace = false;
1079 SDValue N0 = Op.getOperand(0);
1080 if (Opc == ISD::SRA)
1081 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1082 else if (Opc == ISD::SRL)
1083 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1085 N0 = PromoteOperand(N0, PVT, Replace);
1089 AddToWorklist(N0.getNode());
1091 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1093 DEBUG(dbgs() << "\nPromoting ";
1094 Op.getNode()->dump(&DAG));
1096 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1097 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1102 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1103 if (!LegalOperations)
1106 EVT VT = Op.getValueType();
1107 if (VT.isVector() || !VT.isInteger())
1110 // If operation type is 'undesirable', e.g. i16 on x86, consider
1112 unsigned Opc = Op.getOpcode();
1113 if (TLI.isTypeDesirableForOp(Opc, VT))
1117 // Consult target whether it is a good idea to promote this operation and
1118 // what's the right type to promote it to.
1119 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1120 assert(PVT != VT && "Don't know what type to promote to!");
1121 // fold (aext (aext x)) -> (aext x)
1122 // fold (aext (zext x)) -> (zext x)
1123 // fold (aext (sext x)) -> (sext x)
1124 DEBUG(dbgs() << "\nPromoting ";
1125 Op.getNode()->dump(&DAG));
1126 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1131 bool DAGCombiner::PromoteLoad(SDValue Op) {
1132 if (!LegalOperations)
1135 EVT VT = Op.getValueType();
1136 if (VT.isVector() || !VT.isInteger())
1139 // If operation type is 'undesirable', e.g. i16 on x86, consider
1141 unsigned Opc = Op.getOpcode();
1142 if (TLI.isTypeDesirableForOp(Opc, VT))
1146 // Consult target whether it is a good idea to promote this operation and
1147 // what's the right type to promote it to.
1148 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1149 assert(PVT != VT && "Don't know what type to promote to!");
1152 SDNode *N = Op.getNode();
1153 LoadSDNode *LD = cast<LoadSDNode>(N);
1154 EVT MemVT = LD->getMemoryVT();
1155 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1156 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1158 : LD->getExtensionType();
1159 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1160 LD->getChain(), LD->getBasePtr(),
1161 MemVT, LD->getMemOperand());
1162 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1164 DEBUG(dbgs() << "\nPromoting ";
1167 Result.getNode()->dump(&DAG);
1169 WorklistRemover DeadNodes(*this);
1170 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1171 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1172 deleteAndRecombine(N);
1173 AddToWorklist(Result.getNode());
1179 /// \brief Recursively delete a node which has no uses and any operands for
1180 /// which it is the only use.
1182 /// Note that this both deletes the nodes and removes them from the worklist.
1183 /// It also adds any nodes who have had a user deleted to the worklist as they
1184 /// may now have only one use and subject to other combines.
1185 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1186 if (!N->use_empty())
1189 SmallSetVector<SDNode *, 16> Nodes;
1192 N = Nodes.pop_back_val();
1196 if (N->use_empty()) {
1197 for (const SDValue &ChildN : N->op_values())
1198 Nodes.insert(ChildN.getNode());
1200 removeFromWorklist(N);
1205 } while (!Nodes.empty());
1209 //===----------------------------------------------------------------------===//
1210 // Main DAG Combiner implementation
1211 //===----------------------------------------------------------------------===//
1213 void DAGCombiner::Run(CombineLevel AtLevel) {
1214 // set the instance variables, so that the various visit routines may use it.
1216 LegalOperations = Level >= AfterLegalizeVectorOps;
1217 LegalTypes = Level >= AfterLegalizeTypes;
1219 // Add all the dag nodes to the worklist.
1220 for (SDNode &Node : DAG.allnodes())
1221 AddToWorklist(&Node);
1223 // Create a dummy node (which is not added to allnodes), that adds a reference
1224 // to the root node, preventing it from being deleted, and tracking any
1225 // changes of the root.
1226 HandleSDNode Dummy(DAG.getRoot());
1228 // while the worklist isn't empty, find a node and
1229 // try and combine it.
1230 while (!WorklistMap.empty()) {
1232 // The Worklist holds the SDNodes in order, but it may contain null entries.
1234 N = Worklist.pop_back_val();
1237 bool GoodWorklistEntry = WorklistMap.erase(N);
1238 (void)GoodWorklistEntry;
1239 assert(GoodWorklistEntry &&
1240 "Found a worklist entry without a corresponding map entry!");
1242 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1243 // N is deleted from the DAG, since they too may now be dead or may have a
1244 // reduced number of uses, allowing other xforms.
1245 if (recursivelyDeleteUnusedNodes(N))
1248 WorklistRemover DeadNodes(*this);
1250 // If this combine is running after legalizing the DAG, re-legalize any
1251 // nodes pulled off the worklist.
1252 if (Level == AfterLegalizeDAG) {
1253 SmallSetVector<SDNode *, 16> UpdatedNodes;
1254 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1256 for (SDNode *LN : UpdatedNodes) {
1258 AddUsersToWorklist(LN);
1264 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1266 // Add any operands of the new node which have not yet been combined to the
1267 // worklist as well. Because the worklist uniques things already, this
1268 // won't repeatedly process the same operand.
1269 CombinedNodes.insert(N);
1270 for (const SDValue &ChildN : N->op_values())
1271 if (!CombinedNodes.count(ChildN.getNode()))
1272 AddToWorklist(ChildN.getNode());
1274 SDValue RV = combine(N);
1281 // If we get back the same node we passed in, rather than a new node or
1282 // zero, we know that the node must have defined multiple values and
1283 // CombineTo was used. Since CombineTo takes care of the worklist
1284 // mechanics for us, we have no work to do in this case.
1285 if (RV.getNode() == N)
1288 assert(N->getOpcode() != ISD::DELETED_NODE &&
1289 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1290 "Node was deleted but visit returned new node!");
1292 DEBUG(dbgs() << " ... into: ";
1293 RV.getNode()->dump(&DAG));
1295 // Transfer debug value.
1296 DAG.TransferDbgValues(SDValue(N, 0), RV);
1297 if (N->getNumValues() == RV.getNode()->getNumValues())
1298 DAG.ReplaceAllUsesWith(N, RV.getNode());
1300 assert(N->getValueType(0) == RV.getValueType() &&
1301 N->getNumValues() == 1 && "Type mismatch");
1303 DAG.ReplaceAllUsesWith(N, &OpV);
1306 // Push the new node and any users onto the worklist
1307 AddToWorklist(RV.getNode());
1308 AddUsersToWorklist(RV.getNode());
1310 // Finally, if the node is now dead, remove it from the graph. The node
1311 // may not be dead if the replacement process recursively simplified to
1312 // something else needing this node. This will also take care of adding any
1313 // operands which have lost a user to the worklist.
1314 recursivelyDeleteUnusedNodes(N);
1317 // If the root changed (e.g. it was a dead load, update the root).
1318 DAG.setRoot(Dummy.getValue());
1319 DAG.RemoveDeadNodes();
1322 SDValue DAGCombiner::visit(SDNode *N) {
1323 switch (N->getOpcode()) {
1325 case ISD::TokenFactor: return visitTokenFactor(N);
1326 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1327 case ISD::ADD: return visitADD(N);
1328 case ISD::SUB: return visitSUB(N);
1329 case ISD::ADDC: return visitADDC(N);
1330 case ISD::SUBC: return visitSUBC(N);
1331 case ISD::ADDE: return visitADDE(N);
1332 case ISD::SUBE: return visitSUBE(N);
1333 case ISD::MUL: return visitMUL(N);
1334 case ISD::SDIV: return visitSDIV(N);
1335 case ISD::UDIV: return visitUDIV(N);
1336 case ISD::SREM: return visitSREM(N);
1337 case ISD::UREM: return visitUREM(N);
1338 case ISD::MULHU: return visitMULHU(N);
1339 case ISD::MULHS: return visitMULHS(N);
1340 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1341 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1342 case ISD::SMULO: return visitSMULO(N);
1343 case ISD::UMULO: return visitUMULO(N);
1344 case ISD::SDIVREM: return visitSDIVREM(N);
1345 case ISD::UDIVREM: return visitUDIVREM(N);
1349 case ISD::UMAX: return visitIMINMAX(N);
1350 case ISD::AND: return visitAND(N);
1351 case ISD::OR: return visitOR(N);
1352 case ISD::XOR: return visitXOR(N);
1353 case ISD::SHL: return visitSHL(N);
1354 case ISD::SRA: return visitSRA(N);
1355 case ISD::SRL: return visitSRL(N);
1357 case ISD::ROTL: return visitRotate(N);
1358 case ISD::BSWAP: return visitBSWAP(N);
1359 case ISD::CTLZ: return visitCTLZ(N);
1360 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1361 case ISD::CTTZ: return visitCTTZ(N);
1362 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1363 case ISD::CTPOP: return visitCTPOP(N);
1364 case ISD::SELECT: return visitSELECT(N);
1365 case ISD::VSELECT: return visitVSELECT(N);
1366 case ISD::SELECT_CC: return visitSELECT_CC(N);
1367 case ISD::SETCC: return visitSETCC(N);
1368 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1369 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1370 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1371 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1372 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1373 case ISD::TRUNCATE: return visitTRUNCATE(N);
1374 case ISD::BITCAST: return visitBITCAST(N);
1375 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1376 case ISD::FADD: return visitFADD(N);
1377 case ISD::FSUB: return visitFSUB(N);
1378 case ISD::FMUL: return visitFMUL(N);
1379 case ISD::FMA: return visitFMA(N);
1380 case ISD::FDIV: return visitFDIV(N);
1381 case ISD::FREM: return visitFREM(N);
1382 case ISD::FSQRT: return visitFSQRT(N);
1383 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1384 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1385 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1386 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1387 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1388 case ISD::FP_ROUND: return visitFP_ROUND(N);
1389 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1390 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1391 case ISD::FNEG: return visitFNEG(N);
1392 case ISD::FABS: return visitFABS(N);
1393 case ISD::FFLOOR: return visitFFLOOR(N);
1394 case ISD::FMINNUM: return visitFMINNUM(N);
1395 case ISD::FMAXNUM: return visitFMAXNUM(N);
1396 case ISD::FCEIL: return visitFCEIL(N);
1397 case ISD::FTRUNC: return visitFTRUNC(N);
1398 case ISD::BRCOND: return visitBRCOND(N);
1399 case ISD::BR_CC: return visitBR_CC(N);
1400 case ISD::LOAD: return visitLOAD(N);
1401 case ISD::STORE: return visitSTORE(N);
1402 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1403 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1404 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1405 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1406 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1407 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1408 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1409 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1410 case ISD::MGATHER: return visitMGATHER(N);
1411 case ISD::MLOAD: return visitMLOAD(N);
1412 case ISD::MSCATTER: return visitMSCATTER(N);
1413 case ISD::MSTORE: return visitMSTORE(N);
1414 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
1415 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N);
1420 SDValue DAGCombiner::combine(SDNode *N) {
1421 SDValue RV = visit(N);
1423 // If nothing happened, try a target-specific DAG combine.
1424 if (!RV.getNode()) {
1425 assert(N->getOpcode() != ISD::DELETED_NODE &&
1426 "Node was deleted but visit returned NULL!");
1428 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1429 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1431 // Expose the DAG combiner to the target combiner impls.
1432 TargetLowering::DAGCombinerInfo
1433 DagCombineInfo(DAG, Level, false, this);
1435 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1439 // If nothing happened still, try promoting the operation.
1440 if (!RV.getNode()) {
1441 switch (N->getOpcode()) {
1449 RV = PromoteIntBinOp(SDValue(N, 0));
1454 RV = PromoteIntShiftOp(SDValue(N, 0));
1456 case ISD::SIGN_EXTEND:
1457 case ISD::ZERO_EXTEND:
1458 case ISD::ANY_EXTEND:
1459 RV = PromoteExtend(SDValue(N, 0));
1462 if (PromoteLoad(SDValue(N, 0)))
1468 // If N is a commutative binary node, try commuting it to enable more
1470 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1471 N->getNumValues() == 1) {
1472 SDValue N0 = N->getOperand(0);
1473 SDValue N1 = N->getOperand(1);
1475 // Constant operands are canonicalized to RHS.
1476 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1477 SDValue Ops[] = {N1, N0};
1479 if (const auto *BinNode = dyn_cast<BinaryWithFlagsSDNode>(N)) {
1480 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1483 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1486 return SDValue(CSENode, 0);
1493 /// Given a node, return its input chain if it has one, otherwise return a null
1495 static SDValue getInputChainForNode(SDNode *N) {
1496 if (unsigned NumOps = N->getNumOperands()) {
1497 if (N->getOperand(0).getValueType() == MVT::Other)
1498 return N->getOperand(0);
1499 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1500 return N->getOperand(NumOps-1);
1501 for (unsigned i = 1; i < NumOps-1; ++i)
1502 if (N->getOperand(i).getValueType() == MVT::Other)
1503 return N->getOperand(i);
1508 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1509 // If N has two operands, where one has an input chain equal to the other,
1510 // the 'other' chain is redundant.
1511 if (N->getNumOperands() == 2) {
1512 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1513 return N->getOperand(0);
1514 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1515 return N->getOperand(1);
1518 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1519 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1520 SmallPtrSet<SDNode*, 16> SeenOps;
1521 bool Changed = false; // If we should replace this token factor.
1523 // Start out with this token factor.
1526 // Iterate through token factors. The TFs grows when new token factors are
1528 for (unsigned i = 0; i < TFs.size(); ++i) {
1529 SDNode *TF = TFs[i];
1531 // Check each of the operands.
1532 for (const SDValue &Op : TF->op_values()) {
1534 switch (Op.getOpcode()) {
1535 case ISD::EntryToken:
1536 // Entry tokens don't need to be added to the list. They are
1541 case ISD::TokenFactor:
1542 if (Op.hasOneUse() &&
1543 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1544 // Queue up for processing.
1545 TFs.push_back(Op.getNode());
1546 // Clean up in case the token factor is removed.
1547 AddToWorklist(Op.getNode());
1554 // Only add if it isn't already in the list.
1555 if (SeenOps.insert(Op.getNode()).second)
1566 // If we've changed things around then replace token factor.
1569 // The entry token is the only possible outcome.
1570 Result = DAG.getEntryNode();
1572 // New and improved token factor.
1573 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1576 // Add users to worklist if AA is enabled, since it may introduce
1577 // a lot of new chained token factors while removing memory deps.
1578 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1579 : DAG.getSubtarget().useAA();
1580 return CombineTo(N, Result, UseAA /*add to worklist*/);
1586 /// MERGE_VALUES can always be eliminated.
1587 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1588 WorklistRemover DeadNodes(*this);
1589 // Replacing results may cause a different MERGE_VALUES to suddenly
1590 // be CSE'd with N, and carry its uses with it. Iterate until no
1591 // uses remain, to ensure that the node can be safely deleted.
1592 // First add the users of this node to the work list so that they
1593 // can be tried again once they have new operands.
1594 AddUsersToWorklist(N);
1596 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1597 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1598 } while (!N->use_empty());
1599 deleteAndRecombine(N);
1600 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1603 static bool isNullConstant(SDValue V) {
1604 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1605 return Const != nullptr && Const->isNullValue();
1608 static bool isNullFPConstant(SDValue V) {
1609 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1610 return Const != nullptr && Const->isZero() && !Const->isNegative();
1613 static bool isAllOnesConstant(SDValue V) {
1614 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1615 return Const != nullptr && Const->isAllOnesValue();
1618 static bool isOneConstant(SDValue V) {
1619 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1620 return Const != nullptr && Const->isOne();
1623 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1624 /// ContantSDNode pointer else nullptr.
1625 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1626 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1627 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1630 SDValue DAGCombiner::visitADD(SDNode *N) {
1631 SDValue N0 = N->getOperand(0);
1632 SDValue N1 = N->getOperand(1);
1633 EVT VT = N0.getValueType();
1636 if (VT.isVector()) {
1637 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1640 // fold (add x, 0) -> x, vector edition
1641 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1643 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1647 // fold (add x, undef) -> undef
1648 if (N0.getOpcode() == ISD::UNDEF)
1650 if (N1.getOpcode() == ISD::UNDEF)
1652 // fold (add c1, c2) -> c1+c2
1653 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1654 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1656 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1657 // canonicalize constant to RHS
1658 if (isConstantIntBuildVectorOrConstantInt(N0) &&
1659 !isConstantIntBuildVectorOrConstantInt(N1))
1660 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1661 // fold (add x, 0) -> x
1662 if (isNullConstant(N1))
1664 // fold (add Sym, c) -> Sym+c
1665 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1666 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1667 GA->getOpcode() == ISD::GlobalAddress)
1668 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1670 (uint64_t)N1C->getSExtValue());
1671 // fold ((c1-A)+c2) -> (c1+c2)-A
1672 if (N1C && N0.getOpcode() == ISD::SUB)
1673 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1675 return DAG.getNode(ISD::SUB, DL, VT,
1676 DAG.getConstant(N1C->getAPIntValue()+
1677 N0C->getAPIntValue(), DL, VT),
1681 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1683 // fold ((0-A) + B) -> B-A
1684 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1685 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1686 // fold (A + (0-B)) -> A-B
1687 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1688 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1689 // fold (A+(B-A)) -> B
1690 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1691 return N1.getOperand(0);
1692 // fold ((B-A)+A) -> B
1693 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1694 return N0.getOperand(0);
1695 // fold (A+(B-(A+C))) to (B-C)
1696 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1697 N0 == N1.getOperand(1).getOperand(0))
1698 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1699 N1.getOperand(1).getOperand(1));
1700 // fold (A+(B-(C+A))) to (B-C)
1701 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1702 N0 == N1.getOperand(1).getOperand(1))
1703 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1704 N1.getOperand(1).getOperand(0));
1705 // fold (A+((B-A)+or-C)) to (B+or-C)
1706 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1707 N1.getOperand(0).getOpcode() == ISD::SUB &&
1708 N0 == N1.getOperand(0).getOperand(1))
1709 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1710 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1712 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1713 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1714 SDValue N00 = N0.getOperand(0);
1715 SDValue N01 = N0.getOperand(1);
1716 SDValue N10 = N1.getOperand(0);
1717 SDValue N11 = N1.getOperand(1);
1719 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1720 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1721 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1722 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1725 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1726 return SDValue(N, 0);
1728 // fold (a+b) -> (a|b) iff a and b share no bits.
1729 if (VT.isInteger() && !VT.isVector()) {
1730 APInt LHSZero, LHSOne;
1731 APInt RHSZero, RHSOne;
1732 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1734 if (LHSZero.getBoolValue()) {
1735 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1737 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1738 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1739 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1740 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1741 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1746 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1747 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1748 isNullConstant(N1.getOperand(0).getOperand(0)))
1749 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1750 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1751 N1.getOperand(0).getOperand(1),
1753 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1754 isNullConstant(N0.getOperand(0).getOperand(0)))
1755 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1756 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1757 N0.getOperand(0).getOperand(1),
1760 if (N1.getOpcode() == ISD::AND) {
1761 SDValue AndOp0 = N1.getOperand(0);
1762 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1763 unsigned DestBits = VT.getScalarType().getSizeInBits();
1765 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1766 // and similar xforms where the inner op is either ~0 or 0.
1767 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1769 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1773 // add (sext i1), X -> sub X, (zext i1)
1774 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1775 N0.getOperand(0).getValueType() == MVT::i1 &&
1776 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1778 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1779 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1782 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1783 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1784 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1785 if (TN->getVT() == MVT::i1) {
1787 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1788 DAG.getConstant(1, DL, VT));
1789 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1796 SDValue DAGCombiner::visitADDC(SDNode *N) {
1797 SDValue N0 = N->getOperand(0);
1798 SDValue N1 = N->getOperand(1);
1799 EVT VT = N0.getValueType();
1801 // If the flag result is dead, turn this into an ADD.
1802 if (!N->hasAnyUseOfValue(1))
1803 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1804 DAG.getNode(ISD::CARRY_FALSE,
1805 SDLoc(N), MVT::Glue));
1807 // canonicalize constant to RHS.
1808 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1809 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1811 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1813 // fold (addc x, 0) -> x + no carry out
1814 if (isNullConstant(N1))
1815 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1816 SDLoc(N), MVT::Glue));
1818 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1819 APInt LHSZero, LHSOne;
1820 APInt RHSZero, RHSOne;
1821 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1823 if (LHSZero.getBoolValue()) {
1824 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1826 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1827 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1828 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1829 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1830 DAG.getNode(ISD::CARRY_FALSE,
1831 SDLoc(N), MVT::Glue));
1837 SDValue DAGCombiner::visitADDE(SDNode *N) {
1838 SDValue N0 = N->getOperand(0);
1839 SDValue N1 = N->getOperand(1);
1840 SDValue CarryIn = N->getOperand(2);
1842 // canonicalize constant to RHS
1843 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1844 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1846 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1849 // fold (adde x, y, false) -> (addc x, y)
1850 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1851 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1856 // Since it may not be valid to emit a fold to zero for vector initializers
1857 // check if we can before folding.
1858 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1860 bool LegalOperations, bool LegalTypes) {
1862 return DAG.getConstant(0, DL, VT);
1863 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1864 return DAG.getConstant(0, DL, VT);
1868 SDValue DAGCombiner::visitSUB(SDNode *N) {
1869 SDValue N0 = N->getOperand(0);
1870 SDValue N1 = N->getOperand(1);
1871 EVT VT = N0.getValueType();
1874 if (VT.isVector()) {
1875 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1878 // fold (sub x, 0) -> x, vector edition
1879 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1883 // fold (sub x, x) -> 0
1884 // FIXME: Refactor this and xor and other similar operations together.
1886 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1887 // fold (sub c1, c2) -> c1-c2
1888 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1889 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1891 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1892 // fold (sub x, c) -> (add x, -c)
1895 return DAG.getNode(ISD::ADD, DL, VT, N0,
1896 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1898 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1899 if (isAllOnesConstant(N0))
1900 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1901 // fold A-(A-B) -> B
1902 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1903 return N1.getOperand(1);
1904 // fold (A+B)-A -> B
1905 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1906 return N0.getOperand(1);
1907 // fold (A+B)-B -> A
1908 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1909 return N0.getOperand(0);
1910 // fold C2-(A+C1) -> (C2-C1)-A
1911 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1912 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1913 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1915 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1917 return DAG.getNode(ISD::SUB, DL, VT, NewC,
1920 // fold ((A+(B+or-C))-B) -> A+or-C
1921 if (N0.getOpcode() == ISD::ADD &&
1922 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1923 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1924 N0.getOperand(1).getOperand(0) == N1)
1925 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1926 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1927 // fold ((A+(C+B))-B) -> A+C
1928 if (N0.getOpcode() == ISD::ADD &&
1929 N0.getOperand(1).getOpcode() == ISD::ADD &&
1930 N0.getOperand(1).getOperand(1) == N1)
1931 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1932 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1933 // fold ((A-(B-C))-C) -> A-B
1934 if (N0.getOpcode() == ISD::SUB &&
1935 N0.getOperand(1).getOpcode() == ISD::SUB &&
1936 N0.getOperand(1).getOperand(1) == N1)
1937 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1938 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1940 // If either operand of a sub is undef, the result is undef
1941 if (N0.getOpcode() == ISD::UNDEF)
1943 if (N1.getOpcode() == ISD::UNDEF)
1946 // If the relocation model supports it, consider symbol offsets.
1947 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1948 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1949 // fold (sub Sym, c) -> Sym-c
1950 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1951 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1953 (uint64_t)N1C->getSExtValue());
1954 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1955 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1956 if (GA->getGlobal() == GB->getGlobal())
1957 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1961 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1962 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1963 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1964 if (TN->getVT() == MVT::i1) {
1966 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1967 DAG.getConstant(1, DL, VT));
1968 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1975 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1976 SDValue N0 = N->getOperand(0);
1977 SDValue N1 = N->getOperand(1);
1978 EVT VT = N0.getValueType();
1980 // If the flag result is dead, turn this into an SUB.
1981 if (!N->hasAnyUseOfValue(1))
1982 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1983 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1986 // fold (subc x, x) -> 0 + no borrow
1989 return CombineTo(N, DAG.getConstant(0, DL, VT),
1990 DAG.getNode(ISD::CARRY_FALSE, DL,
1994 // fold (subc x, 0) -> x + no borrow
1995 if (isNullConstant(N1))
1996 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1999 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2000 if (isAllOnesConstant(N0))
2001 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
2002 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
2008 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2009 SDValue N0 = N->getOperand(0);
2010 SDValue N1 = N->getOperand(1);
2011 SDValue CarryIn = N->getOperand(2);
2013 // fold (sube x, y, false) -> (subc x, y)
2014 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2015 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2020 SDValue DAGCombiner::visitMUL(SDNode *N) {
2021 SDValue N0 = N->getOperand(0);
2022 SDValue N1 = N->getOperand(1);
2023 EVT VT = N0.getValueType();
2025 // fold (mul x, undef) -> 0
2026 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2027 return DAG.getConstant(0, SDLoc(N), VT);
2029 bool N0IsConst = false;
2030 bool N1IsConst = false;
2031 bool N1IsOpaqueConst = false;
2032 bool N0IsOpaqueConst = false;
2033 APInt ConstValue0, ConstValue1;
2035 if (VT.isVector()) {
2036 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2039 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2040 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2042 N0IsConst = isa<ConstantSDNode>(N0);
2044 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2045 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2047 N1IsConst = isa<ConstantSDNode>(N1);
2049 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2050 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2054 // fold (mul c1, c2) -> c1*c2
2055 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2056 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2057 N0.getNode(), N1.getNode());
2059 // canonicalize constant to RHS (vector doesn't have to splat)
2060 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2061 !isConstantIntBuildVectorOrConstantInt(N1))
2062 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2063 // fold (mul x, 0) -> 0
2064 if (N1IsConst && ConstValue1 == 0)
2066 // We require a splat of the entire scalar bit width for non-contiguous
2069 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2070 // fold (mul x, 1) -> x
2071 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2073 // fold (mul x, -1) -> 0-x
2074 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2076 return DAG.getNode(ISD::SUB, DL, VT,
2077 DAG.getConstant(0, DL, VT), N0);
2079 // fold (mul x, (1 << c)) -> x << c
2080 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2083 return DAG.getNode(ISD::SHL, DL, VT, N0,
2084 DAG.getConstant(ConstValue1.logBase2(), DL,
2085 getShiftAmountTy(N0.getValueType())));
2087 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2088 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2090 unsigned Log2Val = (-ConstValue1).logBase2();
2092 // FIXME: If the input is something that is easily negated (e.g. a
2093 // single-use add), we should put the negate there.
2094 return DAG.getNode(ISD::SUB, DL, VT,
2095 DAG.getConstant(0, DL, VT),
2096 DAG.getNode(ISD::SHL, DL, VT, N0,
2097 DAG.getConstant(Log2Val, DL,
2098 getShiftAmountTy(N0.getValueType()))));
2102 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2103 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2104 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2105 isa<ConstantSDNode>(N0.getOperand(1)))) {
2106 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2107 N1, N0.getOperand(1));
2108 AddToWorklist(C3.getNode());
2109 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2110 N0.getOperand(0), C3);
2113 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2116 SDValue Sh(nullptr,0), Y(nullptr,0);
2117 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2118 if (N0.getOpcode() == ISD::SHL &&
2119 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2120 isa<ConstantSDNode>(N0.getOperand(1))) &&
2121 N0.getNode()->hasOneUse()) {
2123 } else if (N1.getOpcode() == ISD::SHL &&
2124 isa<ConstantSDNode>(N1.getOperand(1)) &&
2125 N1.getNode()->hasOneUse()) {
2130 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2131 Sh.getOperand(0), Y);
2132 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2133 Mul, Sh.getOperand(1));
2137 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2138 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2139 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2140 isa<ConstantSDNode>(N0.getOperand(1))))
2141 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2142 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2143 N0.getOperand(0), N1),
2144 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2145 N0.getOperand(1), N1));
2148 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2154 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2155 SDValue N0 = N->getOperand(0);
2156 SDValue N1 = N->getOperand(1);
2157 EVT VT = N->getValueType(0);
2161 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2164 // fold (sdiv c1, c2) -> c1/c2
2165 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2166 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2167 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2168 return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2169 // fold (sdiv X, 1) -> X
2170 if (N1C && N1C->isOne())
2172 // fold (sdiv X, -1) -> 0-X
2173 if (N1C && N1C->isAllOnesValue()) {
2175 return DAG.getNode(ISD::SUB, DL, VT,
2176 DAG.getConstant(0, DL, VT), N0);
2178 // If we know the sign bits of both operands are zero, strength reduce to a
2179 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2180 if (!VT.isVector()) {
2181 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2182 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2186 // fold (sdiv X, pow2) -> simple ops after legalize
2187 // FIXME: We check for the exact bit here because the generic lowering gives
2188 // better results in that case. The target-specific lowering should learn how
2189 // to handle exact sdivs efficiently.
2190 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2191 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2192 (N1C->getAPIntValue().isPowerOf2() ||
2193 (-N1C->getAPIntValue()).isPowerOf2())) {
2194 // Target-specific implementation of sdiv x, pow2.
2195 if (SDValue Res = BuildSDIVPow2(N))
2198 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2201 // Splat the sign bit into the register
2203 DAG.getNode(ISD::SRA, DL, VT, N0,
2204 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2205 getShiftAmountTy(N0.getValueType())));
2206 AddToWorklist(SGN.getNode());
2208 // Add (N0 < 0) ? abs2 - 1 : 0;
2210 DAG.getNode(ISD::SRL, DL, VT, SGN,
2211 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2212 getShiftAmountTy(SGN.getValueType())));
2213 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2214 AddToWorklist(SRL.getNode());
2215 AddToWorklist(ADD.getNode()); // Divide by pow2
2216 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2217 DAG.getConstant(lg2, DL,
2218 getShiftAmountTy(ADD.getValueType())));
2220 // If we're dividing by a positive value, we're done. Otherwise, we must
2221 // negate the result.
2222 if (N1C->getAPIntValue().isNonNegative())
2225 AddToWorklist(SRA.getNode());
2226 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2229 // If integer divide is expensive and we satisfy the requirements, emit an
2230 // alternate sequence. Targets may check function attributes for size/speed
2232 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2233 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2234 if (SDValue Op = BuildSDIV(N))
2238 if (N0.getOpcode() == ISD::UNDEF)
2239 return DAG.getConstant(0, SDLoc(N), VT);
2240 // X / undef -> undef
2241 if (N1.getOpcode() == ISD::UNDEF)
2247 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2248 SDValue N0 = N->getOperand(0);
2249 SDValue N1 = N->getOperand(1);
2250 EVT VT = N->getValueType(0);
2254 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2257 // fold (udiv c1, c2) -> c1/c2
2258 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2259 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2261 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT,
2264 // fold (udiv x, (1 << c)) -> x >>u c
2265 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) {
2267 return DAG.getNode(ISD::SRL, DL, VT, N0,
2268 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2269 getShiftAmountTy(N0.getValueType())));
2271 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2272 if (N1.getOpcode() == ISD::SHL) {
2273 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2274 if (SHC->getAPIntValue().isPowerOf2()) {
2275 EVT ADDVT = N1.getOperand(1).getValueType();
2277 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2279 DAG.getConstant(SHC->getAPIntValue()
2282 AddToWorklist(Add.getNode());
2283 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2288 // fold (udiv x, c) -> alternate
2289 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2290 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2291 if (SDValue Op = BuildUDIV(N))
2295 if (N0.getOpcode() == ISD::UNDEF)
2296 return DAG.getConstant(0, SDLoc(N), VT);
2297 // X / undef -> undef
2298 if (N1.getOpcode() == ISD::UNDEF)
2304 SDValue DAGCombiner::visitSREM(SDNode *N) {
2305 SDValue N0 = N->getOperand(0);
2306 SDValue N1 = N->getOperand(1);
2307 EVT VT = N->getValueType(0);
2309 // fold (srem c1, c2) -> c1%c2
2310 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2311 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2313 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT,
2316 // If we know the sign bits of both operands are zero, strength reduce to a
2317 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2318 if (!VT.isVector()) {
2319 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2320 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2323 // If X/C can be simplified by the division-by-constant logic, lower
2324 // X%C to the equivalent of X-X/C*C.
2325 if (N1C && !N1C->isNullValue()) {
2326 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2327 AddToWorklist(Div.getNode());
2328 SDValue OptimizedDiv = combine(Div.getNode());
2329 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2330 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2332 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2333 AddToWorklist(Mul.getNode());
2339 if (N0.getOpcode() == ISD::UNDEF)
2340 return DAG.getConstant(0, SDLoc(N), VT);
2341 // X % undef -> undef
2342 if (N1.getOpcode() == ISD::UNDEF)
2348 SDValue DAGCombiner::visitUREM(SDNode *N) {
2349 SDValue N0 = N->getOperand(0);
2350 SDValue N1 = N->getOperand(1);
2351 EVT VT = N->getValueType(0);
2353 // fold (urem c1, c2) -> c1%c2
2354 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2355 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2357 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT,
2360 // fold (urem x, pow2) -> (and x, pow2-1)
2361 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2362 N1C->getAPIntValue().isPowerOf2()) {
2364 return DAG.getNode(ISD::AND, DL, VT, N0,
2365 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2367 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2368 if (N1.getOpcode() == ISD::SHL) {
2369 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2370 if (SHC->getAPIntValue().isPowerOf2()) {
2373 DAG.getNode(ISD::ADD, DL, VT, N1,
2374 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2376 AddToWorklist(Add.getNode());
2377 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2382 // If X/C can be simplified by the division-by-constant logic, lower
2383 // X%C to the equivalent of X-X/C*C.
2384 if (N1C && !N1C->isNullValue()) {
2385 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2386 AddToWorklist(Div.getNode());
2387 SDValue OptimizedDiv = combine(Div.getNode());
2388 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2389 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2391 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2392 AddToWorklist(Mul.getNode());
2398 if (N0.getOpcode() == ISD::UNDEF)
2399 return DAG.getConstant(0, SDLoc(N), VT);
2400 // X % undef -> undef
2401 if (N1.getOpcode() == ISD::UNDEF)
2407 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2408 SDValue N0 = N->getOperand(0);
2409 SDValue N1 = N->getOperand(1);
2410 EVT VT = N->getValueType(0);
2413 // fold (mulhs x, 0) -> 0
2414 if (isNullConstant(N1))
2416 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2417 if (isOneConstant(N1)) {
2419 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2420 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2422 getShiftAmountTy(N0.getValueType())));
2424 // fold (mulhs x, undef) -> 0
2425 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2426 return DAG.getConstant(0, SDLoc(N), VT);
2428 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2430 if (VT.isSimple() && !VT.isVector()) {
2431 MVT Simple = VT.getSimpleVT();
2432 unsigned SimpleSize = Simple.getSizeInBits();
2433 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2434 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2435 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2436 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2437 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2438 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2439 DAG.getConstant(SimpleSize, DL,
2440 getShiftAmountTy(N1.getValueType())));
2441 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2448 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2449 SDValue N0 = N->getOperand(0);
2450 SDValue N1 = N->getOperand(1);
2451 EVT VT = N->getValueType(0);
2454 // fold (mulhu x, 0) -> 0
2455 if (isNullConstant(N1))
2457 // fold (mulhu x, 1) -> 0
2458 if (isOneConstant(N1))
2459 return DAG.getConstant(0, DL, N0.getValueType());
2460 // fold (mulhu x, undef) -> 0
2461 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2462 return DAG.getConstant(0, DL, VT);
2464 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2466 if (VT.isSimple() && !VT.isVector()) {
2467 MVT Simple = VT.getSimpleVT();
2468 unsigned SimpleSize = Simple.getSizeInBits();
2469 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2470 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2471 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2472 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2473 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2474 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2475 DAG.getConstant(SimpleSize, DL,
2476 getShiftAmountTy(N1.getValueType())));
2477 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2484 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2485 /// give the opcodes for the two computations that are being performed. Return
2486 /// true if a simplification was made.
2487 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2489 // If the high half is not needed, just compute the low half.
2490 bool HiExists = N->hasAnyUseOfValue(1);
2492 (!LegalOperations ||
2493 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2494 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2495 return CombineTo(N, Res, Res);
2498 // If the low half is not needed, just compute the high half.
2499 bool LoExists = N->hasAnyUseOfValue(0);
2501 (!LegalOperations ||
2502 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2503 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2504 return CombineTo(N, Res, Res);
2507 // If both halves are used, return as it is.
2508 if (LoExists && HiExists)
2511 // If the two computed results can be simplified separately, separate them.
2513 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2514 AddToWorklist(Lo.getNode());
2515 SDValue LoOpt = combine(Lo.getNode());
2516 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2517 (!LegalOperations ||
2518 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2519 return CombineTo(N, LoOpt, LoOpt);
2523 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2524 AddToWorklist(Hi.getNode());
2525 SDValue HiOpt = combine(Hi.getNode());
2526 if (HiOpt.getNode() && HiOpt != Hi &&
2527 (!LegalOperations ||
2528 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2529 return CombineTo(N, HiOpt, HiOpt);
2535 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2536 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2539 EVT VT = N->getValueType(0);
2542 // If the type is twice as wide is legal, transform the mulhu to a wider
2543 // multiply plus a shift.
2544 if (VT.isSimple() && !VT.isVector()) {
2545 MVT Simple = VT.getSimpleVT();
2546 unsigned SimpleSize = Simple.getSizeInBits();
2547 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2548 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2549 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2550 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2551 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2552 // Compute the high part as N1.
2553 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2554 DAG.getConstant(SimpleSize, DL,
2555 getShiftAmountTy(Lo.getValueType())));
2556 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2557 // Compute the low part as N0.
2558 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2559 return CombineTo(N, Lo, Hi);
2566 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2567 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2570 EVT VT = N->getValueType(0);
2573 // If the type is twice as wide is legal, transform the mulhu to a wider
2574 // multiply plus a shift.
2575 if (VT.isSimple() && !VT.isVector()) {
2576 MVT Simple = VT.getSimpleVT();
2577 unsigned SimpleSize = Simple.getSizeInBits();
2578 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2579 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2580 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2581 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2582 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2583 // Compute the high part as N1.
2584 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2585 DAG.getConstant(SimpleSize, DL,
2586 getShiftAmountTy(Lo.getValueType())));
2587 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2588 // Compute the low part as N0.
2589 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2590 return CombineTo(N, Lo, Hi);
2597 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2598 // (smulo x, 2) -> (saddo x, x)
2599 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2600 if (C2->getAPIntValue() == 2)
2601 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2602 N->getOperand(0), N->getOperand(0));
2607 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2608 // (umulo x, 2) -> (uaddo x, x)
2609 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2610 if (C2->getAPIntValue() == 2)
2611 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2612 N->getOperand(0), N->getOperand(0));
2617 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2618 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM))
2624 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2625 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM))
2631 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2632 SDValue N0 = N->getOperand(0);
2633 SDValue N1 = N->getOperand(1);
2634 EVT VT = N0.getValueType();
2638 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2641 // fold (add c1, c2) -> c1+c2
2642 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2643 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2645 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2647 // canonicalize constant to RHS
2648 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2649 !isConstantIntBuildVectorOrConstantInt(N1))
2650 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2655 /// If this is a binary operator with two operands of the same opcode, try to
2657 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2658 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2659 EVT VT = N0.getValueType();
2660 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2662 // Bail early if none of these transforms apply.
2663 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2665 // For each of OP in AND/OR/XOR:
2666 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2667 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2668 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2669 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2670 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2672 // do not sink logical op inside of a vector extend, since it may combine
2674 EVT Op0VT = N0.getOperand(0).getValueType();
2675 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2676 N0.getOpcode() == ISD::SIGN_EXTEND ||
2677 N0.getOpcode() == ISD::BSWAP ||
2678 // Avoid infinite looping with PromoteIntBinOp.
2679 (N0.getOpcode() == ISD::ANY_EXTEND &&
2680 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2681 (N0.getOpcode() == ISD::TRUNCATE &&
2682 (!TLI.isZExtFree(VT, Op0VT) ||
2683 !TLI.isTruncateFree(Op0VT, VT)) &&
2684 TLI.isTypeLegal(Op0VT))) &&
2686 Op0VT == N1.getOperand(0).getValueType() &&
2687 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2688 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2689 N0.getOperand(0).getValueType(),
2690 N0.getOperand(0), N1.getOperand(0));
2691 AddToWorklist(ORNode.getNode());
2692 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2695 // For each of OP in SHL/SRL/SRA/AND...
2696 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2697 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2698 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2699 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2700 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2701 N0.getOperand(1) == N1.getOperand(1)) {
2702 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2703 N0.getOperand(0).getValueType(),
2704 N0.getOperand(0), N1.getOperand(0));
2705 AddToWorklist(ORNode.getNode());
2706 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2707 ORNode, N0.getOperand(1));
2710 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2711 // Only perform this optimization after type legalization and before
2712 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2713 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2714 // we don't want to undo this promotion.
2715 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2717 if ((N0.getOpcode() == ISD::BITCAST ||
2718 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2719 Level == AfterLegalizeTypes) {
2720 SDValue In0 = N0.getOperand(0);
2721 SDValue In1 = N1.getOperand(0);
2722 EVT In0Ty = In0.getValueType();
2723 EVT In1Ty = In1.getValueType();
2725 // If both incoming values are integers, and the original types are the
2727 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2728 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2729 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2730 AddToWorklist(Op.getNode());
2735 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2736 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2737 // If both shuffles use the same mask, and both shuffle within a single
2738 // vector, then it is worthwhile to move the swizzle after the operation.
2739 // The type-legalizer generates this pattern when loading illegal
2740 // vector types from memory. In many cases this allows additional shuffle
2742 // There are other cases where moving the shuffle after the xor/and/or
2743 // is profitable even if shuffles don't perform a swizzle.
2744 // If both shuffles use the same mask, and both shuffles have the same first
2745 // or second operand, then it might still be profitable to move the shuffle
2746 // after the xor/and/or operation.
2747 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2748 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2749 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2751 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2752 "Inputs to shuffles are not the same type");
2754 // Check that both shuffles use the same mask. The masks are known to be of
2755 // the same length because the result vector type is the same.
2756 // Check also that shuffles have only one use to avoid introducing extra
2758 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2759 SVN0->getMask().equals(SVN1->getMask())) {
2760 SDValue ShOp = N0->getOperand(1);
2762 // Don't try to fold this node if it requires introducing a
2763 // build vector of all zeros that might be illegal at this stage.
2764 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2766 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2771 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2772 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2773 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2774 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2775 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2776 N0->getOperand(0), N1->getOperand(0));
2777 AddToWorklist(NewNode.getNode());
2778 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2779 &SVN0->getMask()[0]);
2782 // Don't try to fold this node if it requires introducing a
2783 // build vector of all zeros that might be illegal at this stage.
2784 ShOp = N0->getOperand(0);
2785 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2787 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2792 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2793 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2794 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2795 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2796 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2797 N0->getOperand(1), N1->getOperand(1));
2798 AddToWorklist(NewNode.getNode());
2799 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2800 &SVN0->getMask()[0]);
2808 /// This contains all DAGCombine rules which reduce two values combined by
2809 /// an And operation to a single value. This makes them reusable in the context
2810 /// of visitSELECT(). Rules involving constants are not included as
2811 /// visitSELECT() already handles those cases.
2812 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2813 SDNode *LocReference) {
2814 EVT VT = N1.getValueType();
2816 // fold (and x, undef) -> 0
2817 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2818 return DAG.getConstant(0, SDLoc(LocReference), VT);
2819 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2820 SDValue LL, LR, RL, RR, CC0, CC1;
2821 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2822 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2823 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2825 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2826 LL.getValueType().isInteger()) {
2827 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2828 if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2829 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2830 LR.getValueType(), LL, RL);
2831 AddToWorklist(ORNode.getNode());
2832 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2834 if (isAllOnesConstant(LR)) {
2835 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2836 if (Op1 == ISD::SETEQ) {
2837 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2838 LR.getValueType(), LL, RL);
2839 AddToWorklist(ANDNode.getNode());
2840 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2842 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2843 if (Op1 == ISD::SETGT) {
2844 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2845 LR.getValueType(), LL, RL);
2846 AddToWorklist(ORNode.getNode());
2847 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2851 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2852 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2853 Op0 == Op1 && LL.getValueType().isInteger() &&
2854 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2855 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2857 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2858 LL, DAG.getConstant(1, DL,
2859 LL.getValueType()));
2860 AddToWorklist(ADDNode.getNode());
2861 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2862 DAG.getConstant(2, DL, LL.getValueType()),
2865 // canonicalize equivalent to ll == rl
2866 if (LL == RR && LR == RL) {
2867 Op1 = ISD::getSetCCSwappedOperands(Op1);
2870 if (LL == RL && LR == RR) {
2871 bool isInteger = LL.getValueType().isInteger();
2872 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2873 if (Result != ISD::SETCC_INVALID &&
2874 (!LegalOperations ||
2875 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2876 TLI.isOperationLegal(ISD::SETCC,
2877 getSetCCResultType(N0.getSimpleValueType())))))
2878 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2883 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2884 VT.getSizeInBits() <= 64) {
2885 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2886 APInt ADDC = ADDI->getAPIntValue();
2887 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2888 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2889 // immediate for an add, but it is legal if its top c2 bits are set,
2890 // transform the ADD so the immediate doesn't need to be materialized
2892 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2893 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2894 SRLI->getZExtValue());
2895 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2897 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2900 DAG.getNode(ISD::ADD, DL, VT,
2901 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2902 CombineTo(N0.getNode(), NewAdd);
2903 // Return N so it doesn't get rechecked!
2904 return SDValue(LocReference, 0);
2915 SDValue DAGCombiner::visitAND(SDNode *N) {
2916 SDValue N0 = N->getOperand(0);
2917 SDValue N1 = N->getOperand(1);
2918 EVT VT = N1.getValueType();
2921 if (VT.isVector()) {
2922 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2925 // fold (and x, 0) -> 0, vector edition
2926 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2927 // do not return N0, because undef node may exist in N0
2928 return DAG.getConstant(
2929 APInt::getNullValue(
2930 N0.getValueType().getScalarType().getSizeInBits()),
2931 SDLoc(N), N0.getValueType());
2932 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2933 // do not return N1, because undef node may exist in N1
2934 return DAG.getConstant(
2935 APInt::getNullValue(
2936 N1.getValueType().getScalarType().getSizeInBits()),
2937 SDLoc(N), N1.getValueType());
2939 // fold (and x, -1) -> x, vector edition
2940 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2942 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2946 // fold (and c1, c2) -> c1&c2
2947 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2948 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2949 if (N0C && N1C && !N1C->isOpaque())
2950 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2951 // canonicalize constant to RHS
2952 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2953 !isConstantIntBuildVectorOrConstantInt(N1))
2954 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2955 // fold (and x, -1) -> x
2956 if (isAllOnesConstant(N1))
2958 // if (and x, c) is known to be zero, return 0
2959 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2960 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2961 APInt::getAllOnesValue(BitWidth)))
2962 return DAG.getConstant(0, SDLoc(N), VT);
2964 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2966 // fold (and (or x, C), D) -> D if (C & D) == D
2967 if (N1C && N0.getOpcode() == ISD::OR)
2968 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2969 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2971 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2972 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2973 SDValue N0Op0 = N0.getOperand(0);
2974 APInt Mask = ~N1C->getAPIntValue();
2975 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2976 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2977 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2978 N0.getValueType(), N0Op0);
2980 // Replace uses of the AND with uses of the Zero extend node.
2983 // We actually want to replace all uses of the any_extend with the
2984 // zero_extend, to avoid duplicating things. This will later cause this
2985 // AND to be folded.
2986 CombineTo(N0.getNode(), Zext);
2987 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2990 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2991 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2992 // already be zero by virtue of the width of the base type of the load.
2994 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2996 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2997 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2998 N0.getOpcode() == ISD::LOAD) {
2999 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3000 N0 : N0.getOperand(0) );
3002 // Get the constant (if applicable) the zero'th operand is being ANDed with.
3003 // This can be a pure constant or a vector splat, in which case we treat the
3004 // vector as a scalar and use the splat value.
3005 APInt Constant = APInt::getNullValue(1);
3006 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3007 Constant = C->getAPIntValue();
3008 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3009 APInt SplatValue, SplatUndef;
3010 unsigned SplatBitSize;
3012 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3013 SplatBitSize, HasAnyUndefs);
3015 // Undef bits can contribute to a possible optimisation if set, so
3017 SplatValue |= SplatUndef;
3019 // The splat value may be something like "0x00FFFFFF", which means 0 for
3020 // the first vector value and FF for the rest, repeating. We need a mask
3021 // that will apply equally to all members of the vector, so AND all the
3022 // lanes of the constant together.
3023 EVT VT = Vector->getValueType(0);
3024 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3026 // If the splat value has been compressed to a bitlength lower
3027 // than the size of the vector lane, we need to re-expand it to
3029 if (BitWidth > SplatBitSize)
3030 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3031 SplatBitSize < BitWidth;
3032 SplatBitSize = SplatBitSize * 2)
3033 SplatValue |= SplatValue.shl(SplatBitSize);
3035 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3036 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3037 if (SplatBitSize % BitWidth == 0) {
3038 Constant = APInt::getAllOnesValue(BitWidth);
3039 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3040 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3045 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3046 // actually legal and isn't going to get expanded, else this is a false
3048 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3049 Load->getValueType(0),
3050 Load->getMemoryVT());
3052 // Resize the constant to the same size as the original memory access before
3053 // extension. If it is still the AllOnesValue then this AND is completely
3056 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3059 switch (Load->getExtensionType()) {
3060 default: B = false; break;
3061 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3063 case ISD::NON_EXTLOAD: B = true; break;
3066 if (B && Constant.isAllOnesValue()) {
3067 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3068 // preserve semantics once we get rid of the AND.
3069 SDValue NewLoad(Load, 0);
3070 if (Load->getExtensionType() == ISD::EXTLOAD) {
3071 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3072 Load->getValueType(0), SDLoc(Load),
3073 Load->getChain(), Load->getBasePtr(),
3074 Load->getOffset(), Load->getMemoryVT(),
3075 Load->getMemOperand());
3076 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3077 if (Load->getNumValues() == 3) {
3078 // PRE/POST_INC loads have 3 values.
3079 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3080 NewLoad.getValue(2) };
3081 CombineTo(Load, To, 3, true);
3083 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3087 // Fold the AND away, taking care not to fold to the old load node if we
3089 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3091 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3095 // fold (and (load x), 255) -> (zextload x, i8)
3096 // fold (and (extload x, i16), 255) -> (zextload x, i8)
3097 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3098 if (N1C && (N0.getOpcode() == ISD::LOAD ||
3099 (N0.getOpcode() == ISD::ANY_EXTEND &&
3100 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3101 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3102 LoadSDNode *LN0 = HasAnyExt
3103 ? cast<LoadSDNode>(N0.getOperand(0))
3104 : cast<LoadSDNode>(N0);
3105 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3106 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3107 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3108 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3109 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3110 EVT LoadedVT = LN0->getMemoryVT();
3111 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3113 if (ExtVT == LoadedVT &&
3114 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3118 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3119 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3120 LN0->getMemOperand());
3122 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3123 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3126 // Do not change the width of a volatile load.
3127 // Do not generate loads of non-round integer types since these can
3128 // be expensive (and would be wrong if the type is not byte sized).
3129 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3130 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3132 EVT PtrType = LN0->getOperand(1).getValueType();
3134 unsigned Alignment = LN0->getAlignment();
3135 SDValue NewPtr = LN0->getBasePtr();
3137 // For big endian targets, we need to add an offset to the pointer
3138 // to load the correct bytes. For little endian systems, we merely
3139 // need to read fewer bytes from the same pointer.
3140 if (DAG.getDataLayout().isBigEndian()) {
3141 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3142 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3143 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3145 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3146 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3147 Alignment = MinAlign(Alignment, PtrOff);
3150 AddToWorklist(NewPtr.getNode());
3153 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3154 LN0->getChain(), NewPtr,
3155 LN0->getPointerInfo(),
3156 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3157 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3159 CombineTo(LN0, Load, Load.getValue(1));
3160 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3166 if (SDValue Combined = visitANDLike(N0, N1, N))
3169 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3170 if (N0.getOpcode() == N1.getOpcode())
3171 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3174 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3175 // fold (and (sra)) -> (and (srl)) when possible.
3176 if (!VT.isVector() &&
3177 SimplifyDemandedBits(SDValue(N, 0)))
3178 return SDValue(N, 0);
3180 // fold (zext_inreg (extload x)) -> (zextload x)
3181 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3182 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3183 EVT MemVT = LN0->getMemoryVT();
3184 // If we zero all the possible extended bits, then we can turn this into
3185 // a zextload if we are running before legalize or the operation is legal.
3186 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3187 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3188 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3189 ((!LegalOperations && !LN0->isVolatile()) ||
3190 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3191 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3192 LN0->getChain(), LN0->getBasePtr(),
3193 MemVT, LN0->getMemOperand());
3195 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3196 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3199 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3200 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3202 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3203 EVT MemVT = LN0->getMemoryVT();
3204 // If we zero all the possible extended bits, then we can turn this into
3205 // a zextload if we are running before legalize or the operation is legal.
3206 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3207 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3208 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3209 ((!LegalOperations && !LN0->isVolatile()) ||
3210 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3211 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3212 LN0->getChain(), LN0->getBasePtr(),
3213 MemVT, LN0->getMemOperand());
3215 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3216 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3219 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3220 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3221 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3222 N0.getOperand(1), false);
3223 if (BSwap.getNode())
3230 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3231 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3232 bool DemandHighBits) {
3233 if (!LegalOperations)
3236 EVT VT = N->getValueType(0);
3237 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3239 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3242 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3243 bool LookPassAnd0 = false;
3244 bool LookPassAnd1 = false;
3245 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3247 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3249 if (N0.getOpcode() == ISD::AND) {
3250 if (!N0.getNode()->hasOneUse())
3252 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3253 if (!N01C || N01C->getZExtValue() != 0xFF00)
3255 N0 = N0.getOperand(0);
3256 LookPassAnd0 = true;
3259 if (N1.getOpcode() == ISD::AND) {
3260 if (!N1.getNode()->hasOneUse())
3262 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3263 if (!N11C || N11C->getZExtValue() != 0xFF)
3265 N1 = N1.getOperand(0);
3266 LookPassAnd1 = true;
3269 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3271 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3273 if (!N0.getNode()->hasOneUse() ||
3274 !N1.getNode()->hasOneUse())
3277 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3278 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3281 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3284 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3285 SDValue N00 = N0->getOperand(0);
3286 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3287 if (!N00.getNode()->hasOneUse())
3289 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3290 if (!N001C || N001C->getZExtValue() != 0xFF)
3292 N00 = N00.getOperand(0);
3293 LookPassAnd0 = true;
3296 SDValue N10 = N1->getOperand(0);
3297 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3298 if (!N10.getNode()->hasOneUse())
3300 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3301 if (!N101C || N101C->getZExtValue() != 0xFF00)
3303 N10 = N10.getOperand(0);
3304 LookPassAnd1 = true;
3310 // Make sure everything beyond the low halfword gets set to zero since the SRL
3311 // 16 will clear the top bits.
3312 unsigned OpSizeInBits = VT.getSizeInBits();
3313 if (DemandHighBits && OpSizeInBits > 16) {
3314 // If the left-shift isn't masked out then the only way this is a bswap is
3315 // if all bits beyond the low 8 are 0. In that case the entire pattern
3316 // reduces to a left shift anyway: leave it for other parts of the combiner.
3320 // However, if the right shift isn't masked out then it might be because
3321 // it's not needed. See if we can spot that too.
3322 if (!LookPassAnd1 &&
3323 !DAG.MaskedValueIsZero(
3324 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3328 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3329 if (OpSizeInBits > 16) {
3331 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3332 DAG.getConstant(OpSizeInBits - 16, DL,
3333 getShiftAmountTy(VT)));
3338 /// Return true if the specified node is an element that makes up a 32-bit
3339 /// packed halfword byteswap.
3340 /// ((x & 0x000000ff) << 8) |
3341 /// ((x & 0x0000ff00) >> 8) |
3342 /// ((x & 0x00ff0000) << 8) |
3343 /// ((x & 0xff000000) >> 8)
3344 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3345 if (!N.getNode()->hasOneUse())
3348 unsigned Opc = N.getOpcode();
3349 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3352 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3357 switch (N1C->getZExtValue()) {
3360 case 0xFF: Num = 0; break;
3361 case 0xFF00: Num = 1; break;
3362 case 0xFF0000: Num = 2; break;
3363 case 0xFF000000: Num = 3; break;
3366 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3367 SDValue N0 = N.getOperand(0);
3368 if (Opc == ISD::AND) {
3369 if (Num == 0 || Num == 2) {
3371 // (x >> 8) & 0xff0000
3372 if (N0.getOpcode() != ISD::SRL)
3374 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3375 if (!C || C->getZExtValue() != 8)
3378 // (x << 8) & 0xff00
3379 // (x << 8) & 0xff000000
3380 if (N0.getOpcode() != ISD::SHL)
3382 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3383 if (!C || C->getZExtValue() != 8)
3386 } else if (Opc == ISD::SHL) {
3388 // (x & 0xff0000) << 8
3389 if (Num != 0 && Num != 2)
3391 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3392 if (!C || C->getZExtValue() != 8)
3394 } else { // Opc == ISD::SRL
3395 // (x & 0xff00) >> 8
3396 // (x & 0xff000000) >> 8
3397 if (Num != 1 && Num != 3)
3399 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3400 if (!C || C->getZExtValue() != 8)
3407 Parts[Num] = N0.getOperand(0).getNode();
3411 /// Match a 32-bit packed halfword bswap. That is
3412 /// ((x & 0x000000ff) << 8) |
3413 /// ((x & 0x0000ff00) >> 8) |
3414 /// ((x & 0x00ff0000) << 8) |
3415 /// ((x & 0xff000000) >> 8)
3416 /// => (rotl (bswap x), 16)
3417 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3418 if (!LegalOperations)
3421 EVT VT = N->getValueType(0);
3424 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3428 // (or (or (and), (and)), (or (and), (and)))
3429 // (or (or (or (and), (and)), (and)), (and))
3430 if (N0.getOpcode() != ISD::OR)
3432 SDValue N00 = N0.getOperand(0);
3433 SDValue N01 = N0.getOperand(1);
3434 SDNode *Parts[4] = {};
3436 if (N1.getOpcode() == ISD::OR &&
3437 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3438 // (or (or (and), (and)), (or (and), (and)))
3439 SDValue N000 = N00.getOperand(0);
3440 if (!isBSwapHWordElement(N000, Parts))
3443 SDValue N001 = N00.getOperand(1);
3444 if (!isBSwapHWordElement(N001, Parts))
3446 SDValue N010 = N01.getOperand(0);
3447 if (!isBSwapHWordElement(N010, Parts))
3449 SDValue N011 = N01.getOperand(1);
3450 if (!isBSwapHWordElement(N011, Parts))
3453 // (or (or (or (and), (and)), (and)), (and))
3454 if (!isBSwapHWordElement(N1, Parts))
3456 if (!isBSwapHWordElement(N01, Parts))
3458 if (N00.getOpcode() != ISD::OR)
3460 SDValue N000 = N00.getOperand(0);
3461 if (!isBSwapHWordElement(N000, Parts))
3463 SDValue N001 = N00.getOperand(1);
3464 if (!isBSwapHWordElement(N001, Parts))
3468 // Make sure the parts are all coming from the same node.
3469 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3473 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3474 SDValue(Parts[0], 0));
3476 // Result of the bswap should be rotated by 16. If it's not legal, then
3477 // do (x << 16) | (x >> 16).
3478 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3479 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3480 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3481 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3482 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3483 return DAG.getNode(ISD::OR, DL, VT,
3484 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3485 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3488 /// This contains all DAGCombine rules which reduce two values combined by
3489 /// an Or operation to a single value \see visitANDLike().
3490 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3491 EVT VT = N1.getValueType();
3492 // fold (or x, undef) -> -1
3493 if (!LegalOperations &&
3494 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3495 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3496 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3497 SDLoc(LocReference), VT);
3499 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3500 SDValue LL, LR, RL, RR, CC0, CC1;
3501 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3502 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3503 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3505 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3506 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3507 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3508 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3509 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3510 LR.getValueType(), LL, RL);
3511 AddToWorklist(ORNode.getNode());
3512 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3514 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3515 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3516 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3517 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3518 LR.getValueType(), LL, RL);
3519 AddToWorklist(ANDNode.getNode());
3520 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3523 // canonicalize equivalent to ll == rl
3524 if (LL == RR && LR == RL) {
3525 Op1 = ISD::getSetCCSwappedOperands(Op1);
3528 if (LL == RL && LR == RR) {
3529 bool isInteger = LL.getValueType().isInteger();
3530 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3531 if (Result != ISD::SETCC_INVALID &&
3532 (!LegalOperations ||
3533 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3534 TLI.isOperationLegal(ISD::SETCC,
3535 getSetCCResultType(N0.getValueType())))))
3536 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3541 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3542 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3543 // Don't increase # computations.
3544 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3545 // We can only do this xform if we know that bits from X that are set in C2
3546 // but not in C1 are already zero. Likewise for Y.
3547 if (const ConstantSDNode *N0O1C =
3548 getAsNonOpaqueConstant(N0.getOperand(1))) {
3549 if (const ConstantSDNode *N1O1C =
3550 getAsNonOpaqueConstant(N1.getOperand(1))) {
3551 // We can only do this xform if we know that bits from X that are set in
3552 // C2 but not in C1 are already zero. Likewise for Y.
3553 const APInt &LHSMask = N0O1C->getAPIntValue();
3554 const APInt &RHSMask = N1O1C->getAPIntValue();
3556 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3557 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3558 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3559 N0.getOperand(0), N1.getOperand(0));
3560 SDLoc DL(LocReference);
3561 return DAG.getNode(ISD::AND, DL, VT, X,
3562 DAG.getConstant(LHSMask | RHSMask, DL, VT));
3568 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3569 if (N0.getOpcode() == ISD::AND &&
3570 N1.getOpcode() == ISD::AND &&
3571 N0.getOperand(0) == N1.getOperand(0) &&
3572 // Don't increase # computations.
3573 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3574 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3575 N0.getOperand(1), N1.getOperand(1));
3576 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3582 SDValue DAGCombiner::visitOR(SDNode *N) {
3583 SDValue N0 = N->getOperand(0);
3584 SDValue N1 = N->getOperand(1);
3585 EVT VT = N1.getValueType();
3588 if (VT.isVector()) {
3589 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3592 // fold (or x, 0) -> x, vector edition
3593 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3595 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3598 // fold (or x, -1) -> -1, vector edition
3599 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3600 // do not return N0, because undef node may exist in N0
3601 return DAG.getConstant(
3602 APInt::getAllOnesValue(
3603 N0.getValueType().getScalarType().getSizeInBits()),
3604 SDLoc(N), N0.getValueType());
3605 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3606 // do not return N1, because undef node may exist in N1
3607 return DAG.getConstant(
3608 APInt::getAllOnesValue(
3609 N1.getValueType().getScalarType().getSizeInBits()),
3610 SDLoc(N), N1.getValueType());
3612 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3613 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3614 // Do this only if the resulting shuffle is legal.
3615 if (isa<ShuffleVectorSDNode>(N0) &&
3616 isa<ShuffleVectorSDNode>(N1) &&
3617 // Avoid folding a node with illegal type.
3618 TLI.isTypeLegal(VT) &&
3619 N0->getOperand(1) == N1->getOperand(1) &&
3620 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3621 bool CanFold = true;
3622 unsigned NumElts = VT.getVectorNumElements();
3623 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3624 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3625 // We construct two shuffle masks:
3626 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3627 // and N1 as the second operand.
3628 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3629 // and N0 as the second operand.
3630 // We do this because OR is commutable and therefore there might be
3631 // two ways to fold this node into a shuffle.
3632 SmallVector<int,4> Mask1;
3633 SmallVector<int,4> Mask2;
3635 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3636 int M0 = SV0->getMaskElt(i);
3637 int M1 = SV1->getMaskElt(i);
3639 // Both shuffle indexes are undef. Propagate Undef.
3640 if (M0 < 0 && M1 < 0) {
3641 Mask1.push_back(M0);
3642 Mask2.push_back(M0);
3646 if (M0 < 0 || M1 < 0 ||
3647 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3648 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3653 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3654 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3658 // Fold this sequence only if the resulting shuffle is 'legal'.
3659 if (TLI.isShuffleMaskLegal(Mask1, VT))
3660 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3661 N1->getOperand(0), &Mask1[0]);
3662 if (TLI.isShuffleMaskLegal(Mask2, VT))
3663 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3664 N0->getOperand(0), &Mask2[0]);
3669 // fold (or c1, c2) -> c1|c2
3670 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3671 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3672 if (N0C && N1C && !N1C->isOpaque())
3673 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3674 // canonicalize constant to RHS
3675 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3676 !isConstantIntBuildVectorOrConstantInt(N1))
3677 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3678 // fold (or x, 0) -> x
3679 if (isNullConstant(N1))
3681 // fold (or x, -1) -> -1
3682 if (isAllOnesConstant(N1))
3684 // fold (or x, c) -> c iff (x & ~c) == 0
3685 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3688 if (SDValue Combined = visitORLike(N0, N1, N))
3691 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3692 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3694 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3698 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3700 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3701 // iff (c1 & c2) == 0.
3702 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3703 isa<ConstantSDNode>(N0.getOperand(1))) {
3704 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3705 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3706 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3709 ISD::AND, SDLoc(N), VT,
3710 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3714 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3715 if (N0.getOpcode() == N1.getOpcode())
3716 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3719 // See if this is some rotate idiom.
3720 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3721 return SDValue(Rot, 0);
3723 // Simplify the operands using demanded-bits information.
3724 if (!VT.isVector() &&
3725 SimplifyDemandedBits(SDValue(N, 0)))
3726 return SDValue(N, 0);
3731 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3732 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3733 if (Op.getOpcode() == ISD::AND) {
3734 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3735 Mask = Op.getOperand(1);
3736 Op = Op.getOperand(0);
3742 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3750 // Return true if we can prove that, whenever Neg and Pos are both in the
3751 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3752 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3754 // (or (shift1 X, Neg), (shift2 X, Pos))
3756 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3757 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3758 // to consider shift amounts with defined behavior.
3759 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3760 // If OpSize is a power of 2 then:
3762 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3763 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3765 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3766 // for the stronger condition:
3768 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3770 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3771 // we can just replace Neg with Neg' for the rest of the function.
3773 // In other cases we check for the even stronger condition:
3775 // Neg == OpSize - Pos [B]
3777 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3778 // behavior if Pos == 0 (and consequently Neg == OpSize).
3780 // We could actually use [A] whenever OpSize is a power of 2, but the
3781 // only extra cases that it would match are those uninteresting ones
3782 // where Neg and Pos are never in range at the same time. E.g. for
3783 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3784 // as well as (sub 32, Pos), but:
3786 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3788 // always invokes undefined behavior for 32-bit X.
3790 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3791 unsigned MaskLoBits = 0;
3792 if (Neg.getOpcode() == ISD::AND &&
3793 isPowerOf2_64(OpSize) &&
3794 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3795 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3796 Neg = Neg.getOperand(0);
3797 MaskLoBits = Log2_64(OpSize);
3800 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3801 if (Neg.getOpcode() != ISD::SUB)
3803 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3806 SDValue NegOp1 = Neg.getOperand(1);
3808 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3809 // Pos'. The truncation is redundant for the purpose of the equality.
3811 Pos.getOpcode() == ISD::AND &&
3812 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3813 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3814 Pos = Pos.getOperand(0);
3816 // The condition we need is now:
3818 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3820 // If NegOp1 == Pos then we need:
3822 // OpSize & Mask == NegC & Mask
3824 // (because "x & Mask" is a truncation and distributes through subtraction).
3827 Width = NegC->getAPIntValue();
3828 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3829 // Then the condition we want to prove becomes:
3831 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3833 // which, again because "x & Mask" is a truncation, becomes:
3835 // NegC & Mask == (OpSize - PosC) & Mask
3836 // OpSize & Mask == (NegC + PosC) & Mask
3837 else if (Pos.getOpcode() == ISD::ADD &&
3838 Pos.getOperand(0) == NegOp1 &&
3839 Pos.getOperand(1).getOpcode() == ISD::Constant)
3840 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3841 NegC->getAPIntValue());
3845 // Now we just need to check that OpSize & Mask == Width & Mask.
3847 // Opsize & Mask is 0 since Mask is Opsize - 1.
3848 return Width.getLoBits(MaskLoBits) == 0;
3849 return Width == OpSize;
3852 // A subroutine of MatchRotate used once we have found an OR of two opposite
3853 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3854 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3855 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3856 // Neg with outer conversions stripped away.
3857 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3858 SDValue Neg, SDValue InnerPos,
3859 SDValue InnerNeg, unsigned PosOpcode,
3860 unsigned NegOpcode, SDLoc DL) {
3861 // fold (or (shl x, (*ext y)),
3862 // (srl x, (*ext (sub 32, y)))) ->
3863 // (rotl x, y) or (rotr x, (sub 32, y))
3865 // fold (or (shl x, (*ext (sub 32, y))),
3866 // (srl x, (*ext y))) ->
3867 // (rotr x, y) or (rotl x, (sub 32, y))
3868 EVT VT = Shifted.getValueType();
3869 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3870 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3871 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3872 HasPos ? Pos : Neg).getNode();
3878 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3879 // idioms for rotate, and if the target supports rotation instructions, generate
3881 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3882 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3883 EVT VT = LHS.getValueType();
3884 if (!TLI.isTypeLegal(VT)) return nullptr;
3886 // The target must have at least one rotate flavor.
3887 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3888 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3889 if (!HasROTL && !HasROTR) return nullptr;
3891 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3892 SDValue LHSShift; // The shift.
3893 SDValue LHSMask; // AND value if any.
3894 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3895 return nullptr; // Not part of a rotate.
3897 SDValue RHSShift; // The shift.
3898 SDValue RHSMask; // AND value if any.
3899 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3900 return nullptr; // Not part of a rotate.
3902 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3903 return nullptr; // Not shifting the same value.
3905 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3906 return nullptr; // Shifts must disagree.
3908 // Canonicalize shl to left side in a shl/srl pair.
3909 if (RHSShift.getOpcode() == ISD::SHL) {
3910 std::swap(LHS, RHS);
3911 std::swap(LHSShift, RHSShift);
3912 std::swap(LHSMask , RHSMask );
3915 unsigned OpSizeInBits = VT.getSizeInBits();
3916 SDValue LHSShiftArg = LHSShift.getOperand(0);
3917 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3918 SDValue RHSShiftArg = RHSShift.getOperand(0);
3919 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3921 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3922 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3923 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3924 RHSShiftAmt.getOpcode() == ISD::Constant) {
3925 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3926 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3927 if ((LShVal + RShVal) != OpSizeInBits)
3930 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3931 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3933 // If there is an AND of either shifted operand, apply it to the result.
3934 if (LHSMask.getNode() || RHSMask.getNode()) {
3935 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3937 if (LHSMask.getNode()) {
3938 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3939 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3941 if (RHSMask.getNode()) {
3942 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3943 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3946 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3949 return Rot.getNode();
3952 // If there is a mask here, and we have a variable shift, we can't be sure
3953 // that we're masking out the right stuff.
3954 if (LHSMask.getNode() || RHSMask.getNode())
3957 // If the shift amount is sign/zext/any-extended just peel it off.
3958 SDValue LExtOp0 = LHSShiftAmt;
3959 SDValue RExtOp0 = RHSShiftAmt;
3960 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3961 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3962 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3963 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3964 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3965 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3966 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3967 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3968 LExtOp0 = LHSShiftAmt.getOperand(0);
3969 RExtOp0 = RHSShiftAmt.getOperand(0);
3972 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3973 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3977 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3978 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3985 SDValue DAGCombiner::visitXOR(SDNode *N) {
3986 SDValue N0 = N->getOperand(0);
3987 SDValue N1 = N->getOperand(1);
3988 EVT VT = N0.getValueType();
3991 if (VT.isVector()) {
3992 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3995 // fold (xor x, 0) -> x, vector edition
3996 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3998 if (ISD::isBuildVectorAllZeros(N1.getNode()))
4002 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4003 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
4004 return DAG.getConstant(0, SDLoc(N), VT);
4005 // fold (xor x, undef) -> undef
4006 if (N0.getOpcode() == ISD::UNDEF)
4008 if (N1.getOpcode() == ISD::UNDEF)
4010 // fold (xor c1, c2) -> c1^c2
4011 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4012 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4014 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4015 // canonicalize constant to RHS
4016 if (isConstantIntBuildVectorOrConstantInt(N0) &&
4017 !isConstantIntBuildVectorOrConstantInt(N1))
4018 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4019 // fold (xor x, 0) -> x
4020 if (isNullConstant(N1))
4023 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4026 // fold !(x cc y) -> (x !cc y)
4027 SDValue LHS, RHS, CC;
4028 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4029 bool isInt = LHS.getValueType().isInteger();
4030 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4033 if (!LegalOperations ||
4034 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4035 switch (N0.getOpcode()) {
4037 llvm_unreachable("Unhandled SetCC Equivalent!");
4039 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4040 case ISD::SELECT_CC:
4041 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4042 N0.getOperand(3), NotCC);
4047 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4048 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4049 N0.getNode()->hasOneUse() &&
4050 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4051 SDValue V = N0.getOperand(0);
4053 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4054 DAG.getConstant(1, DL, V.getValueType()));
4055 AddToWorklist(V.getNode());
4056 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4059 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4060 if (isOneConstant(N1) && VT == MVT::i1 &&
4061 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4062 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4063 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4064 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4065 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4066 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4067 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4068 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4071 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4072 if (isAllOnesConstant(N1) &&
4073 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4074 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4075 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4076 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4077 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4078 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4079 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4080 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4083 // fold (xor (and x, y), y) -> (and (not x), y)
4084 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4085 N0->getOperand(1) == N1) {
4086 SDValue X = N0->getOperand(0);
4087 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4088 AddToWorklist(NotX.getNode());
4089 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4091 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4092 if (N1C && N0.getOpcode() == ISD::XOR) {
4093 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4095 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4096 DAG.getConstant(N1C->getAPIntValue() ^
4097 N00C->getAPIntValue(), DL, VT));
4099 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4101 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4102 DAG.getConstant(N1C->getAPIntValue() ^
4103 N01C->getAPIntValue(), DL, VT));
4106 // fold (xor x, x) -> 0
4108 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4110 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4111 // Here is a concrete example of this equivalence:
4113 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
4114 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4118 // i16 ~1 == 0b1111111111111110
4119 // i16 rol(~1, 14) == 0b1011111111111111
4121 // Some additional tips to help conceptualize this transform:
4122 // - Try to see the operation as placing a single zero in a value of all ones.
4123 // - There exists no value for x which would allow the result to contain zero.
4124 // - Values of x larger than the bitwidth are undefined and do not require a
4125 // consistent result.
4126 // - Pushing the zero left requires shifting one bits in from the right.
4127 // A rotate left of ~1 is a nice way of achieving the desired result.
4128 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4129 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4131 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4135 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4136 if (N0.getOpcode() == N1.getOpcode())
4137 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4140 // Simplify the expression using non-local knowledge.
4141 if (!VT.isVector() &&
4142 SimplifyDemandedBits(SDValue(N, 0)))
4143 return SDValue(N, 0);
4148 /// Handle transforms common to the three shifts, when the shift amount is a
4150 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4151 SDNode *LHS = N->getOperand(0).getNode();
4152 if (!LHS->hasOneUse()) return SDValue();
4154 // We want to pull some binops through shifts, so that we have (and (shift))
4155 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4156 // thing happens with address calculations, so it's important to canonicalize
4158 bool HighBitSet = false; // Can we transform this if the high bit is set?
4160 switch (LHS->getOpcode()) {
4161 default: return SDValue();
4164 HighBitSet = false; // We can only transform sra if the high bit is clear.
4167 HighBitSet = true; // We can only transform sra if the high bit is set.
4170 if (N->getOpcode() != ISD::SHL)
4171 return SDValue(); // only shl(add) not sr[al](add).
4172 HighBitSet = false; // We can only transform sra if the high bit is clear.
4176 // We require the RHS of the binop to be a constant and not opaque as well.
4177 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4178 if (!BinOpCst) return SDValue();
4180 // FIXME: disable this unless the input to the binop is a shift by a constant.
4181 // If it is not a shift, it pessimizes some common cases like:
4183 // void foo(int *X, int i) { X[i & 1235] = 1; }
4184 // int bar(int *X, int i) { return X[i & 255]; }
4185 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4186 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4187 BinOpLHSVal->getOpcode() != ISD::SRA &&
4188 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4189 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4192 EVT VT = N->getValueType(0);
4194 // If this is a signed shift right, and the high bit is modified by the
4195 // logical operation, do not perform the transformation. The highBitSet
4196 // boolean indicates the value of the high bit of the constant which would
4197 // cause it to be modified for this operation.
4198 if (N->getOpcode() == ISD::SRA) {
4199 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4200 if (BinOpRHSSignSet != HighBitSet)
4204 if (!TLI.isDesirableToCommuteWithShift(LHS))
4207 // Fold the constants, shifting the binop RHS by the shift amount.
4208 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4210 LHS->getOperand(1), N->getOperand(1));
4211 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4213 // Create the new shift.
4214 SDValue NewShift = DAG.getNode(N->getOpcode(),
4215 SDLoc(LHS->getOperand(0)),
4216 VT, LHS->getOperand(0), N->getOperand(1));
4218 // Create the new binop.
4219 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4222 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4223 assert(N->getOpcode() == ISD::TRUNCATE);
4224 assert(N->getOperand(0).getOpcode() == ISD::AND);
4226 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4227 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4228 SDValue N01 = N->getOperand(0).getOperand(1);
4230 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4231 if (!N01C->isOpaque()) {
4232 EVT TruncVT = N->getValueType(0);
4233 SDValue N00 = N->getOperand(0).getOperand(0);
4234 APInt TruncC = N01C->getAPIntValue();
4235 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4238 return DAG.getNode(ISD::AND, DL, TruncVT,
4239 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4240 DAG.getConstant(TruncC, DL, TruncVT));
4248 SDValue DAGCombiner::visitRotate(SDNode *N) {
4249 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4250 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4251 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4252 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4253 if (NewOp1.getNode())
4254 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4255 N->getOperand(0), NewOp1);
4260 SDValue DAGCombiner::visitSHL(SDNode *N) {
4261 SDValue N0 = N->getOperand(0);
4262 SDValue N1 = N->getOperand(1);
4263 EVT VT = N0.getValueType();
4264 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4267 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4268 if (VT.isVector()) {
4269 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4272 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4273 // If setcc produces all-one true value then:
4274 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4275 if (N1CV && N1CV->isConstant()) {
4276 if (N0.getOpcode() == ISD::AND) {
4277 SDValue N00 = N0->getOperand(0);
4278 SDValue N01 = N0->getOperand(1);
4279 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4281 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4282 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4283 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4284 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4286 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4289 N1C = isConstOrConstSplat(N1);
4294 // fold (shl c1, c2) -> c1<<c2
4295 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4296 if (N0C && N1C && !N1C->isOpaque())
4297 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4298 // fold (shl 0, x) -> 0
4299 if (isNullConstant(N0))
4301 // fold (shl x, c >= size(x)) -> undef
4302 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4303 return DAG.getUNDEF(VT);
4304 // fold (shl x, 0) -> x
4305 if (N1C && N1C->isNullValue())
4307 // fold (shl undef, x) -> 0
4308 if (N0.getOpcode() == ISD::UNDEF)
4309 return DAG.getConstant(0, SDLoc(N), VT);
4310 // if (shl x, c) is known to be zero, return 0
4311 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4312 APInt::getAllOnesValue(OpSizeInBits)))
4313 return DAG.getConstant(0, SDLoc(N), VT);
4314 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4315 if (N1.getOpcode() == ISD::TRUNCATE &&
4316 N1.getOperand(0).getOpcode() == ISD::AND) {
4317 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4318 if (NewOp1.getNode())
4319 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4322 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4323 return SDValue(N, 0);
4325 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4326 if (N1C && N0.getOpcode() == ISD::SHL) {
4327 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4328 uint64_t c1 = N0C1->getZExtValue();
4329 uint64_t c2 = N1C->getZExtValue();
4331 if (c1 + c2 >= OpSizeInBits)
4332 return DAG.getConstant(0, DL, VT);
4333 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4334 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4338 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4339 // For this to be valid, the second form must not preserve any of the bits
4340 // that are shifted out by the inner shift in the first form. This means
4341 // the outer shift size must be >= the number of bits added by the ext.
4342 // As a corollary, we don't care what kind of ext it is.
4343 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4344 N0.getOpcode() == ISD::ANY_EXTEND ||
4345 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4346 N0.getOperand(0).getOpcode() == ISD::SHL) {
4347 SDValue N0Op0 = N0.getOperand(0);
4348 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4349 uint64_t c1 = N0Op0C1->getZExtValue();
4350 uint64_t c2 = N1C->getZExtValue();
4351 EVT InnerShiftVT = N0Op0.getValueType();
4352 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4353 if (c2 >= OpSizeInBits - InnerShiftSize) {
4355 if (c1 + c2 >= OpSizeInBits)
4356 return DAG.getConstant(0, DL, VT);
4357 return DAG.getNode(ISD::SHL, DL, VT,
4358 DAG.getNode(N0.getOpcode(), DL, VT,
4359 N0Op0->getOperand(0)),
4360 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4365 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4366 // Only fold this if the inner zext has no other uses to avoid increasing
4367 // the total number of instructions.
4368 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4369 N0.getOperand(0).getOpcode() == ISD::SRL) {
4370 SDValue N0Op0 = N0.getOperand(0);
4371 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4372 uint64_t c1 = N0Op0C1->getZExtValue();
4373 if (c1 < VT.getScalarSizeInBits()) {
4374 uint64_t c2 = N1C->getZExtValue();
4376 SDValue NewOp0 = N0.getOperand(0);
4377 EVT CountVT = NewOp0.getOperand(1).getValueType();
4379 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4381 DAG.getConstant(c2, DL, CountVT));
4382 AddToWorklist(NewSHL.getNode());
4383 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4389 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
4390 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2
4391 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4392 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4393 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4394 uint64_t C1 = N0C1->getZExtValue();
4395 uint64_t C2 = N1C->getZExtValue();
4398 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4399 DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4400 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4401 DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4405 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4406 // (and (srl x, (sub c1, c2), MASK)
4407 // Only fold this if the inner shift has no other uses -- if it does, folding
4408 // this will increase the total number of instructions.
4409 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4410 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4411 uint64_t c1 = N0C1->getZExtValue();
4412 if (c1 < OpSizeInBits) {
4413 uint64_t c2 = N1C->getZExtValue();
4414 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4417 Mask = Mask.shl(c2 - c1);
4419 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4420 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4422 Mask = Mask.lshr(c1 - c2);
4424 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4425 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4428 return DAG.getNode(ISD::AND, DL, VT, Shift,
4429 DAG.getConstant(Mask, DL, VT));
4433 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4434 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4435 unsigned BitSize = VT.getScalarSizeInBits();
4437 SDValue HiBitsMask =
4438 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4439 BitSize - N1C->getZExtValue()),
4441 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4445 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4446 // Variant of version done on multiply, except mul by a power of 2 is turned
4449 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4450 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4451 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4452 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4453 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4454 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4457 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4458 if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4459 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4460 SDValue Folded = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C);
4461 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4465 if (N1C && !N1C->isOpaque())
4466 if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4472 SDValue DAGCombiner::visitSRA(SDNode *N) {
4473 SDValue N0 = N->getOperand(0);
4474 SDValue N1 = N->getOperand(1);
4475 EVT VT = N0.getValueType();
4476 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4479 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4480 if (VT.isVector()) {
4481 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4484 N1C = isConstOrConstSplat(N1);
4487 // fold (sra c1, c2) -> (sra c1, c2)
4488 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4489 if (N0C && N1C && !N1C->isOpaque())
4490 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4491 // fold (sra 0, x) -> 0
4492 if (isNullConstant(N0))
4494 // fold (sra -1, x) -> -1
4495 if (isAllOnesConstant(N0))
4497 // fold (sra x, (setge c, size(x))) -> undef
4498 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4499 return DAG.getUNDEF(VT);
4500 // fold (sra x, 0) -> x
4501 if (N1C && N1C->isNullValue())
4503 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4505 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4506 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4507 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4509 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4510 ExtVT, VT.getVectorNumElements());
4511 if ((!LegalOperations ||
4512 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4513 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4514 N0.getOperand(0), DAG.getValueType(ExtVT));
4517 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4518 if (N1C && N0.getOpcode() == ISD::SRA) {
4519 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4520 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4521 if (Sum >= OpSizeInBits)
4522 Sum = OpSizeInBits - 1;
4524 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4525 DAG.getConstant(Sum, DL, N1.getValueType()));
4529 // fold (sra (shl X, m), (sub result_size, n))
4530 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4531 // result_size - n != m.
4532 // If truncate is free for the target sext(shl) is likely to result in better
4534 if (N0.getOpcode() == ISD::SHL && N1C) {
4535 // Get the two constanst of the shifts, CN0 = m, CN = n.
4536 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4538 LLVMContext &Ctx = *DAG.getContext();
4539 // Determine what the truncate's result bitsize and type would be.
4540 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4543 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4545 // Determine the residual right-shift amount.
4546 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4548 // If the shift is not a no-op (in which case this should be just a sign
4549 // extend already), the truncated to type is legal, sign_extend is legal
4550 // on that type, and the truncate to that type is both legal and free,
4551 // perform the transform.
4552 if ((ShiftAmt > 0) &&
4553 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4554 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4555 TLI.isTruncateFree(VT, TruncVT)) {
4558 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4559 getShiftAmountTy(N0.getOperand(0).getValueType()));
4560 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4561 N0.getOperand(0), Amt);
4562 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4564 return DAG.getNode(ISD::SIGN_EXTEND, DL,
4565 N->getValueType(0), Trunc);
4570 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4571 if (N1.getOpcode() == ISD::TRUNCATE &&
4572 N1.getOperand(0).getOpcode() == ISD::AND) {
4573 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4574 if (NewOp1.getNode())
4575 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4578 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4579 // if c1 is equal to the number of bits the trunc removes
4580 if (N0.getOpcode() == ISD::TRUNCATE &&
4581 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4582 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4583 N0.getOperand(0).hasOneUse() &&
4584 N0.getOperand(0).getOperand(1).hasOneUse() &&
4586 SDValue N0Op0 = N0.getOperand(0);
4587 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4588 unsigned LargeShiftVal = LargeShift->getZExtValue();
4589 EVT LargeVT = N0Op0.getValueType();
4591 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4594 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4595 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4596 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4597 N0Op0.getOperand(0), Amt);
4598 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4603 // Simplify, based on bits shifted out of the LHS.
4604 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4605 return SDValue(N, 0);
4608 // If the sign bit is known to be zero, switch this to a SRL.
4609 if (DAG.SignBitIsZero(N0))
4610 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4612 if (N1C && !N1C->isOpaque())
4613 if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4619 SDValue DAGCombiner::visitSRL(SDNode *N) {
4620 SDValue N0 = N->getOperand(0);
4621 SDValue N1 = N->getOperand(1);
4622 EVT VT = N0.getValueType();
4623 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4626 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4627 if (VT.isVector()) {
4628 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4631 N1C = isConstOrConstSplat(N1);
4634 // fold (srl c1, c2) -> c1 >>u c2
4635 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4636 if (N0C && N1C && !N1C->isOpaque())
4637 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4638 // fold (srl 0, x) -> 0
4639 if (isNullConstant(N0))
4641 // fold (srl x, c >= size(x)) -> undef
4642 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4643 return DAG.getUNDEF(VT);
4644 // fold (srl x, 0) -> x
4645 if (N1C && N1C->isNullValue())
4647 // if (srl x, c) is known to be zero, return 0
4648 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4649 APInt::getAllOnesValue(OpSizeInBits)))
4650 return DAG.getConstant(0, SDLoc(N), VT);
4652 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4653 if (N1C && N0.getOpcode() == ISD::SRL) {
4654 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4655 uint64_t c1 = N01C->getZExtValue();
4656 uint64_t c2 = N1C->getZExtValue();
4658 if (c1 + c2 >= OpSizeInBits)
4659 return DAG.getConstant(0, DL, VT);
4660 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4661 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4665 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4666 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4667 N0.getOperand(0).getOpcode() == ISD::SRL &&
4668 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4670 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4671 uint64_t c2 = N1C->getZExtValue();
4672 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4673 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4674 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4675 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4676 if (c1 + OpSizeInBits == InnerShiftSize) {
4678 if (c1 + c2 >= InnerShiftSize)
4679 return DAG.getConstant(0, DL, VT);
4680 return DAG.getNode(ISD::TRUNCATE, DL, VT,
4681 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4682 N0.getOperand(0)->getOperand(0),
4683 DAG.getConstant(c1 + c2, DL,
4688 // fold (srl (shl x, c), c) -> (and x, cst2)
4689 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4690 unsigned BitSize = N0.getScalarValueSizeInBits();
4691 if (BitSize <= 64) {
4692 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4694 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4695 DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4699 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4700 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4701 // Shifting in all undef bits?
4702 EVT SmallVT = N0.getOperand(0).getValueType();
4703 unsigned BitSize = SmallVT.getScalarSizeInBits();
4704 if (N1C->getZExtValue() >= BitSize)
4705 return DAG.getUNDEF(VT);
4707 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4708 uint64_t ShiftAmt = N1C->getZExtValue();
4710 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4712 DAG.getConstant(ShiftAmt, DL0,
4713 getShiftAmountTy(SmallVT)));
4714 AddToWorklist(SmallShift.getNode());
4715 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4717 return DAG.getNode(ISD::AND, DL, VT,
4718 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4719 DAG.getConstant(Mask, DL, VT));
4723 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4724 // bit, which is unmodified by sra.
4725 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4726 if (N0.getOpcode() == ISD::SRA)
4727 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4730 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4731 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4732 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4733 APInt KnownZero, KnownOne;
4734 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4736 // If any of the input bits are KnownOne, then the input couldn't be all
4737 // zeros, thus the result of the srl will always be zero.
4738 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4740 // If all of the bits input the to ctlz node are known to be zero, then
4741 // the result of the ctlz is "32" and the result of the shift is one.
4742 APInt UnknownBits = ~KnownZero;
4743 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4745 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4746 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4747 // Okay, we know that only that the single bit specified by UnknownBits
4748 // could be set on input to the CTLZ node. If this bit is set, the SRL
4749 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4750 // to an SRL/XOR pair, which is likely to simplify more.
4751 unsigned ShAmt = UnknownBits.countTrailingZeros();
4752 SDValue Op = N0.getOperand(0);
4756 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4757 DAG.getConstant(ShAmt, DL,
4758 getShiftAmountTy(Op.getValueType())));
4759 AddToWorklist(Op.getNode());
4763 return DAG.getNode(ISD::XOR, DL, VT,
4764 Op, DAG.getConstant(1, DL, VT));
4768 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4769 if (N1.getOpcode() == ISD::TRUNCATE &&
4770 N1.getOperand(0).getOpcode() == ISD::AND) {
4771 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4772 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4775 // fold operands of srl based on knowledge that the low bits are not
4777 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4778 return SDValue(N, 0);
4780 if (N1C && !N1C->isOpaque())
4781 if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4784 // Attempt to convert a srl of a load into a narrower zero-extending load.
4785 if (SDValue NarrowLoad = ReduceLoadWidth(N))
4788 // Here is a common situation. We want to optimize:
4791 // %b = and i32 %a, 2
4792 // %c = srl i32 %b, 1
4793 // brcond i32 %c ...
4799 // %c = setcc eq %b, 0
4802 // However when after the source operand of SRL is optimized into AND, the SRL
4803 // itself may not be optimized further. Look for it and add the BRCOND into
4805 if (N->hasOneUse()) {
4806 SDNode *Use = *N->use_begin();
4807 if (Use->getOpcode() == ISD::BRCOND)
4809 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4810 // Also look pass the truncate.
4811 Use = *Use->use_begin();
4812 if (Use->getOpcode() == ISD::BRCOND)
4820 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4821 SDValue N0 = N->getOperand(0);
4822 EVT VT = N->getValueType(0);
4824 // fold (bswap c1) -> c2
4825 if (isConstantIntBuildVectorOrConstantInt(N0))
4826 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4827 // fold (bswap (bswap x)) -> x
4828 if (N0.getOpcode() == ISD::BSWAP)
4829 return N0->getOperand(0);
4833 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4834 SDValue N0 = N->getOperand(0);
4835 EVT VT = N->getValueType(0);
4837 // fold (ctlz c1) -> c2
4838 if (isConstantIntBuildVectorOrConstantInt(N0))
4839 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4843 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4844 SDValue N0 = N->getOperand(0);
4845 EVT VT = N->getValueType(0);
4847 // fold (ctlz_zero_undef c1) -> c2
4848 if (isConstantIntBuildVectorOrConstantInt(N0))
4849 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4853 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4854 SDValue N0 = N->getOperand(0);
4855 EVT VT = N->getValueType(0);
4857 // fold (cttz c1) -> c2
4858 if (isConstantIntBuildVectorOrConstantInt(N0))
4859 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4863 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4864 SDValue N0 = N->getOperand(0);
4865 EVT VT = N->getValueType(0);
4867 // fold (cttz_zero_undef c1) -> c2
4868 if (isConstantIntBuildVectorOrConstantInt(N0))
4869 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4873 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4874 SDValue N0 = N->getOperand(0);
4875 EVT VT = N->getValueType(0);
4877 // fold (ctpop c1) -> c2
4878 if (isConstantIntBuildVectorOrConstantInt(N0))
4879 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4884 /// \brief Generate Min/Max node
4885 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4886 SDValue True, SDValue False,
4887 ISD::CondCode CC, const TargetLowering &TLI,
4888 SelectionDAG &DAG) {
4889 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4899 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4900 if (TLI.isOperationLegal(Opcode, VT))
4901 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4910 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4911 if (TLI.isOperationLegal(Opcode, VT))
4912 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4920 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4921 SDValue N0 = N->getOperand(0);
4922 SDValue N1 = N->getOperand(1);
4923 SDValue N2 = N->getOperand(2);
4924 EVT VT = N->getValueType(0);
4925 EVT VT0 = N0.getValueType();
4927 // fold (select C, X, X) -> X
4930 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4931 // fold (select true, X, Y) -> X
4932 // fold (select false, X, Y) -> Y
4933 return !N0C->isNullValue() ? N1 : N2;
4935 // fold (select C, 1, X) -> (or C, X)
4936 if (VT == MVT::i1 && isOneConstant(N1))
4937 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4938 // fold (select C, 0, 1) -> (xor C, 1)
4939 // We can't do this reliably if integer based booleans have different contents
4940 // to floating point based booleans. This is because we can't tell whether we
4941 // have an integer-based boolean or a floating-point-based boolean unless we
4942 // can find the SETCC that produced it and inspect its operands. This is
4943 // fairly easy if C is the SETCC node, but it can potentially be
4944 // undiscoverable (or not reasonably discoverable). For example, it could be
4945 // in another basic block or it could require searching a complicated
4947 if (VT.isInteger() &&
4948 (VT0 == MVT::i1 || (VT0.isInteger() &&
4949 TLI.getBooleanContents(false, false) ==
4950 TLI.getBooleanContents(false, true) &&
4951 TLI.getBooleanContents(false, false) ==
4952 TargetLowering::ZeroOrOneBooleanContent)) &&
4953 isNullConstant(N1) && isOneConstant(N2)) {
4957 return DAG.getNode(ISD::XOR, DL, VT0,
4958 N0, DAG.getConstant(1, DL, VT0));
4961 XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4962 N0, DAG.getConstant(1, DL0, VT0));
4963 AddToWorklist(XORNode.getNode());
4965 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4966 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4968 // fold (select C, 0, X) -> (and (not C), X)
4969 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4970 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4971 AddToWorklist(NOTNode.getNode());
4972 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4974 // fold (select C, X, 1) -> (or (not C), X)
4975 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
4976 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4977 AddToWorklist(NOTNode.getNode());
4978 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4980 // fold (select C, X, 0) -> (and C, X)
4981 if (VT == MVT::i1 && isNullConstant(N2))
4982 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4983 // fold (select X, X, Y) -> (or X, Y)
4984 // fold (select X, 1, Y) -> (or X, Y)
4985 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
4986 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4987 // fold (select X, Y, X) -> (and X, Y)
4988 // fold (select X, Y, 0) -> (and X, Y)
4989 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
4990 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4992 // If we can fold this based on the true/false value, do so.
4993 if (SimplifySelectOps(N, N1, N2))
4994 return SDValue(N, 0); // Don't revisit N.
4996 if (VT0 == MVT::i1) {
4997 // The code in this block deals with the following 2 equivalences:
4998 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
4999 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5000 // The target can specify its prefered form with the
5001 // shouldNormalizeToSelectSequence() callback. However we always transform
5002 // to the right anyway if we find the inner select exists in the DAG anyway
5003 // and we always transform to the left side if we know that we can further
5004 // optimize the combination of the conditions.
5005 bool normalizeToSequence
5006 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5007 // select (and Cond0, Cond1), X, Y
5008 // -> select Cond0, (select Cond1, X, Y), Y
5009 if (N0->getOpcode() == ISD::AND && 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 if (normalizeToSequence || !InnerSelect.use_empty())
5015 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5018 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5019 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5020 SDValue Cond0 = N0->getOperand(0);
5021 SDValue Cond1 = N0->getOperand(1);
5022 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5023 N1.getValueType(), Cond1, N1, N2);
5024 if (normalizeToSequence || !InnerSelect.use_empty())
5025 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5029 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5030 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5031 SDValue N1_0 = N1->getOperand(0);
5032 SDValue N1_1 = N1->getOperand(1);
5033 SDValue N1_2 = N1->getOperand(2);
5034 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5035 // Create the actual and node if we can generate good code for it.
5036 if (!normalizeToSequence) {
5037 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5039 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5042 // Otherwise see if we can optimize the "and" to a better pattern.
5043 if (SDValue Combined = visitANDLike(N0, N1_0, N))
5044 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5048 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5049 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5050 SDValue N2_0 = N2->getOperand(0);
5051 SDValue N2_1 = N2->getOperand(1);
5052 SDValue N2_2 = N2->getOperand(2);
5053 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5054 // Create the actual or node if we can generate good code for it.
5055 if (!normalizeToSequence) {
5056 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5058 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5061 // Otherwise see if we can optimize to a better pattern.
5062 if (SDValue Combined = visitORLike(N0, N2_0, N))
5063 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5069 // fold selects based on a setcc into other things, such as min/max/abs
5070 if (N0.getOpcode() == ISD::SETCC) {
5071 // select x, y (fcmp lt x, y) -> fminnum x, y
5072 // select x, y (fcmp gt x, y) -> fmaxnum x, y
5074 // This is OK if we don't care about what happens if either operand is a
5078 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5079 // no signed zeros as well as no nans.
5080 const TargetOptions &Options = DAG.getTarget().Options;
5081 if (Options.UnsafeFPMath &&
5082 VT.isFloatingPoint() && N0.hasOneUse() &&
5083 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5084 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5086 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5087 N0.getOperand(1), N1, N2, CC,
5092 if ((!LegalOperations &&
5093 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5094 TLI.isOperationLegal(ISD::SELECT_CC, VT))
5095 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5096 N0.getOperand(0), N0.getOperand(1),
5097 N1, N2, N0.getOperand(2));
5098 return SimplifySelect(SDLoc(N), N0, N1, N2);
5105 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5108 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5110 // Split the inputs.
5111 SDValue Lo, Hi, LL, LH, RL, RH;
5112 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5113 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5115 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5116 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5118 return std::make_pair(Lo, Hi);
5121 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5122 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5123 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5125 SDValue Cond = N->getOperand(0);
5126 SDValue LHS = N->getOperand(1);
5127 SDValue RHS = N->getOperand(2);
5128 EVT VT = N->getValueType(0);
5129 int NumElems = VT.getVectorNumElements();
5130 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5131 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5132 Cond.getOpcode() == ISD::BUILD_VECTOR);
5134 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5135 // binary ones here.
5136 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5139 // We're sure we have an even number of elements due to the
5140 // concat_vectors we have as arguments to vselect.
5141 // Skip BV elements until we find one that's not an UNDEF
5142 // After we find an UNDEF element, keep looping until we get to half the
5143 // length of the BV and see if all the non-undef nodes are the same.
5144 ConstantSDNode *BottomHalf = nullptr;
5145 for (int i = 0; i < NumElems / 2; ++i) {
5146 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5149 if (BottomHalf == nullptr)
5150 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5151 else if (Cond->getOperand(i).getNode() != BottomHalf)
5155 // Do the same for the second half of the BuildVector
5156 ConstantSDNode *TopHalf = nullptr;
5157 for (int i = NumElems / 2; i < NumElems; ++i) {
5158 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5161 if (TopHalf == nullptr)
5162 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5163 else if (Cond->getOperand(i).getNode() != TopHalf)
5167 assert(TopHalf && BottomHalf &&
5168 "One half of the selector was all UNDEFs and the other was all the "
5169 "same value. This should have been addressed before this function.");
5171 ISD::CONCAT_VECTORS, dl, VT,
5172 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5173 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5176 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5178 if (Level >= AfterLegalizeTypes)
5181 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5182 SDValue Mask = MSC->getMask();
5183 SDValue Data = MSC->getValue();
5186 // If the MSCATTER data type requires splitting and the mask is provided by a
5187 // SETCC, then split both nodes and its operands before legalization. This
5188 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5189 // and enables future optimizations (e.g. min/max pattern matching on X86).
5190 if (Mask.getOpcode() != ISD::SETCC)
5193 // Check if any splitting is required.
5194 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5195 TargetLowering::TypeSplitVector)
5197 SDValue MaskLo, MaskHi, Lo, Hi;
5198 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5201 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5203 SDValue Chain = MSC->getChain();
5205 EVT MemoryVT = MSC->getMemoryVT();
5206 unsigned Alignment = MSC->getOriginalAlignment();
5208 EVT LoMemVT, HiMemVT;
5209 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5211 SDValue DataLo, DataHi;
5212 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5214 SDValue BasePtr = MSC->getBasePtr();
5215 SDValue IndexLo, IndexHi;
5216 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5218 MachineMemOperand *MMO = DAG.getMachineFunction().
5219 getMachineMemOperand(MSC->getPointerInfo(),
5220 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5221 Alignment, MSC->getAAInfo(), MSC->getRanges());
5223 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5224 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5227 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5228 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5231 AddToWorklist(Lo.getNode());
5232 AddToWorklist(Hi.getNode());
5234 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5237 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5239 if (Level >= AfterLegalizeTypes)
5242 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5243 SDValue Mask = MST->getMask();
5244 SDValue Data = MST->getValue();
5247 // If the MSTORE data type requires splitting and the mask is provided by a
5248 // SETCC, then split both nodes and its operands before legalization. This
5249 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5250 // and enables future optimizations (e.g. min/max pattern matching on X86).
5251 if (Mask.getOpcode() == ISD::SETCC) {
5253 // Check if any splitting is required.
5254 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5255 TargetLowering::TypeSplitVector)
5258 SDValue MaskLo, MaskHi, Lo, Hi;
5259 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5262 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5264 SDValue Chain = MST->getChain();
5265 SDValue Ptr = MST->getBasePtr();
5267 EVT MemoryVT = MST->getMemoryVT();
5268 unsigned Alignment = MST->getOriginalAlignment();
5270 // if Alignment is equal to the vector size,
5271 // take the half of it for the second part
5272 unsigned SecondHalfAlignment =
5273 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5274 Alignment/2 : Alignment;
5276 EVT LoMemVT, HiMemVT;
5277 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5279 SDValue DataLo, DataHi;
5280 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5282 MachineMemOperand *MMO = DAG.getMachineFunction().
5283 getMachineMemOperand(MST->getPointerInfo(),
5284 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5285 Alignment, MST->getAAInfo(), MST->getRanges());
5287 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5288 MST->isTruncatingStore());
5290 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5291 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5292 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5294 MMO = DAG.getMachineFunction().
5295 getMachineMemOperand(MST->getPointerInfo(),
5296 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5297 SecondHalfAlignment, MST->getAAInfo(),
5300 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5301 MST->isTruncatingStore());
5303 AddToWorklist(Lo.getNode());
5304 AddToWorklist(Hi.getNode());
5306 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5311 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5313 if (Level >= AfterLegalizeTypes)
5316 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5317 SDValue Mask = MGT->getMask();
5320 // If the MGATHER result requires splitting and the mask is provided by a
5321 // SETCC, then split both nodes and its operands before legalization. This
5322 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5323 // and enables future optimizations (e.g. min/max pattern matching on X86).
5325 if (Mask.getOpcode() != ISD::SETCC)
5328 EVT VT = N->getValueType(0);
5330 // Check if any splitting is required.
5331 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5332 TargetLowering::TypeSplitVector)
5335 SDValue MaskLo, MaskHi, Lo, Hi;
5336 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5338 SDValue Src0 = MGT->getValue();
5339 SDValue Src0Lo, Src0Hi;
5340 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5343 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5345 SDValue Chain = MGT->getChain();
5346 EVT MemoryVT = MGT->getMemoryVT();
5347 unsigned Alignment = MGT->getOriginalAlignment();
5349 EVT LoMemVT, HiMemVT;
5350 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5352 SDValue BasePtr = MGT->getBasePtr();
5353 SDValue Index = MGT->getIndex();
5354 SDValue IndexLo, IndexHi;
5355 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5357 MachineMemOperand *MMO = DAG.getMachineFunction().
5358 getMachineMemOperand(MGT->getPointerInfo(),
5359 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5360 Alignment, MGT->getAAInfo(), MGT->getRanges());
5362 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5363 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5366 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5367 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5370 AddToWorklist(Lo.getNode());
5371 AddToWorklist(Hi.getNode());
5373 // Build a factor node to remember that this load is independent of the
5375 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5378 // Legalized the chain result - switch anything that used the old chain to
5380 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5382 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5384 SDValue RetOps[] = { GatherRes, Chain };
5385 return DAG.getMergeValues(RetOps, DL);
5388 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5390 if (Level >= AfterLegalizeTypes)
5393 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5394 SDValue Mask = MLD->getMask();
5397 // If the MLOAD result requires splitting and the mask is provided by a
5398 // SETCC, then split both nodes and its operands before legalization. This
5399 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5400 // and enables future optimizations (e.g. min/max pattern matching on X86).
5402 if (Mask.getOpcode() == ISD::SETCC) {
5403 EVT VT = N->getValueType(0);
5405 // Check if any splitting is required.
5406 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5407 TargetLowering::TypeSplitVector)
5410 SDValue MaskLo, MaskHi, Lo, Hi;
5411 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5413 SDValue Src0 = MLD->getSrc0();
5414 SDValue Src0Lo, Src0Hi;
5415 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5418 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5420 SDValue Chain = MLD->getChain();
5421 SDValue Ptr = MLD->getBasePtr();
5422 EVT MemoryVT = MLD->getMemoryVT();
5423 unsigned Alignment = MLD->getOriginalAlignment();
5425 // if Alignment is equal to the vector size,
5426 // take the half of it for the second part
5427 unsigned SecondHalfAlignment =
5428 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5429 Alignment/2 : Alignment;
5431 EVT LoMemVT, HiMemVT;
5432 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5434 MachineMemOperand *MMO = DAG.getMachineFunction().
5435 getMachineMemOperand(MLD->getPointerInfo(),
5436 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5437 Alignment, MLD->getAAInfo(), MLD->getRanges());
5439 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5442 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5443 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5444 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5446 MMO = DAG.getMachineFunction().
5447 getMachineMemOperand(MLD->getPointerInfo(),
5448 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5449 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5451 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5454 AddToWorklist(Lo.getNode());
5455 AddToWorklist(Hi.getNode());
5457 // Build a factor node to remember that this load is independent of the
5459 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5462 // Legalized the chain result - switch anything that used the old chain to
5464 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5466 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5468 SDValue RetOps[] = { LoadRes, Chain };
5469 return DAG.getMergeValues(RetOps, DL);
5474 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5475 SDValue N0 = N->getOperand(0);
5476 SDValue N1 = N->getOperand(1);
5477 SDValue N2 = N->getOperand(2);
5480 // Canonicalize integer abs.
5481 // vselect (setg[te] X, 0), X, -X ->
5482 // vselect (setgt X, -1), X, -X ->
5483 // vselect (setl[te] X, 0), -X, X ->
5484 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5485 if (N0.getOpcode() == ISD::SETCC) {
5486 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5487 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5489 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5491 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5492 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5493 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5494 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5495 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5496 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5497 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5500 EVT VT = LHS.getValueType();
5501 SDValue Shift = DAG.getNode(
5502 ISD::SRA, DL, VT, LHS,
5503 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5504 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5505 AddToWorklist(Shift.getNode());
5506 AddToWorklist(Add.getNode());
5507 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5511 if (SimplifySelectOps(N, N1, N2))
5512 return SDValue(N, 0); // Don't revisit N.
5514 // If the VSELECT result requires splitting and the mask is provided by a
5515 // SETCC, then split both nodes and its operands before legalization. This
5516 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5517 // and enables future optimizations (e.g. min/max pattern matching on X86).
5518 if (N0.getOpcode() == ISD::SETCC) {
5519 EVT VT = N->getValueType(0);
5521 // Check if any splitting is required.
5522 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5523 TargetLowering::TypeSplitVector)
5526 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5527 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5528 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5529 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5531 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5532 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5534 // Add the new VSELECT nodes to the work list in case they need to be split
5536 AddToWorklist(Lo.getNode());
5537 AddToWorklist(Hi.getNode());
5539 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5542 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5543 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5545 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5546 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5549 // The ConvertSelectToConcatVector function is assuming both the above
5550 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5552 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5553 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5554 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5555 if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5562 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5563 SDValue N0 = N->getOperand(0);
5564 SDValue N1 = N->getOperand(1);
5565 SDValue N2 = N->getOperand(2);
5566 SDValue N3 = N->getOperand(3);
5567 SDValue N4 = N->getOperand(4);
5568 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5570 // fold select_cc lhs, rhs, x, x, cc -> x
5574 // Determine if the condition we're dealing with is constant
5575 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5576 N0, N1, CC, SDLoc(N), false);
5577 if (SCC.getNode()) {
5578 AddToWorklist(SCC.getNode());
5580 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5581 if (!SCCC->isNullValue())
5582 return N2; // cond always true -> true val
5584 return N3; // cond always false -> false val
5585 } else if (SCC->getOpcode() == ISD::UNDEF) {
5586 // When the condition is UNDEF, just return the first operand. This is
5587 // coherent the DAG creation, no setcc node is created in this case
5589 } else if (SCC.getOpcode() == ISD::SETCC) {
5590 // Fold to a simpler select_cc
5591 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5592 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5597 // If we can fold this based on the true/false value, do so.
5598 if (SimplifySelectOps(N, N2, N3))
5599 return SDValue(N, 0); // Don't revisit N.
5601 // fold select_cc into other things, such as min/max/abs
5602 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5605 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5606 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5607 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5611 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5612 /// a build_vector of constants.
5613 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5614 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5615 /// Vector extends are not folded if operations are legal; this is to
5616 /// avoid introducing illegal build_vector dag nodes.
5617 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5618 SelectionDAG &DAG, bool LegalTypes,
5619 bool LegalOperations) {
5620 unsigned Opcode = N->getOpcode();
5621 SDValue N0 = N->getOperand(0);
5622 EVT VT = N->getValueType(0);
5624 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5625 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5626 && "Expected EXTEND dag node in input!");
5628 // fold (sext c1) -> c1
5629 // fold (zext c1) -> c1
5630 // fold (aext c1) -> c1
5631 if (isa<ConstantSDNode>(N0))
5632 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5634 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5635 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5636 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5637 EVT SVT = VT.getScalarType();
5638 if (!(VT.isVector() &&
5639 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5640 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5643 // We can fold this node into a build_vector.
5644 unsigned VTBits = SVT.getSizeInBits();
5645 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5646 SmallVector<SDValue, 8> Elts;
5647 unsigned NumElts = VT.getVectorNumElements();
5650 for (unsigned i=0; i != NumElts; ++i) {
5651 SDValue Op = N0->getOperand(i);
5652 if (Op->getOpcode() == ISD::UNDEF) {
5653 Elts.push_back(DAG.getUNDEF(SVT));
5658 // Get the constant value and if needed trunc it to the size of the type.
5659 // Nodes like build_vector might have constants wider than the scalar type.
5660 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5661 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5662 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5664 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5667 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5670 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5671 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5672 // transformation. Returns true if extension are possible and the above
5673 // mentioned transformation is profitable.
5674 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5676 SmallVectorImpl<SDNode *> &ExtendNodes,
5677 const TargetLowering &TLI) {
5678 bool HasCopyToRegUses = false;
5679 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5680 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5681 UE = N0.getNode()->use_end();
5686 if (UI.getUse().getResNo() != N0.getResNo())
5688 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5689 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5690 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5691 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5692 // Sign bits will be lost after a zext.
5695 for (unsigned i = 0; i != 2; ++i) {
5696 SDValue UseOp = User->getOperand(i);
5699 if (!isa<ConstantSDNode>(UseOp))
5704 ExtendNodes.push_back(User);
5707 // If truncates aren't free and there are users we can't
5708 // extend, it isn't worthwhile.
5711 // Remember if this value is live-out.
5712 if (User->getOpcode() == ISD::CopyToReg)
5713 HasCopyToRegUses = true;
5716 if (HasCopyToRegUses) {
5717 bool BothLiveOut = false;
5718 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5720 SDUse &Use = UI.getUse();
5721 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5727 // Both unextended and extended values are live out. There had better be
5728 // a good reason for the transformation.
5729 return ExtendNodes.size();
5734 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5735 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5736 ISD::NodeType ExtType) {
5737 // Extend SetCC uses if necessary.
5738 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5739 SDNode *SetCC = SetCCs[i];
5740 SmallVector<SDValue, 4> Ops;
5742 for (unsigned j = 0; j != 2; ++j) {
5743 SDValue SOp = SetCC->getOperand(j);
5745 Ops.push_back(ExtLoad);
5747 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5750 Ops.push_back(SetCC->getOperand(2));
5751 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5755 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5756 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5757 SDValue N0 = N->getOperand(0);
5758 EVT DstVT = N->getValueType(0);
5759 EVT SrcVT = N0.getValueType();
5761 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5762 N->getOpcode() == ISD::ZERO_EXTEND) &&
5763 "Unexpected node type (not an extend)!");
5765 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5766 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5767 // (v8i32 (sext (v8i16 (load x))))
5769 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5770 // (v4i32 (sextload (x + 16)))))
5771 // Where uses of the original load, i.e.:
5773 // are replaced with:
5775 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5776 // (v4i32 (sextload (x + 16)))))))
5778 // This combine is only applicable to illegal, but splittable, vectors.
5779 // All legal types, and illegal non-vector types, are handled elsewhere.
5780 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5782 if (N0->getOpcode() != ISD::LOAD)
5785 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5787 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5788 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5789 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5792 SmallVector<SDNode *, 4> SetCCs;
5793 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5796 ISD::LoadExtType ExtType =
5797 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5799 // Try to split the vector types to get down to legal types.
5800 EVT SplitSrcVT = SrcVT;
5801 EVT SplitDstVT = DstVT;
5802 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5803 SplitSrcVT.getVectorNumElements() > 1) {
5804 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5805 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5808 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5812 const unsigned NumSplits =
5813 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5814 const unsigned Stride = SplitSrcVT.getStoreSize();
5815 SmallVector<SDValue, 4> Loads;
5816 SmallVector<SDValue, 4> Chains;
5818 SDValue BasePtr = LN0->getBasePtr();
5819 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5820 const unsigned Offset = Idx * Stride;
5821 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5823 SDValue SplitLoad = DAG.getExtLoad(
5824 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5825 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5826 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5827 Align, LN0->getAAInfo());
5829 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5830 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5832 Loads.push_back(SplitLoad.getValue(0));
5833 Chains.push_back(SplitLoad.getValue(1));
5836 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5837 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5839 CombineTo(N, NewValue);
5841 // Replace uses of the original load (before extension)
5842 // with a truncate of the concatenated sextloaded vectors.
5844 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5845 CombineTo(N0.getNode(), Trunc, NewChain);
5846 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5847 (ISD::NodeType)N->getOpcode());
5848 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5851 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5852 SDValue N0 = N->getOperand(0);
5853 EVT VT = N->getValueType(0);
5855 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5857 return SDValue(Res, 0);
5859 // fold (sext (sext x)) -> (sext x)
5860 // fold (sext (aext x)) -> (sext x)
5861 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5862 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5865 if (N0.getOpcode() == ISD::TRUNCATE) {
5866 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5867 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5868 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
5869 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5870 if (NarrowLoad.getNode() != N0.getNode()) {
5871 CombineTo(N0.getNode(), NarrowLoad);
5872 // CombineTo deleted the truncate, if needed, but not what's under it.
5875 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5878 // See if the value being truncated is already sign extended. If so, just
5879 // eliminate the trunc/sext pair.
5880 SDValue Op = N0.getOperand(0);
5881 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5882 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5883 unsigned DestBits = VT.getScalarType().getSizeInBits();
5884 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5886 if (OpBits == DestBits) {
5887 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5888 // bits, it is already ready.
5889 if (NumSignBits > DestBits-MidBits)
5891 } else if (OpBits < DestBits) {
5892 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5893 // bits, just sext from i32.
5894 if (NumSignBits > OpBits-MidBits)
5895 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5897 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5898 // bits, just truncate to i32.
5899 if (NumSignBits > OpBits-MidBits)
5900 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5903 // fold (sext (truncate x)) -> (sextinreg x).
5904 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5905 N0.getValueType())) {
5906 if (OpBits < DestBits)
5907 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5908 else if (OpBits > DestBits)
5909 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5910 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5911 DAG.getValueType(N0.getValueType()));
5915 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5916 // Only generate vector extloads when 1) they're legal, and 2) they are
5917 // deemed desirable by the target.
5918 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5919 ((!LegalOperations && !VT.isVector() &&
5920 !cast<LoadSDNode>(N0)->isVolatile()) ||
5921 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5922 bool DoXform = true;
5923 SmallVector<SDNode*, 4> SetCCs;
5924 if (!N0.hasOneUse())
5925 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5927 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5929 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5930 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5932 LN0->getBasePtr(), N0.getValueType(),
5933 LN0->getMemOperand());
5934 CombineTo(N, ExtLoad);
5935 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5936 N0.getValueType(), ExtLoad);
5937 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5938 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5940 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5944 // fold (sext (load x)) to multiple smaller sextloads.
5945 // Only on illegal but splittable vectors.
5946 if (SDValue ExtLoad = CombineExtLoad(N))
5949 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5950 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5951 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5952 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5953 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5954 EVT MemVT = LN0->getMemoryVT();
5955 if ((!LegalOperations && !LN0->isVolatile()) ||
5956 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5957 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5959 LN0->getBasePtr(), MemVT,
5960 LN0->getMemOperand());
5961 CombineTo(N, ExtLoad);
5962 CombineTo(N0.getNode(),
5963 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5964 N0.getValueType(), ExtLoad),
5965 ExtLoad.getValue(1));
5966 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5970 // fold (sext (and/or/xor (load x), cst)) ->
5971 // (and/or/xor (sextload x), (sext cst))
5972 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5973 N0.getOpcode() == ISD::XOR) &&
5974 isa<LoadSDNode>(N0.getOperand(0)) &&
5975 N0.getOperand(1).getOpcode() == ISD::Constant &&
5976 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5977 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5978 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5979 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5980 bool DoXform = true;
5981 SmallVector<SDNode*, 4> SetCCs;
5982 if (!N0.hasOneUse())
5983 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5986 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5987 LN0->getChain(), LN0->getBasePtr(),
5989 LN0->getMemOperand());
5990 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5991 Mask = Mask.sext(VT.getSizeInBits());
5993 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5994 ExtLoad, DAG.getConstant(Mask, DL, VT));
5995 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5996 SDLoc(N0.getOperand(0)),
5997 N0.getOperand(0).getValueType(), ExtLoad);
5999 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6000 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6002 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6007 if (N0.getOpcode() == ISD::SETCC) {
6008 EVT N0VT = N0.getOperand(0).getValueType();
6009 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6010 // Only do this before legalize for now.
6011 if (VT.isVector() && !LegalOperations &&
6012 TLI.getBooleanContents(N0VT) ==
6013 TargetLowering::ZeroOrNegativeOneBooleanContent) {
6014 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6015 // of the same size as the compared operands. Only optimize sext(setcc())
6016 // if this is the case.
6017 EVT SVT = getSetCCResultType(N0VT);
6019 // We know that the # elements of the results is the same as the
6020 // # elements of the compare (and the # elements of the compare result
6021 // for that matter). Check to see that they are the same size. If so,
6022 // we know that the element size of the sext'd result matches the
6023 // element size of the compare operands.
6024 if (VT.getSizeInBits() == SVT.getSizeInBits())
6025 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6027 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6029 // If the desired elements are smaller or larger than the source
6030 // elements we can use a matching integer vector type and then
6031 // truncate/sign extend
6032 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6033 if (SVT == MatchingVectorType) {
6034 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6035 N0.getOperand(0), N0.getOperand(1),
6036 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6037 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6041 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6042 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6045 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6047 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6048 NegOne, DAG.getConstant(0, DL, VT),
6049 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6050 if (SCC.getNode()) return SCC;
6052 if (!VT.isVector()) {
6053 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6054 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
6056 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6057 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6058 N0.getOperand(0), N0.getOperand(1), CC);
6059 return DAG.getSelect(DL, VT, SetCC,
6060 NegOne, DAG.getConstant(0, DL, VT));
6065 // fold (sext x) -> (zext x) if the sign bit is known zero.
6066 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6067 DAG.SignBitIsZero(N0))
6068 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6073 // isTruncateOf - If N is a truncate of some other value, return true, record
6074 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6075 // This function computes KnownZero to avoid a duplicated call to
6076 // computeKnownBits in the caller.
6077 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6080 if (N->getOpcode() == ISD::TRUNCATE) {
6081 Op = N->getOperand(0);
6082 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6086 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6087 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6090 SDValue Op0 = N->getOperand(0);
6091 SDValue Op1 = N->getOperand(1);
6092 assert(Op0.getValueType() == Op1.getValueType());
6094 if (isNullConstant(Op0))
6096 else if (isNullConstant(Op1))
6101 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6103 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6109 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6110 SDValue N0 = N->getOperand(0);
6111 EVT VT = N->getValueType(0);
6113 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6115 return SDValue(Res, 0);
6117 // fold (zext (zext x)) -> (zext x)
6118 // fold (zext (aext x)) -> (zext x)
6119 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6120 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6123 // fold (zext (truncate x)) -> (zext x) or
6124 // (zext (truncate x)) -> (truncate x)
6125 // This is valid when the truncated bits of x are already zero.
6126 // FIXME: We should extend this to work for vectors too.
6129 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6130 APInt TruncatedBits =
6131 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6132 APInt(Op.getValueSizeInBits(), 0) :
6133 APInt::getBitsSet(Op.getValueSizeInBits(),
6134 N0.getValueSizeInBits(),
6135 std::min(Op.getValueSizeInBits(),
6136 VT.getSizeInBits()));
6137 if (TruncatedBits == (KnownZero & TruncatedBits)) {
6138 if (VT.bitsGT(Op.getValueType()))
6139 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6140 if (VT.bitsLT(Op.getValueType()))
6141 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6147 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6148 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6149 if (N0.getOpcode() == ISD::TRUNCATE) {
6150 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6151 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6152 if (NarrowLoad.getNode() != N0.getNode()) {
6153 CombineTo(N0.getNode(), NarrowLoad);
6154 // CombineTo deleted the truncate, if needed, but not what's under it.
6157 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6161 // fold (zext (truncate x)) -> (and x, mask)
6162 if (N0.getOpcode() == ISD::TRUNCATE) {
6163 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6164 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6165 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6166 SDNode *oye = N0.getNode()->getOperand(0).getNode();
6167 if (NarrowLoad.getNode() != N0.getNode()) {
6168 CombineTo(N0.getNode(), NarrowLoad);
6169 // CombineTo deleted the truncate, if needed, but not what's under it.
6172 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6175 EVT SrcVT = N0.getOperand(0).getValueType();
6176 EVT MinVT = N0.getValueType();
6178 // Try to mask before the extension to avoid having to generate a larger mask,
6179 // possibly over several sub-vectors.
6180 if (SrcVT.bitsLT(VT)) {
6181 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6182 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6183 SDValue Op = N0.getOperand(0);
6184 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6185 AddToWorklist(Op.getNode());
6186 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6190 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6191 SDValue Op = N0.getOperand(0);
6192 if (SrcVT.bitsLT(VT)) {
6193 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6194 AddToWorklist(Op.getNode());
6195 } else if (SrcVT.bitsGT(VT)) {
6196 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6197 AddToWorklist(Op.getNode());
6199 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6203 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6204 // if either of the casts is not free.
6205 if (N0.getOpcode() == ISD::AND &&
6206 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6207 N0.getOperand(1).getOpcode() == ISD::Constant &&
6208 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6209 N0.getValueType()) ||
6210 !TLI.isZExtFree(N0.getValueType(), VT))) {
6211 SDValue X = N0.getOperand(0).getOperand(0);
6212 if (X.getValueType().bitsLT(VT)) {
6213 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6214 } else if (X.getValueType().bitsGT(VT)) {
6215 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6217 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6218 Mask = Mask.zext(VT.getSizeInBits());
6220 return DAG.getNode(ISD::AND, DL, VT,
6221 X, DAG.getConstant(Mask, DL, VT));
6224 // fold (zext (load x)) -> (zext (truncate (zextload x)))
6225 // Only generate vector extloads when 1) they're legal, and 2) they are
6226 // deemed desirable by the target.
6227 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6228 ((!LegalOperations && !VT.isVector() &&
6229 !cast<LoadSDNode>(N0)->isVolatile()) ||
6230 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6231 bool DoXform = true;
6232 SmallVector<SDNode*, 4> SetCCs;
6233 if (!N0.hasOneUse())
6234 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6236 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6238 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6239 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6241 LN0->getBasePtr(), N0.getValueType(),
6242 LN0->getMemOperand());
6243 CombineTo(N, ExtLoad);
6244 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6245 N0.getValueType(), ExtLoad);
6246 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6248 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6250 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6254 // fold (zext (load x)) to multiple smaller zextloads.
6255 // Only on illegal but splittable vectors.
6256 if (SDValue ExtLoad = CombineExtLoad(N))
6259 // fold (zext (and/or/xor (load x), cst)) ->
6260 // (and/or/xor (zextload x), (zext cst))
6261 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6262 N0.getOpcode() == ISD::XOR) &&
6263 isa<LoadSDNode>(N0.getOperand(0)) &&
6264 N0.getOperand(1).getOpcode() == ISD::Constant &&
6265 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6266 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6267 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6268 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6269 bool DoXform = true;
6270 SmallVector<SDNode*, 4> SetCCs;
6271 if (!N0.hasOneUse())
6272 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6275 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6276 LN0->getChain(), LN0->getBasePtr(),
6278 LN0->getMemOperand());
6279 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6280 Mask = Mask.zext(VT.getSizeInBits());
6282 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6283 ExtLoad, DAG.getConstant(Mask, DL, VT));
6284 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6285 SDLoc(N0.getOperand(0)),
6286 N0.getOperand(0).getValueType(), ExtLoad);
6288 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6289 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6291 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6296 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6297 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6298 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6299 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6300 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6301 EVT MemVT = LN0->getMemoryVT();
6302 if ((!LegalOperations && !LN0->isVolatile()) ||
6303 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6304 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6306 LN0->getBasePtr(), MemVT,
6307 LN0->getMemOperand());
6308 CombineTo(N, ExtLoad);
6309 CombineTo(N0.getNode(),
6310 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6312 ExtLoad.getValue(1));
6313 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6317 if (N0.getOpcode() == ISD::SETCC) {
6318 if (!LegalOperations && VT.isVector() &&
6319 N0.getValueType().getVectorElementType() == MVT::i1) {
6320 EVT N0VT = N0.getOperand(0).getValueType();
6321 if (getSetCCResultType(N0VT) == N0.getValueType())
6324 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6325 // Only do this before legalize for now.
6326 EVT EltVT = VT.getVectorElementType();
6328 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6329 DAG.getConstant(1, DL, EltVT));
6330 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6331 // We know that the # elements of the results is the same as the
6332 // # elements of the compare (and the # elements of the compare result
6333 // for that matter). Check to see that they are the same size. If so,
6334 // we know that the element size of the sext'd result matches the
6335 // element size of the compare operands.
6336 return DAG.getNode(ISD::AND, DL, VT,
6337 DAG.getSetCC(DL, VT, N0.getOperand(0),
6339 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6340 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6343 // If the desired elements are smaller or larger than the source
6344 // elements we can use a matching integer vector type and then
6345 // truncate/sign extend
6346 EVT MatchingElementType =
6347 EVT::getIntegerVT(*DAG.getContext(),
6348 N0VT.getScalarType().getSizeInBits());
6349 EVT MatchingVectorType =
6350 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6351 N0VT.getVectorNumElements());
6353 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6355 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6356 return DAG.getNode(ISD::AND, DL, VT,
6357 DAG.getSExtOrTrunc(VsetCC, DL, VT),
6358 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6361 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6364 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6365 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6366 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6367 if (SCC.getNode()) return SCC;
6370 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6371 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6372 isa<ConstantSDNode>(N0.getOperand(1)) &&
6373 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6375 SDValue ShAmt = N0.getOperand(1);
6376 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6377 if (N0.getOpcode() == ISD::SHL) {
6378 SDValue InnerZExt = N0.getOperand(0);
6379 // If the original shl may be shifting out bits, do not perform this
6381 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6382 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6383 if (ShAmtVal > KnownZeroBits)
6389 // Ensure that the shift amount is wide enough for the shifted value.
6390 if (VT.getSizeInBits() >= 256)
6391 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6393 return DAG.getNode(N0.getOpcode(), DL, VT,
6394 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6401 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6402 SDValue N0 = N->getOperand(0);
6403 EVT VT = N->getValueType(0);
6405 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6407 return SDValue(Res, 0);
6409 // fold (aext (aext x)) -> (aext x)
6410 // fold (aext (zext x)) -> (zext x)
6411 // fold (aext (sext x)) -> (sext x)
6412 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6413 N0.getOpcode() == ISD::ZERO_EXTEND ||
6414 N0.getOpcode() == ISD::SIGN_EXTEND)
6415 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6417 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6418 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6419 if (N0.getOpcode() == ISD::TRUNCATE) {
6420 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6421 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6422 if (NarrowLoad.getNode() != N0.getNode()) {
6423 CombineTo(N0.getNode(), NarrowLoad);
6424 // CombineTo deleted the truncate, if needed, but not what's under it.
6427 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6431 // fold (aext (truncate x))
6432 if (N0.getOpcode() == ISD::TRUNCATE) {
6433 SDValue TruncOp = N0.getOperand(0);
6434 if (TruncOp.getValueType() == VT)
6435 return TruncOp; // x iff x size == zext size.
6436 if (TruncOp.getValueType().bitsGT(VT))
6437 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6438 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6441 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6442 // if the trunc is not free.
6443 if (N0.getOpcode() == ISD::AND &&
6444 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6445 N0.getOperand(1).getOpcode() == ISD::Constant &&
6446 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6447 N0.getValueType())) {
6448 SDValue X = N0.getOperand(0).getOperand(0);
6449 if (X.getValueType().bitsLT(VT)) {
6450 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6451 } else if (X.getValueType().bitsGT(VT)) {
6452 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6454 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6455 Mask = Mask.zext(VT.getSizeInBits());
6457 return DAG.getNode(ISD::AND, DL, VT,
6458 X, DAG.getConstant(Mask, DL, VT));
6461 // fold (aext (load x)) -> (aext (truncate (extload x)))
6462 // None of the supported targets knows how to perform load and any_ext
6463 // on vectors in one instruction. We only perform this transformation on
6465 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6466 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6467 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6468 bool DoXform = true;
6469 SmallVector<SDNode*, 4> SetCCs;
6470 if (!N0.hasOneUse())
6471 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6473 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6474 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6476 LN0->getBasePtr(), N0.getValueType(),
6477 LN0->getMemOperand());
6478 CombineTo(N, ExtLoad);
6479 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6480 N0.getValueType(), ExtLoad);
6481 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6482 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6484 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6488 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6489 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6490 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6491 if (N0.getOpcode() == ISD::LOAD &&
6492 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6494 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6495 ISD::LoadExtType ExtType = LN0->getExtensionType();
6496 EVT MemVT = LN0->getMemoryVT();
6497 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6498 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6499 VT, LN0->getChain(), LN0->getBasePtr(),
6500 MemVT, LN0->getMemOperand());
6501 CombineTo(N, ExtLoad);
6502 CombineTo(N0.getNode(),
6503 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6504 N0.getValueType(), ExtLoad),
6505 ExtLoad.getValue(1));
6506 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6510 if (N0.getOpcode() == ISD::SETCC) {
6512 // aext(setcc) -> vsetcc
6513 // aext(setcc) -> truncate(vsetcc)
6514 // aext(setcc) -> aext(vsetcc)
6515 // Only do this before legalize for now.
6516 if (VT.isVector() && !LegalOperations) {
6517 EVT N0VT = N0.getOperand(0).getValueType();
6518 // We know that the # elements of the results is the same as the
6519 // # elements of the compare (and the # elements of the compare result
6520 // for that matter). Check to see that they are the same size. If so,
6521 // we know that the element size of the sext'd result matches the
6522 // element size of the compare operands.
6523 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6524 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6526 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6527 // If the desired elements are smaller or larger than the source
6528 // elements we can use a matching integer vector type and then
6529 // truncate/any extend
6531 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6533 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6535 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6536 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6540 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6543 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6544 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6545 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6553 /// See if the specified operand can be simplified with the knowledge that only
6554 /// the bits specified by Mask are used. If so, return the simpler operand,
6555 /// otherwise return a null SDValue.
6556 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6557 switch (V.getOpcode()) {
6559 case ISD::Constant: {
6560 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6561 assert(CV && "Const value should be ConstSDNode.");
6562 const APInt &CVal = CV->getAPIntValue();
6563 APInt NewVal = CVal & Mask;
6565 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6570 // If the LHS or RHS don't contribute bits to the or, drop them.
6571 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6572 return V.getOperand(1);
6573 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6574 return V.getOperand(0);
6577 // Only look at single-use SRLs.
6578 if (!V.getNode()->hasOneUse())
6580 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6581 // See if we can recursively simplify the LHS.
6582 unsigned Amt = RHSC->getZExtValue();
6584 // Watch out for shift count overflow though.
6585 if (Amt >= Mask.getBitWidth()) break;
6586 APInt NewMask = Mask << Amt;
6587 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6588 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6589 SimplifyLHS, V.getOperand(1));
6595 /// If the result of a wider load is shifted to right of N bits and then
6596 /// truncated to a narrower type and where N is a multiple of number of bits of
6597 /// the narrower type, transform it to a narrower load from address + N / num of
6598 /// bits of new type. If the result is to be extended, also fold the extension
6599 /// to form a extending load.
6600 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6601 unsigned Opc = N->getOpcode();
6603 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6604 SDValue N0 = N->getOperand(0);
6605 EVT VT = N->getValueType(0);
6608 // This transformation isn't valid for vector loads.
6612 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6614 if (Opc == ISD::SIGN_EXTEND_INREG) {
6615 ExtType = ISD::SEXTLOAD;
6616 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6617 } else if (Opc == ISD::SRL) {
6618 // Another special-case: SRL is basically zero-extending a narrower value.
6619 ExtType = ISD::ZEXTLOAD;
6621 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6622 if (!N01) return SDValue();
6623 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6624 VT.getSizeInBits() - N01->getZExtValue());
6626 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6629 unsigned EVTBits = ExtVT.getSizeInBits();
6631 // Do not generate loads of non-round integer types since these can
6632 // be expensive (and would be wrong if the type is not byte sized).
6633 if (!ExtVT.isRound())
6637 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6638 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6639 ShAmt = N01->getZExtValue();
6640 // Is the shift amount a multiple of size of VT?
6641 if ((ShAmt & (EVTBits-1)) == 0) {
6642 N0 = N0.getOperand(0);
6643 // Is the load width a multiple of size of VT?
6644 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6648 // At this point, we must have a load or else we can't do the transform.
6649 if (!isa<LoadSDNode>(N0)) return SDValue();
6651 // Because a SRL must be assumed to *need* to zero-extend the high bits
6652 // (as opposed to anyext the high bits), we can't combine the zextload
6653 // lowering of SRL and an sextload.
6654 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6657 // If the shift amount is larger than the input type then we're not
6658 // accessing any of the loaded bytes. If the load was a zextload/extload
6659 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6660 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6665 // If the load is shifted left (and the result isn't shifted back right),
6666 // we can fold the truncate through the shift.
6667 unsigned ShLeftAmt = 0;
6668 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6669 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6670 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6671 ShLeftAmt = N01->getZExtValue();
6672 N0 = N0.getOperand(0);
6676 // If we haven't found a load, we can't narrow it. Don't transform one with
6677 // multiple uses, this would require adding a new load.
6678 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6681 // Don't change the width of a volatile load.
6682 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6683 if (LN0->isVolatile())
6686 // Verify that we are actually reducing a load width here.
6687 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6690 // For the transform to be legal, the load must produce only two values
6691 // (the value loaded and the chain). Don't transform a pre-increment
6692 // load, for example, which produces an extra value. Otherwise the
6693 // transformation is not equivalent, and the downstream logic to replace
6694 // uses gets things wrong.
6695 if (LN0->getNumValues() > 2)
6698 // If the load that we're shrinking is an extload and we're not just
6699 // discarding the extension we can't simply shrink the load. Bail.
6700 // TODO: It would be possible to merge the extensions in some cases.
6701 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6702 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6705 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6708 EVT PtrType = N0.getOperand(1).getValueType();
6710 if (PtrType == MVT::Untyped || PtrType.isExtended())
6711 // It's not possible to generate a constant of extended or untyped type.
6714 // For big endian targets, we need to adjust the offset to the pointer to
6715 // load the correct bytes.
6716 if (DAG.getDataLayout().isBigEndian()) {
6717 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6718 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6719 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6722 uint64_t PtrOff = ShAmt / 8;
6723 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6725 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6726 PtrType, LN0->getBasePtr(),
6727 DAG.getConstant(PtrOff, DL, PtrType));
6728 AddToWorklist(NewPtr.getNode());
6731 if (ExtType == ISD::NON_EXTLOAD)
6732 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6733 LN0->getPointerInfo().getWithOffset(PtrOff),
6734 LN0->isVolatile(), LN0->isNonTemporal(),
6735 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6737 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6738 LN0->getPointerInfo().getWithOffset(PtrOff),
6739 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6740 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6742 // Replace the old load's chain with the new load's chain.
6743 WorklistRemover DeadNodes(*this);
6744 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6746 // Shift the result left, if we've swallowed a left shift.
6747 SDValue Result = Load;
6748 if (ShLeftAmt != 0) {
6749 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6750 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6752 // If the shift amount is as large as the result size (but, presumably,
6753 // no larger than the source) then the useful bits of the result are
6754 // zero; we can't simply return the shortened shift, because the result
6755 // of that operation is undefined.
6757 if (ShLeftAmt >= VT.getSizeInBits())
6758 Result = DAG.getConstant(0, DL, VT);
6760 Result = DAG.getNode(ISD::SHL, DL, VT,
6761 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6764 // Return the new loaded value.
6768 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6769 SDValue N0 = N->getOperand(0);
6770 SDValue N1 = N->getOperand(1);
6771 EVT VT = N->getValueType(0);
6772 EVT EVT = cast<VTSDNode>(N1)->getVT();
6773 unsigned VTBits = VT.getScalarType().getSizeInBits();
6774 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6776 // fold (sext_in_reg c1) -> c1
6777 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6778 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6780 // If the input is already sign extended, just drop the extension.
6781 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6784 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6785 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6786 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6787 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6788 N0.getOperand(0), N1);
6790 // fold (sext_in_reg (sext x)) -> (sext x)
6791 // fold (sext_in_reg (aext x)) -> (sext x)
6792 // if x is small enough.
6793 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6794 SDValue N00 = N0.getOperand(0);
6795 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6796 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6797 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6800 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6801 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6802 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6804 // fold operands of sext_in_reg based on knowledge that the top bits are not
6806 if (SimplifyDemandedBits(SDValue(N, 0)))
6807 return SDValue(N, 0);
6809 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6810 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6811 if (SDValue NarrowLoad = ReduceLoadWidth(N))
6814 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6815 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6816 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6817 if (N0.getOpcode() == ISD::SRL) {
6818 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6819 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6820 // We can turn this into an SRA iff the input to the SRL is already sign
6822 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6823 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6824 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6825 N0.getOperand(0), N0.getOperand(1));
6829 // fold (sext_inreg (extload x)) -> (sextload x)
6830 if (ISD::isEXTLoad(N0.getNode()) &&
6831 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6832 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6833 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6834 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6835 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6836 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6838 LN0->getBasePtr(), EVT,
6839 LN0->getMemOperand());
6840 CombineTo(N, ExtLoad);
6841 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6842 AddToWorklist(ExtLoad.getNode());
6843 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6845 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6846 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6848 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6849 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6850 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6851 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6852 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6854 LN0->getBasePtr(), EVT,
6855 LN0->getMemOperand());
6856 CombineTo(N, ExtLoad);
6857 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6858 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6861 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6862 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6863 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6864 N0.getOperand(1), false);
6865 if (BSwap.getNode())
6866 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6870 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6871 // into a build_vector.
6872 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6873 SmallVector<SDValue, 8> Elts;
6874 unsigned NumElts = N0->getNumOperands();
6875 unsigned ShAmt = VTBits - EVTBits;
6877 for (unsigned i = 0; i != NumElts; ++i) {
6878 SDValue Op = N0->getOperand(i);
6879 if (Op->getOpcode() == ISD::UNDEF) {
6884 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6885 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6886 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6887 SDLoc(Op), Op.getValueType()));
6890 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6896 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6897 SDValue N0 = N->getOperand(0);
6898 EVT VT = N->getValueType(0);
6900 if (N0.getOpcode() == ISD::UNDEF)
6901 return DAG.getUNDEF(VT);
6903 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6905 return SDValue(Res, 0);
6910 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6911 SDValue N0 = N->getOperand(0);
6912 EVT VT = N->getValueType(0);
6913 bool isLE = DAG.getDataLayout().isLittleEndian();
6916 if (N0.getValueType() == N->getValueType(0))
6918 // fold (truncate c1) -> c1
6919 if (isConstantIntBuildVectorOrConstantInt(N0))
6920 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6921 // fold (truncate (truncate x)) -> (truncate x)
6922 if (N0.getOpcode() == ISD::TRUNCATE)
6923 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6924 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6925 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6926 N0.getOpcode() == ISD::SIGN_EXTEND ||
6927 N0.getOpcode() == ISD::ANY_EXTEND) {
6928 if (N0.getOperand(0).getValueType().bitsLT(VT))
6929 // if the source is smaller than the dest, we still need an extend
6930 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6932 if (N0.getOperand(0).getValueType().bitsGT(VT))
6933 // if the source is larger than the dest, than we just need the truncate
6934 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6935 // if the source and dest are the same type, we can drop both the extend
6936 // and the truncate.
6937 return N0.getOperand(0);
6940 // Fold extract-and-trunc into a narrow extract. For example:
6941 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6942 // i32 y = TRUNCATE(i64 x)
6944 // v16i8 b = BITCAST (v2i64 val)
6945 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6947 // Note: We only run this optimization after type legalization (which often
6948 // creates this pattern) and before operation legalization after which
6949 // we need to be more careful about the vector instructions that we generate.
6950 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6951 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6953 EVT VecTy = N0.getOperand(0).getValueType();
6954 EVT ExTy = N0.getValueType();
6955 EVT TrTy = N->getValueType(0);
6957 unsigned NumElem = VecTy.getVectorNumElements();
6958 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6960 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6961 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6963 SDValue EltNo = N0->getOperand(1);
6964 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6965 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6966 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
6967 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6969 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6970 NVT, N0.getOperand(0));
6973 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6975 DAG.getConstant(Index, DL, IndexTy));
6979 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6980 if (N0.getOpcode() == ISD::SELECT) {
6981 EVT SrcVT = N0.getValueType();
6982 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6983 TLI.isTruncateFree(SrcVT, VT)) {
6985 SDValue Cond = N0.getOperand(0);
6986 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6987 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6988 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6992 // Fold a series of buildvector, bitcast, and truncate if possible.
6994 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6995 // (2xi32 (buildvector x, y)).
6996 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6997 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6998 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6999 N0.getOperand(0).hasOneUse()) {
7001 SDValue BuildVect = N0.getOperand(0);
7002 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7003 EVT TruncVecEltTy = VT.getVectorElementType();
7005 // Check that the element types match.
7006 if (BuildVectEltTy == TruncVecEltTy) {
7007 // Now we only need to compute the offset of the truncated elements.
7008 unsigned BuildVecNumElts = BuildVect.getNumOperands();
7009 unsigned TruncVecNumElts = VT.getVectorNumElements();
7010 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7012 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7013 "Invalid number of elements");
7015 SmallVector<SDValue, 8> Opnds;
7016 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7017 Opnds.push_back(BuildVect.getOperand(i));
7019 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
7023 // See if we can simplify the input to this truncate through knowledge that
7024 // only the low bits are being used.
7025 // For example "trunc (or (shl x, 8), y)" // -> trunc y
7026 // Currently we only perform this optimization on scalars because vectors
7027 // may have different active low bits.
7028 if (!VT.isVector()) {
7030 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7031 VT.getSizeInBits()));
7032 if (Shorter.getNode())
7033 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7035 // fold (truncate (load x)) -> (smaller load x)
7036 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7037 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7038 if (SDValue Reduced = ReduceLoadWidth(N))
7041 // Handle the case where the load remains an extending load even
7042 // after truncation.
7043 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7044 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7045 if (!LN0->isVolatile() &&
7046 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7047 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7048 VT, LN0->getChain(), LN0->getBasePtr(),
7050 LN0->getMemOperand());
7051 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7056 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7057 // where ... are all 'undef'.
7058 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7059 SmallVector<EVT, 8> VTs;
7062 unsigned NumDefs = 0;
7064 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7065 SDValue X = N0.getOperand(i);
7066 if (X.getOpcode() != ISD::UNDEF) {
7071 // Stop if more than one members are non-undef.
7074 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7075 VT.getVectorElementType(),
7076 X.getValueType().getVectorNumElements()));
7080 return DAG.getUNDEF(VT);
7083 assert(V.getNode() && "The single defined operand is empty!");
7084 SmallVector<SDValue, 8> Opnds;
7085 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7087 Opnds.push_back(DAG.getUNDEF(VTs[i]));
7090 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7091 AddToWorklist(NV.getNode());
7092 Opnds.push_back(NV);
7094 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7098 // Simplify the operands using demanded-bits information.
7099 if (!VT.isVector() &&
7100 SimplifyDemandedBits(SDValue(N, 0)))
7101 return SDValue(N, 0);
7106 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7107 SDValue Elt = N->getOperand(i);
7108 if (Elt.getOpcode() != ISD::MERGE_VALUES)
7109 return Elt.getNode();
7110 return Elt.getOperand(Elt.getResNo()).getNode();
7113 /// build_pair (load, load) -> load
7114 /// if load locations are consecutive.
7115 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7116 assert(N->getOpcode() == ISD::BUILD_PAIR);
7118 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7119 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7120 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7121 LD1->getAddressSpace() != LD2->getAddressSpace())
7123 EVT LD1VT = LD1->getValueType(0);
7125 if (ISD::isNON_EXTLoad(LD2) &&
7127 // If both are volatile this would reduce the number of volatile loads.
7128 // If one is volatile it might be ok, but play conservative and bail out.
7129 !LD1->isVolatile() &&
7130 !LD2->isVolatile() &&
7131 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7132 unsigned Align = LD1->getAlignment();
7133 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7134 VT.getTypeForEVT(*DAG.getContext()));
7136 if (NewAlign <= Align &&
7137 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7138 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7139 LD1->getBasePtr(), LD1->getPointerInfo(),
7140 false, false, false, Align);
7146 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7147 SDValue N0 = N->getOperand(0);
7148 EVT VT = N->getValueType(0);
7150 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7151 // Only do this before legalize, since afterward the target may be depending
7152 // on the bitconvert.
7153 // First check to see if this is all constant.
7155 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7157 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7159 EVT DestEltVT = N->getValueType(0).getVectorElementType();
7160 assert(!DestEltVT.isVector() &&
7161 "Element type of vector ValueType must not be vector!");
7163 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7166 // If the input is a constant, let getNode fold it.
7167 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7168 // If we can't allow illegal operations, we need to check that this is just
7169 // a fp -> int or int -> conversion and that the resulting operation will
7171 if (!LegalOperations ||
7172 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7173 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7174 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7175 TLI.isOperationLegal(ISD::Constant, VT)))
7176 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7179 // (conv (conv x, t1), t2) -> (conv x, t2)
7180 if (N0.getOpcode() == ISD::BITCAST)
7181 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7184 // fold (conv (load x)) -> (load (conv*)x)
7185 // If the resultant load doesn't need a higher alignment than the original!
7186 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7187 // Do not change the width of a volatile load.
7188 !cast<LoadSDNode>(N0)->isVolatile() &&
7189 // Do not remove the cast if the types differ in endian layout.
7190 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7191 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7192 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7193 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7194 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7195 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7196 VT.getTypeForEVT(*DAG.getContext()));
7197 unsigned OrigAlign = LN0->getAlignment();
7199 if (Align <= OrigAlign) {
7200 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7201 LN0->getBasePtr(), LN0->getPointerInfo(),
7202 LN0->isVolatile(), LN0->isNonTemporal(),
7203 LN0->isInvariant(), OrigAlign,
7205 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7210 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7211 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7212 // This often reduces constant pool loads.
7213 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7214 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7215 N0.getNode()->hasOneUse() && VT.isInteger() &&
7216 !VT.isVector() && !N0.getValueType().isVector()) {
7217 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7219 AddToWorklist(NewConv.getNode());
7222 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7223 if (N0.getOpcode() == ISD::FNEG)
7224 return DAG.getNode(ISD::XOR, DL, VT,
7225 NewConv, DAG.getConstant(SignBit, DL, VT));
7226 assert(N0.getOpcode() == ISD::FABS);
7227 return DAG.getNode(ISD::AND, DL, VT,
7228 NewConv, DAG.getConstant(~SignBit, DL, VT));
7231 // fold (bitconvert (fcopysign cst, x)) ->
7232 // (or (and (bitconvert x), sign), (and cst, (not sign)))
7233 // Note that we don't handle (copysign x, cst) because this can always be
7234 // folded to an fneg or fabs.
7235 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7236 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7237 VT.isInteger() && !VT.isVector()) {
7238 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7239 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7240 if (isTypeLegal(IntXVT)) {
7241 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7242 IntXVT, N0.getOperand(1));
7243 AddToWorklist(X.getNode());
7245 // If X has a different width than the result/lhs, sext it or truncate it.
7246 unsigned VTWidth = VT.getSizeInBits();
7247 if (OrigXWidth < VTWidth) {
7248 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7249 AddToWorklist(X.getNode());
7250 } else if (OrigXWidth > VTWidth) {
7251 // To get the sign bit in the right place, we have to shift it right
7252 // before truncating.
7254 X = DAG.getNode(ISD::SRL, DL,
7255 X.getValueType(), X,
7256 DAG.getConstant(OrigXWidth-VTWidth, DL,
7258 AddToWorklist(X.getNode());
7259 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7260 AddToWorklist(X.getNode());
7263 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7264 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7265 X, DAG.getConstant(SignBit, SDLoc(X), VT));
7266 AddToWorklist(X.getNode());
7268 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7269 VT, N0.getOperand(0));
7270 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7271 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7272 AddToWorklist(Cst.getNode());
7274 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7278 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7279 if (N0.getOpcode() == ISD::BUILD_PAIR)
7280 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7283 // Remove double bitcasts from shuffles - this is often a legacy of
7284 // XformToShuffleWithZero being used to combine bitmaskings (of
7285 // float vectors bitcast to integer vectors) into shuffles.
7286 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7287 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7288 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7289 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7290 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7291 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7293 // If operands are a bitcast, peek through if it casts the original VT.
7294 // If operands are a constant, just bitcast back to original VT.
7295 auto PeekThroughBitcast = [&](SDValue Op) {
7296 if (Op.getOpcode() == ISD::BITCAST &&
7297 Op.getOperand(0).getValueType() == VT)
7298 return SDValue(Op.getOperand(0));
7299 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7300 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7301 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7305 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7306 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7311 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7312 SmallVector<int, 8> NewMask;
7313 for (int M : SVN->getMask())
7314 for (int i = 0; i != MaskScale; ++i)
7315 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7317 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7319 std::swap(SV0, SV1);
7320 ShuffleVectorSDNode::commuteMask(NewMask);
7321 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7325 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7331 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7332 EVT VT = N->getValueType(0);
7333 return CombineConsecutiveLoads(N, VT);
7336 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7337 /// operands. DstEltVT indicates the destination element value type.
7338 SDValue DAGCombiner::
7339 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7340 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7342 // If this is already the right type, we're done.
7343 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7345 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7346 unsigned DstBitSize = DstEltVT.getSizeInBits();
7348 // If this is a conversion of N elements of one type to N elements of another
7349 // type, convert each element. This handles FP<->INT cases.
7350 if (SrcBitSize == DstBitSize) {
7351 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7352 BV->getValueType(0).getVectorNumElements());
7354 // Due to the FP element handling below calling this routine recursively,
7355 // we can end up with a scalar-to-vector node here.
7356 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7357 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7358 DAG.getNode(ISD::BITCAST, SDLoc(BV),
7359 DstEltVT, BV->getOperand(0)));
7361 SmallVector<SDValue, 8> Ops;
7362 for (SDValue Op : BV->op_values()) {
7363 // If the vector element type is not legal, the BUILD_VECTOR operands
7364 // are promoted and implicitly truncated. Make that explicit here.
7365 if (Op.getValueType() != SrcEltVT)
7366 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7367 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7369 AddToWorklist(Ops.back().getNode());
7371 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7374 // Otherwise, we're growing or shrinking the elements. To avoid having to
7375 // handle annoying details of growing/shrinking FP values, we convert them to
7377 if (SrcEltVT.isFloatingPoint()) {
7378 // Convert the input float vector to a int vector where the elements are the
7380 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7381 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7385 // Now we know the input is an integer vector. If the output is a FP type,
7386 // convert to integer first, then to FP of the right size.
7387 if (DstEltVT.isFloatingPoint()) {
7388 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7389 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7391 // Next, convert to FP elements of the same size.
7392 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7397 // Okay, we know the src/dst types are both integers of differing types.
7398 // Handling growing first.
7399 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7400 if (SrcBitSize < DstBitSize) {
7401 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7403 SmallVector<SDValue, 8> Ops;
7404 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7405 i += NumInputsPerOutput) {
7406 bool isLE = DAG.getDataLayout().isLittleEndian();
7407 APInt NewBits = APInt(DstBitSize, 0);
7408 bool EltIsUndef = true;
7409 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7410 // Shift the previously computed bits over.
7411 NewBits <<= SrcBitSize;
7412 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7413 if (Op.getOpcode() == ISD::UNDEF) continue;
7416 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7417 zextOrTrunc(SrcBitSize).zext(DstBitSize);
7421 Ops.push_back(DAG.getUNDEF(DstEltVT));
7423 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7426 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7427 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7430 // Finally, this must be the case where we are shrinking elements: each input
7431 // turns into multiple outputs.
7432 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7433 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7434 NumOutputsPerInput*BV->getNumOperands());
7435 SmallVector<SDValue, 8> Ops;
7437 for (const SDValue &Op : BV->op_values()) {
7438 if (Op.getOpcode() == ISD::UNDEF) {
7439 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7443 APInt OpVal = cast<ConstantSDNode>(Op)->
7444 getAPIntValue().zextOrTrunc(SrcBitSize);
7446 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7447 APInt ThisVal = OpVal.trunc(DstBitSize);
7448 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7449 OpVal = OpVal.lshr(DstBitSize);
7452 // For big endian targets, swap the order of the pieces of each element.
7453 if (DAG.getDataLayout().isBigEndian())
7454 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7457 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7460 /// Try to perform FMA combining on a given FADD node.
7461 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7462 SDValue N0 = N->getOperand(0);
7463 SDValue N1 = N->getOperand(1);
7464 EVT VT = N->getValueType(0);
7467 const TargetOptions &Options = DAG.getTarget().Options;
7468 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7469 Options.UnsafeFPMath);
7471 // Floating-point multiply-add with intermediate rounding.
7472 bool HasFMAD = (LegalOperations &&
7473 TLI.isOperationLegal(ISD::FMAD, VT));
7475 // Floating-point multiply-add without intermediate rounding.
7476 bool HasFMA = ((!LegalOperations ||
7477 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7478 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7481 // No valid opcode, do not combine.
7482 if (!HasFMAD && !HasFMA)
7485 // Always prefer FMAD to FMA for precision.
7486 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7487 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7488 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7490 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7491 // prefer to fold the multiply with fewer uses.
7492 if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7493 N1.getOpcode() == ISD::FMUL) {
7494 if (N0.getNode()->use_size() > N1.getNode()->use_size())
7498 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7499 if (N0.getOpcode() == ISD::FMUL &&
7500 (Aggressive || N0->hasOneUse())) {
7501 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7502 N0.getOperand(0), N0.getOperand(1), N1);
7505 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7506 // Note: Commutes FADD operands.
7507 if (N1.getOpcode() == ISD::FMUL &&
7508 (Aggressive || N1->hasOneUse())) {
7509 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7510 N1.getOperand(0), N1.getOperand(1), N0);
7513 // Look through FP_EXTEND nodes to do more combining.
7514 if (UnsafeFPMath && LookThroughFPExt) {
7515 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7516 if (N0.getOpcode() == ISD::FP_EXTEND) {
7517 SDValue N00 = N0.getOperand(0);
7518 if (N00.getOpcode() == ISD::FMUL)
7519 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7520 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7522 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7523 N00.getOperand(1)), N1);
7526 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7527 // Note: Commutes FADD operands.
7528 if (N1.getOpcode() == ISD::FP_EXTEND) {
7529 SDValue N10 = N1.getOperand(0);
7530 if (N10.getOpcode() == ISD::FMUL)
7531 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7532 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7534 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7535 N10.getOperand(1)), N0);
7539 // More folding opportunities when target permits.
7540 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7541 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7542 if (N0.getOpcode() == PreferredFusedOpcode &&
7543 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7544 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7545 N0.getOperand(0), N0.getOperand(1),
7546 DAG.getNode(PreferredFusedOpcode, SL, VT,
7547 N0.getOperand(2).getOperand(0),
7548 N0.getOperand(2).getOperand(1),
7552 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7553 if (N1->getOpcode() == PreferredFusedOpcode &&
7554 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7555 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7556 N1.getOperand(0), N1.getOperand(1),
7557 DAG.getNode(PreferredFusedOpcode, SL, VT,
7558 N1.getOperand(2).getOperand(0),
7559 N1.getOperand(2).getOperand(1),
7563 if (UnsafeFPMath && LookThroughFPExt) {
7564 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7565 // -> (fma x, y, (fma (fpext u), (fpext v), z))
7566 auto FoldFAddFMAFPExtFMul = [&] (
7567 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7568 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7569 DAG.getNode(PreferredFusedOpcode, SL, VT,
7570 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7571 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7574 if (N0.getOpcode() == PreferredFusedOpcode) {
7575 SDValue N02 = N0.getOperand(2);
7576 if (N02.getOpcode() == ISD::FP_EXTEND) {
7577 SDValue N020 = N02.getOperand(0);
7578 if (N020.getOpcode() == ISD::FMUL)
7579 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7580 N020.getOperand(0), N020.getOperand(1),
7585 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7586 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7587 // FIXME: This turns two single-precision and one double-precision
7588 // operation into two double-precision operations, which might not be
7589 // interesting for all targets, especially GPUs.
7590 auto FoldFAddFPExtFMAFMul = [&] (
7591 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7592 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7593 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7594 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7595 DAG.getNode(PreferredFusedOpcode, SL, VT,
7596 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7597 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7600 if (N0.getOpcode() == ISD::FP_EXTEND) {
7601 SDValue N00 = N0.getOperand(0);
7602 if (N00.getOpcode() == PreferredFusedOpcode) {
7603 SDValue N002 = N00.getOperand(2);
7604 if (N002.getOpcode() == ISD::FMUL)
7605 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7606 N002.getOperand(0), N002.getOperand(1),
7611 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7612 // -> (fma y, z, (fma (fpext u), (fpext v), x))
7613 if (N1.getOpcode() == PreferredFusedOpcode) {
7614 SDValue N12 = N1.getOperand(2);
7615 if (N12.getOpcode() == ISD::FP_EXTEND) {
7616 SDValue N120 = N12.getOperand(0);
7617 if (N120.getOpcode() == ISD::FMUL)
7618 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7619 N120.getOperand(0), N120.getOperand(1),
7624 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7625 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7626 // FIXME: This turns two single-precision and one double-precision
7627 // operation into two double-precision operations, which might not be
7628 // interesting for all targets, especially GPUs.
7629 if (N1.getOpcode() == ISD::FP_EXTEND) {
7630 SDValue N10 = N1.getOperand(0);
7631 if (N10.getOpcode() == PreferredFusedOpcode) {
7632 SDValue N102 = N10.getOperand(2);
7633 if (N102.getOpcode() == ISD::FMUL)
7634 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7635 N102.getOperand(0), N102.getOperand(1),
7645 /// Try to perform FMA combining on a given FSUB node.
7646 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7647 SDValue N0 = N->getOperand(0);
7648 SDValue N1 = N->getOperand(1);
7649 EVT VT = N->getValueType(0);
7652 const TargetOptions &Options = DAG.getTarget().Options;
7653 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7654 Options.UnsafeFPMath);
7656 // Floating-point multiply-add with intermediate rounding.
7657 bool HasFMAD = (LegalOperations &&
7658 TLI.isOperationLegal(ISD::FMAD, VT));
7660 // Floating-point multiply-add without intermediate rounding.
7661 bool HasFMA = ((!LegalOperations ||
7662 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7663 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7666 // No valid opcode, do not combine.
7667 if (!HasFMAD && !HasFMA)
7670 // Always prefer FMAD to FMA for precision.
7671 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7672 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7673 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7675 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7676 if (N0.getOpcode() == ISD::FMUL &&
7677 (Aggressive || N0->hasOneUse())) {
7678 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7679 N0.getOperand(0), N0.getOperand(1),
7680 DAG.getNode(ISD::FNEG, SL, VT, N1));
7683 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7684 // Note: Commutes FSUB operands.
7685 if (N1.getOpcode() == ISD::FMUL &&
7686 (Aggressive || N1->hasOneUse()))
7687 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7688 DAG.getNode(ISD::FNEG, SL, VT,
7690 N1.getOperand(1), N0);
7692 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7693 if (N0.getOpcode() == ISD::FNEG &&
7694 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7695 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7696 SDValue N00 = N0.getOperand(0).getOperand(0);
7697 SDValue N01 = N0.getOperand(0).getOperand(1);
7698 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7699 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7700 DAG.getNode(ISD::FNEG, SL, VT, N1));
7703 // Look through FP_EXTEND nodes to do more combining.
7704 if (UnsafeFPMath && LookThroughFPExt) {
7705 // fold (fsub (fpext (fmul x, y)), z)
7706 // -> (fma (fpext x), (fpext y), (fneg z))
7707 if (N0.getOpcode() == ISD::FP_EXTEND) {
7708 SDValue N00 = N0.getOperand(0);
7709 if (N00.getOpcode() == ISD::FMUL)
7710 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7711 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7713 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7715 DAG.getNode(ISD::FNEG, SL, VT, N1));
7718 // fold (fsub x, (fpext (fmul y, z)))
7719 // -> (fma (fneg (fpext y)), (fpext z), x)
7720 // Note: Commutes FSUB operands.
7721 if (N1.getOpcode() == ISD::FP_EXTEND) {
7722 SDValue N10 = N1.getOperand(0);
7723 if (N10.getOpcode() == ISD::FMUL)
7724 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7725 DAG.getNode(ISD::FNEG, SL, VT,
7726 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7727 N10.getOperand(0))),
7728 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7733 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7734 // -> (fneg (fma (fpext x), (fpext y), z))
7735 // Note: This could be removed with appropriate canonicalization of the
7736 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7737 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7738 // from implementing the canonicalization in visitFSUB.
7739 if (N0.getOpcode() == ISD::FP_EXTEND) {
7740 SDValue N00 = N0.getOperand(0);
7741 if (N00.getOpcode() == ISD::FNEG) {
7742 SDValue N000 = N00.getOperand(0);
7743 if (N000.getOpcode() == ISD::FMUL) {
7744 return DAG.getNode(ISD::FNEG, SL, VT,
7745 DAG.getNode(PreferredFusedOpcode, SL, VT,
7746 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7747 N000.getOperand(0)),
7748 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7749 N000.getOperand(1)),
7755 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7756 // -> (fneg (fma (fpext x)), (fpext y), z)
7757 // Note: This could be removed with appropriate canonicalization of the
7758 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7759 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7760 // from implementing the canonicalization in visitFSUB.
7761 if (N0.getOpcode() == ISD::FNEG) {
7762 SDValue N00 = N0.getOperand(0);
7763 if (N00.getOpcode() == ISD::FP_EXTEND) {
7764 SDValue N000 = N00.getOperand(0);
7765 if (N000.getOpcode() == ISD::FMUL) {
7766 return DAG.getNode(ISD::FNEG, SL, VT,
7767 DAG.getNode(PreferredFusedOpcode, SL, VT,
7768 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7769 N000.getOperand(0)),
7770 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7771 N000.getOperand(1)),
7779 // More folding opportunities when target permits.
7780 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7781 // fold (fsub (fma x, y, (fmul u, v)), z)
7782 // -> (fma x, y (fma u, v, (fneg z)))
7783 if (N0.getOpcode() == PreferredFusedOpcode &&
7784 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7785 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7786 N0.getOperand(0), N0.getOperand(1),
7787 DAG.getNode(PreferredFusedOpcode, SL, VT,
7788 N0.getOperand(2).getOperand(0),
7789 N0.getOperand(2).getOperand(1),
7790 DAG.getNode(ISD::FNEG, SL, VT,
7794 // fold (fsub x, (fma y, z, (fmul u, v)))
7795 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7796 if (N1.getOpcode() == PreferredFusedOpcode &&
7797 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7798 SDValue N20 = N1.getOperand(2).getOperand(0);
7799 SDValue N21 = N1.getOperand(2).getOperand(1);
7800 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7801 DAG.getNode(ISD::FNEG, SL, VT,
7804 DAG.getNode(PreferredFusedOpcode, SL, VT,
7805 DAG.getNode(ISD::FNEG, SL, VT, N20),
7810 if (UnsafeFPMath && LookThroughFPExt) {
7811 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7812 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7813 if (N0.getOpcode() == PreferredFusedOpcode) {
7814 SDValue N02 = N0.getOperand(2);
7815 if (N02.getOpcode() == ISD::FP_EXTEND) {
7816 SDValue N020 = N02.getOperand(0);
7817 if (N020.getOpcode() == ISD::FMUL)
7818 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7819 N0.getOperand(0), N0.getOperand(1),
7820 DAG.getNode(PreferredFusedOpcode, SL, VT,
7821 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7822 N020.getOperand(0)),
7823 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7824 N020.getOperand(1)),
7825 DAG.getNode(ISD::FNEG, SL, VT,
7830 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7831 // -> (fma (fpext x), (fpext y),
7832 // (fma (fpext u), (fpext v), (fneg z)))
7833 // FIXME: This turns two single-precision and one double-precision
7834 // operation into two double-precision operations, which might not be
7835 // interesting for all targets, especially GPUs.
7836 if (N0.getOpcode() == ISD::FP_EXTEND) {
7837 SDValue N00 = N0.getOperand(0);
7838 if (N00.getOpcode() == PreferredFusedOpcode) {
7839 SDValue N002 = N00.getOperand(2);
7840 if (N002.getOpcode() == ISD::FMUL)
7841 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7842 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7844 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7846 DAG.getNode(PreferredFusedOpcode, SL, VT,
7847 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7848 N002.getOperand(0)),
7849 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7850 N002.getOperand(1)),
7851 DAG.getNode(ISD::FNEG, SL, VT,
7856 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7857 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7858 if (N1.getOpcode() == PreferredFusedOpcode &&
7859 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7860 SDValue N120 = N1.getOperand(2).getOperand(0);
7861 if (N120.getOpcode() == ISD::FMUL) {
7862 SDValue N1200 = N120.getOperand(0);
7863 SDValue N1201 = N120.getOperand(1);
7864 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7865 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7867 DAG.getNode(PreferredFusedOpcode, SL, VT,
7868 DAG.getNode(ISD::FNEG, SL, VT,
7869 DAG.getNode(ISD::FP_EXTEND, SL,
7871 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7877 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7878 // -> (fma (fneg (fpext y)), (fpext z),
7879 // (fma (fneg (fpext u)), (fpext v), x))
7880 // FIXME: This turns two single-precision and one double-precision
7881 // operation into two double-precision operations, which might not be
7882 // interesting for all targets, especially GPUs.
7883 if (N1.getOpcode() == ISD::FP_EXTEND &&
7884 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7885 SDValue N100 = N1.getOperand(0).getOperand(0);
7886 SDValue N101 = N1.getOperand(0).getOperand(1);
7887 SDValue N102 = N1.getOperand(0).getOperand(2);
7888 if (N102.getOpcode() == ISD::FMUL) {
7889 SDValue N1020 = N102.getOperand(0);
7890 SDValue N1021 = N102.getOperand(1);
7891 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7892 DAG.getNode(ISD::FNEG, SL, VT,
7893 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7895 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7896 DAG.getNode(PreferredFusedOpcode, SL, VT,
7897 DAG.getNode(ISD::FNEG, SL, VT,
7898 DAG.getNode(ISD::FP_EXTEND, SL,
7900 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7911 SDValue DAGCombiner::visitFADD(SDNode *N) {
7912 SDValue N0 = N->getOperand(0);
7913 SDValue N1 = N->getOperand(1);
7914 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7915 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7916 EVT VT = N->getValueType(0);
7918 const TargetOptions &Options = DAG.getTarget().Options;
7922 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7925 // fold (fadd c1, c2) -> c1 + c2
7927 return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7929 // canonicalize constant to RHS
7930 if (N0CFP && !N1CFP)
7931 return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7933 // fold (fadd A, (fneg B)) -> (fsub A, B)
7934 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7935 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7936 return DAG.getNode(ISD::FSUB, DL, VT, N0,
7937 GetNegatedExpression(N1, DAG, LegalOperations));
7939 // fold (fadd (fneg A), B) -> (fsub B, A)
7940 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7941 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7942 return DAG.getNode(ISD::FSUB, DL, VT, N1,
7943 GetNegatedExpression(N0, DAG, LegalOperations));
7945 // If 'unsafe math' is enabled, fold lots of things.
7946 if (Options.UnsafeFPMath) {
7947 // No FP constant should be created after legalization as Instruction
7948 // Selection pass has a hard time dealing with FP constants.
7949 bool AllowNewConst = (Level < AfterLegalizeDAG);
7951 // fold (fadd A, 0) -> A
7952 if (N1CFP && N1CFP->isZero())
7955 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7956 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7957 isa<ConstantFPSDNode>(N0.getOperand(1)))
7958 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7959 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7961 // If allowed, fold (fadd (fneg x), x) -> 0.0
7962 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7963 return DAG.getConstantFP(0.0, DL, VT);
7965 // If allowed, fold (fadd x, (fneg x)) -> 0.0
7966 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7967 return DAG.getConstantFP(0.0, DL, VT);
7969 // We can fold chains of FADD's of the same value into multiplications.
7970 // This transform is not safe in general because we are reducing the number
7971 // of rounding steps.
7972 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7973 if (N0.getOpcode() == ISD::FMUL) {
7974 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7975 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7977 // (fadd (fmul x, c), x) -> (fmul x, c+1)
7978 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7979 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7980 DAG.getConstantFP(1.0, DL, VT));
7981 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7984 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7985 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7986 N1.getOperand(0) == N1.getOperand(1) &&
7987 N0.getOperand(0) == N1.getOperand(0)) {
7988 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7989 DAG.getConstantFP(2.0, DL, VT));
7990 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
7994 if (N1.getOpcode() == ISD::FMUL) {
7995 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7996 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7998 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7999 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8000 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
8001 DAG.getConstantFP(1.0, DL, VT));
8002 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
8005 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8006 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8007 N0.getOperand(0) == N0.getOperand(1) &&
8008 N1.getOperand(0) == N0.getOperand(0)) {
8009 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
8010 DAG.getConstantFP(2.0, DL, VT));
8011 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
8015 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8016 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
8017 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8018 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
8019 (N0.getOperand(0) == N1)) {
8020 return DAG.getNode(ISD::FMUL, DL, VT,
8021 N1, DAG.getConstantFP(3.0, DL, VT));
8025 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8026 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
8027 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8028 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8029 N1.getOperand(0) == N0) {
8030 return DAG.getNode(ISD::FMUL, DL, VT,
8031 N0, DAG.getConstantFP(3.0, DL, VT));
8035 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8036 if (AllowNewConst &&
8037 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8038 N0.getOperand(0) == N0.getOperand(1) &&
8039 N1.getOperand(0) == N1.getOperand(1) &&
8040 N0.getOperand(0) == N1.getOperand(0)) {
8041 return DAG.getNode(ISD::FMUL, DL, VT,
8042 N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
8045 } // enable-unsafe-fp-math
8047 // FADD -> FMA combines:
8048 if (SDValue Fused = visitFADDForFMACombine(N)) {
8049 AddToWorklist(Fused.getNode());
8056 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8057 SDValue N0 = N->getOperand(0);
8058 SDValue N1 = N->getOperand(1);
8059 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8060 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8061 EVT VT = N->getValueType(0);
8063 const TargetOptions &Options = DAG.getTarget().Options;
8067 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8070 // fold (fsub c1, c2) -> c1-c2
8072 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
8074 // fold (fsub A, (fneg B)) -> (fadd A, B)
8075 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8076 return DAG.getNode(ISD::FADD, dl, VT, N0,
8077 GetNegatedExpression(N1, DAG, LegalOperations));
8079 // If 'unsafe math' is enabled, fold lots of things.
8080 if (Options.UnsafeFPMath) {
8082 if (N1CFP && N1CFP->isZero())
8085 // (fsub 0, B) -> -B
8086 if (N0CFP && N0CFP->isZero()) {
8087 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8088 return GetNegatedExpression(N1, DAG, LegalOperations);
8089 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8090 return DAG.getNode(ISD::FNEG, dl, VT, N1);
8093 // (fsub x, x) -> 0.0
8095 return DAG.getConstantFP(0.0f, dl, VT);
8097 // (fsub x, (fadd x, y)) -> (fneg y)
8098 // (fsub x, (fadd y, x)) -> (fneg y)
8099 if (N1.getOpcode() == ISD::FADD) {
8100 SDValue N10 = N1->getOperand(0);
8101 SDValue N11 = N1->getOperand(1);
8103 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8104 return GetNegatedExpression(N11, DAG, LegalOperations);
8106 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8107 return GetNegatedExpression(N10, DAG, LegalOperations);
8111 // FSUB -> FMA combines:
8112 if (SDValue Fused = visitFSUBForFMACombine(N)) {
8113 AddToWorklist(Fused.getNode());
8120 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8121 SDValue N0 = N->getOperand(0);
8122 SDValue N1 = N->getOperand(1);
8123 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8124 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8125 EVT VT = N->getValueType(0);
8127 const TargetOptions &Options = DAG.getTarget().Options;
8130 if (VT.isVector()) {
8131 // This just handles C1 * C2 for vectors. Other vector folds are below.
8132 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8136 // fold (fmul c1, c2) -> c1*c2
8138 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
8140 // canonicalize constant to RHS
8141 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8142 !isConstantFPBuildVectorOrConstantFP(N1))
8143 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
8145 // fold (fmul A, 1.0) -> A
8146 if (N1CFP && N1CFP->isExactlyValue(1.0))
8149 if (Options.UnsafeFPMath) {
8150 // fold (fmul A, 0) -> 0
8151 if (N1CFP && N1CFP->isZero())
8154 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8155 if (N0.getOpcode() == ISD::FMUL) {
8156 // Fold scalars or any vector constants (not just splats).
8157 // This fold is done in general by InstCombine, but extra fmul insts
8158 // may have been generated during lowering.
8159 SDValue N00 = N0.getOperand(0);
8160 SDValue N01 = N0.getOperand(1);
8161 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8162 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8163 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8165 // Check 1: Make sure that the first operand of the inner multiply is NOT
8166 // a constant. Otherwise, we may induce infinite looping.
8167 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8168 // Check 2: Make sure that the second operand of the inner multiply and
8169 // the second operand of the outer multiply are constants.
8170 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8171 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8172 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8173 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
8178 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8179 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8180 // during an early run of DAGCombiner can prevent folding with fmuls
8181 // inserted during lowering.
8182 if (N0.getOpcode() == ISD::FADD &&
8183 (N0.getOperand(0) == N0.getOperand(1)) &&
8185 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8186 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8187 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
8191 // fold (fmul X, 2.0) -> (fadd X, X)
8192 if (N1CFP && N1CFP->isExactlyValue(+2.0))
8193 return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
8195 // fold (fmul X, -1.0) -> (fneg X)
8196 if (N1CFP && N1CFP->isExactlyValue(-1.0))
8197 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8198 return DAG.getNode(ISD::FNEG, DL, VT, N0);
8200 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8201 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8202 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8203 // Both can be negated for free, check to see if at least one is cheaper
8205 if (LHSNeg == 2 || RHSNeg == 2)
8206 return DAG.getNode(ISD::FMUL, DL, VT,
8207 GetNegatedExpression(N0, DAG, LegalOperations),
8208 GetNegatedExpression(N1, DAG, LegalOperations));
8215 SDValue DAGCombiner::visitFMA(SDNode *N) {
8216 SDValue N0 = N->getOperand(0);
8217 SDValue N1 = N->getOperand(1);
8218 SDValue N2 = N->getOperand(2);
8219 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8220 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8221 EVT VT = N->getValueType(0);
8223 const TargetOptions &Options = DAG.getTarget().Options;
8225 // Constant fold FMA.
8226 if (isa<ConstantFPSDNode>(N0) &&
8227 isa<ConstantFPSDNode>(N1) &&
8228 isa<ConstantFPSDNode>(N2)) {
8229 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8232 if (Options.UnsafeFPMath) {
8233 if (N0CFP && N0CFP->isZero())
8235 if (N1CFP && N1CFP->isZero())
8238 if (N0CFP && N0CFP->isExactlyValue(1.0))
8239 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8240 if (N1CFP && N1CFP->isExactlyValue(1.0))
8241 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8243 // Canonicalize (fma c, x, y) -> (fma x, c, y)
8244 if (N0CFP && !N1CFP)
8245 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8247 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8248 if (Options.UnsafeFPMath && N1CFP &&
8249 N2.getOpcode() == ISD::FMUL &&
8250 N0 == N2.getOperand(0) &&
8251 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8252 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8253 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8257 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8258 if (Options.UnsafeFPMath &&
8259 N0.getOpcode() == ISD::FMUL && N1CFP &&
8260 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8261 return DAG.getNode(ISD::FMA, dl, VT,
8263 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8267 // (fma x, 1, y) -> (fadd x, y)
8268 // (fma x, -1, y) -> (fadd (fneg x), y)
8270 if (N1CFP->isExactlyValue(1.0))
8271 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8273 if (N1CFP->isExactlyValue(-1.0) &&
8274 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8275 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8276 AddToWorklist(RHSNeg.getNode());
8277 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8281 // (fma x, c, x) -> (fmul x, (c+1))
8282 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8283 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8284 DAG.getNode(ISD::FADD, dl, VT,
8285 N1, DAG.getConstantFP(1.0, dl, VT)));
8287 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8288 if (Options.UnsafeFPMath && N1CFP &&
8289 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8290 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8291 DAG.getNode(ISD::FADD, dl, VT,
8292 N1, DAG.getConstantFP(-1.0, dl, VT)));
8298 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8300 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8301 // Notice that this is not always beneficial. One reason is different target
8302 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8303 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8304 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8305 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8306 if (!DAG.getTarget().Options.UnsafeFPMath)
8309 // Skip if current node is a reciprocal.
8310 SDValue N0 = N->getOperand(0);
8311 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8312 if (N0CFP && N0CFP->isExactlyValue(1.0))
8315 // Exit early if the target does not want this transform or if there can't
8316 // possibly be enough uses of the divisor to make the transform worthwhile.
8317 SDValue N1 = N->getOperand(1);
8318 unsigned MinUses = TLI.combineRepeatedFPDivisors();
8319 if (!MinUses || N1->use_size() < MinUses)
8322 // Find all FDIV users of the same divisor.
8323 // Use a set because duplicates may be present in the user list.
8324 SetVector<SDNode *> Users;
8325 for (auto *U : N1->uses())
8326 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8329 // Now that we have the actual number of divisor uses, make sure it meets
8330 // the minimum threshold specified by the target.
8331 if (Users.size() < MinUses)
8334 EVT VT = N->getValueType(0);
8336 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8337 // FIXME: This optimization requires some level of fast-math, so the
8338 // created reciprocal node should at least have the 'allowReciprocal'
8339 // fast-math-flag set.
8340 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8342 // Dividend / Divisor -> Dividend * Reciprocal
8343 for (auto *U : Users) {
8344 SDValue Dividend = U->getOperand(0);
8345 if (Dividend != FPOne) {
8346 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8348 CombineTo(U, NewNode);
8349 } else if (U != Reciprocal.getNode()) {
8350 // In the absence of fast-math-flags, this user node is always the
8351 // same node as Reciprocal, but with FMF they may be different nodes.
8352 CombineTo(U, Reciprocal);
8355 return SDValue(N, 0); // N was replaced.
8358 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8359 SDValue N0 = N->getOperand(0);
8360 SDValue N1 = N->getOperand(1);
8361 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8362 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8363 EVT VT = N->getValueType(0);
8365 const TargetOptions &Options = DAG.getTarget().Options;
8369 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8372 // fold (fdiv c1, c2) -> c1/c2
8374 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8376 if (Options.UnsafeFPMath) {
8377 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8379 // Compute the reciprocal 1.0 / c2.
8380 APFloat N1APF = N1CFP->getValueAPF();
8381 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8382 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8383 // Only do the transform if the reciprocal is a legal fp immediate that
8384 // isn't too nasty (eg NaN, denormal, ...).
8385 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8386 (!LegalOperations ||
8387 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8388 // backend)... we should handle this gracefully after Legalize.
8389 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8390 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8391 TLI.isFPImmLegal(Recip, VT)))
8392 return DAG.getNode(ISD::FMUL, DL, VT, N0,
8393 DAG.getConstantFP(Recip, DL, VT));
8396 // If this FDIV is part of a reciprocal square root, it may be folded
8397 // into a target-specific square root estimate instruction.
8398 if (N1.getOpcode() == ISD::FSQRT) {
8399 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8400 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8402 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8403 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8404 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8405 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8406 AddToWorklist(RV.getNode());
8407 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8409 } else if (N1.getOpcode() == ISD::FP_ROUND &&
8410 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8411 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8412 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8413 AddToWorklist(RV.getNode());
8414 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8416 } else if (N1.getOpcode() == ISD::FMUL) {
8417 // Look through an FMUL. Even though this won't remove the FDIV directly,
8418 // it's still worthwhile to get rid of the FSQRT if possible.
8421 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8422 SqrtOp = N1.getOperand(0);
8423 OtherOp = N1.getOperand(1);
8424 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8425 SqrtOp = N1.getOperand(1);
8426 OtherOp = N1.getOperand(0);
8428 if (SqrtOp.getNode()) {
8429 // We found a FSQRT, so try to make this fold:
8430 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8431 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8432 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8433 AddToWorklist(RV.getNode());
8434 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8439 // Fold into a reciprocal estimate and multiply instead of a real divide.
8440 if (SDValue RV = BuildReciprocalEstimate(N1)) {
8441 AddToWorklist(RV.getNode());
8442 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8446 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8447 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8448 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8449 // Both can be negated for free, check to see if at least one is cheaper
8451 if (LHSNeg == 2 || RHSNeg == 2)
8452 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8453 GetNegatedExpression(N0, DAG, LegalOperations),
8454 GetNegatedExpression(N1, DAG, LegalOperations));
8458 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8459 return CombineRepeatedDivisors;
8464 SDValue DAGCombiner::visitFREM(SDNode *N) {
8465 SDValue N0 = N->getOperand(0);
8466 SDValue N1 = N->getOperand(1);
8467 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8468 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8469 EVT VT = N->getValueType(0);
8471 // fold (frem c1, c2) -> fmod(c1,c2)
8473 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8478 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8479 if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8482 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8483 SDValue RV = BuildRsqrtEstimate(N->getOperand(0));
8487 EVT VT = RV.getValueType();
8489 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8490 AddToWorklist(RV.getNode());
8492 // Unfortunately, RV is now NaN if the input was exactly 0.
8493 // Select out this case and force the answer to 0.
8494 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8495 EVT CCVT = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8496 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8497 AddToWorklist(ZeroCmp.getNode());
8498 AddToWorklist(RV.getNode());
8500 return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8504 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8505 SDValue N0 = N->getOperand(0);
8506 SDValue N1 = N->getOperand(1);
8507 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8508 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8509 EVT VT = N->getValueType(0);
8511 if (N0CFP && N1CFP) // Constant fold
8512 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8515 const APFloat& V = N1CFP->getValueAPF();
8516 // copysign(x, c1) -> fabs(x) iff ispos(c1)
8517 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8518 if (!V.isNegative()) {
8519 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8520 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8522 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8523 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8524 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8528 // copysign(fabs(x), y) -> copysign(x, y)
8529 // copysign(fneg(x), y) -> copysign(x, y)
8530 // copysign(copysign(x,z), y) -> copysign(x, y)
8531 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8532 N0.getOpcode() == ISD::FCOPYSIGN)
8533 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8534 N0.getOperand(0), N1);
8536 // copysign(x, abs(y)) -> abs(x)
8537 if (N1.getOpcode() == ISD::FABS)
8538 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8540 // copysign(x, copysign(y,z)) -> copysign(x, z)
8541 if (N1.getOpcode() == ISD::FCOPYSIGN)
8542 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8543 N0, N1.getOperand(1));
8545 // copysign(x, fp_extend(y)) -> copysign(x, y)
8546 // copysign(x, fp_round(y)) -> copysign(x, y)
8547 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8548 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8549 N0, N1.getOperand(0));
8554 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8555 SDValue N0 = N->getOperand(0);
8556 EVT VT = N->getValueType(0);
8557 EVT OpVT = N0.getValueType();
8559 // fold (sint_to_fp c1) -> c1fp
8560 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8561 // ...but only if the target supports immediate floating-point values
8562 (!LegalOperations ||
8563 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8564 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8566 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8567 // but UINT_TO_FP is legal on this target, try to convert.
8568 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8569 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8570 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8571 if (DAG.SignBitIsZero(N0))
8572 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8575 // The next optimizations are desirable only if SELECT_CC can be lowered.
8576 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8577 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8578 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8580 (!LegalOperations ||
8581 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8584 { N0.getOperand(0), N0.getOperand(1),
8585 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8587 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8590 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8591 // (select_cc x, y, 1.0, 0.0,, cc)
8592 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8593 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8594 (!LegalOperations ||
8595 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8598 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8599 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8600 N0.getOperand(0).getOperand(2) };
8601 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8608 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8609 SDValue N0 = N->getOperand(0);
8610 EVT VT = N->getValueType(0);
8611 EVT OpVT = N0.getValueType();
8613 // fold (uint_to_fp c1) -> c1fp
8614 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8615 // ...but only if the target supports immediate floating-point values
8616 (!LegalOperations ||
8617 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8618 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8620 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8621 // but SINT_TO_FP is legal on this target, try to convert.
8622 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8623 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8624 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8625 if (DAG.SignBitIsZero(N0))
8626 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8629 // The next optimizations are desirable only if SELECT_CC can be lowered.
8630 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8631 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8633 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8634 (!LegalOperations ||
8635 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8638 { N0.getOperand(0), N0.getOperand(1),
8639 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8641 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8648 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8649 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8650 SDValue N0 = N->getOperand(0);
8651 EVT VT = N->getValueType(0);
8653 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8656 SDValue Src = N0.getOperand(0);
8657 EVT SrcVT = Src.getValueType();
8658 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8659 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8661 // We can safely assume the conversion won't overflow the output range,
8662 // because (for example) (uint8_t)18293.f is undefined behavior.
8664 // Since we can assume the conversion won't overflow, our decision as to
8665 // whether the input will fit in the float should depend on the minimum
8666 // of the input range and output range.
8668 // This means this is also safe for a signed input and unsigned output, since
8669 // a negative input would lead to undefined behavior.
8670 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8671 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8672 unsigned ActualSize = std::min(InputSize, OutputSize);
8673 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8675 // We can only fold away the float conversion if the input range can be
8676 // represented exactly in the float range.
8677 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8678 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8679 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8681 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8683 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8684 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8687 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8692 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8693 SDValue N0 = N->getOperand(0);
8694 EVT VT = N->getValueType(0);
8696 // fold (fp_to_sint c1fp) -> c1
8697 if (isConstantFPBuildVectorOrConstantFP(N0))
8698 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8700 return FoldIntToFPToInt(N, DAG);
8703 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8704 SDValue N0 = N->getOperand(0);
8705 EVT VT = N->getValueType(0);
8707 // fold (fp_to_uint c1fp) -> c1
8708 if (isConstantFPBuildVectorOrConstantFP(N0))
8709 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8711 return FoldIntToFPToInt(N, DAG);
8714 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8715 SDValue N0 = N->getOperand(0);
8716 SDValue N1 = N->getOperand(1);
8717 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8718 EVT VT = N->getValueType(0);
8720 // fold (fp_round c1fp) -> c1fp
8722 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8724 // fold (fp_round (fp_extend x)) -> x
8725 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8726 return N0.getOperand(0);
8728 // fold (fp_round (fp_round x)) -> (fp_round x)
8729 if (N0.getOpcode() == ISD::FP_ROUND) {
8730 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8731 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8732 // If the first fp_round isn't a value preserving truncation, it might
8733 // introduce a tie in the second fp_round, that wouldn't occur in the
8734 // single-step fp_round we want to fold to.
8735 // In other words, double rounding isn't the same as rounding.
8736 // Also, this is a value preserving truncation iff both fp_round's are.
8737 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8739 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8740 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8744 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8745 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8746 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8747 N0.getOperand(0), N1);
8748 AddToWorklist(Tmp.getNode());
8749 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8750 Tmp, N0.getOperand(1));
8756 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8757 SDValue N0 = N->getOperand(0);
8758 EVT VT = N->getValueType(0);
8759 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8760 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8762 // fold (fp_round_inreg c1fp) -> c1fp
8763 if (N0CFP && isTypeLegal(EVT)) {
8765 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8766 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8772 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8773 SDValue N0 = N->getOperand(0);
8774 EVT VT = N->getValueType(0);
8776 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8777 if (N->hasOneUse() &&
8778 N->use_begin()->getOpcode() == ISD::FP_ROUND)
8781 // fold (fp_extend c1fp) -> c1fp
8782 if (isConstantFPBuildVectorOrConstantFP(N0))
8783 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8785 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8786 if (N0.getOpcode() == ISD::FP16_TO_FP &&
8787 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8788 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8790 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8792 if (N0.getOpcode() == ISD::FP_ROUND
8793 && N0.getNode()->getConstantOperandVal(1) == 1) {
8794 SDValue In = N0.getOperand(0);
8795 if (In.getValueType() == VT) return In;
8796 if (VT.bitsLT(In.getValueType()))
8797 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8798 In, N0.getOperand(1));
8799 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8802 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8803 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8804 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8805 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8806 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8808 LN0->getBasePtr(), N0.getValueType(),
8809 LN0->getMemOperand());
8810 CombineTo(N, ExtLoad);
8811 CombineTo(N0.getNode(),
8812 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8813 N0.getValueType(), ExtLoad,
8814 DAG.getIntPtrConstant(1, SDLoc(N0))),
8815 ExtLoad.getValue(1));
8816 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8822 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8823 SDValue N0 = N->getOperand(0);
8824 EVT VT = N->getValueType(0);
8826 // fold (fceil c1) -> fceil(c1)
8827 if (isConstantFPBuildVectorOrConstantFP(N0))
8828 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8833 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8834 SDValue N0 = N->getOperand(0);
8835 EVT VT = N->getValueType(0);
8837 // fold (ftrunc c1) -> ftrunc(c1)
8838 if (isConstantFPBuildVectorOrConstantFP(N0))
8839 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8844 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8845 SDValue N0 = N->getOperand(0);
8846 EVT VT = N->getValueType(0);
8848 // fold (ffloor c1) -> ffloor(c1)
8849 if (isConstantFPBuildVectorOrConstantFP(N0))
8850 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8855 // FIXME: FNEG and FABS have a lot in common; refactor.
8856 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8857 SDValue N0 = N->getOperand(0);
8858 EVT VT = N->getValueType(0);
8860 // Constant fold FNEG.
8861 if (isConstantFPBuildVectorOrConstantFP(N0))
8862 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8864 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8865 &DAG.getTarget().Options))
8866 return GetNegatedExpression(N0, DAG, LegalOperations);
8868 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8869 // constant pool values.
8870 if (!TLI.isFNegFree(VT) &&
8871 N0.getOpcode() == ISD::BITCAST &&
8872 N0.getNode()->hasOneUse()) {
8873 SDValue Int = N0.getOperand(0);
8874 EVT IntVT = Int.getValueType();
8875 if (IntVT.isInteger() && !IntVT.isVector()) {
8877 if (N0.getValueType().isVector()) {
8878 // For a vector, get a mask such as 0x80... per scalar element
8880 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8881 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8883 // For a scalar, just generate 0x80...
8884 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8887 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8888 DAG.getConstant(SignMask, DL0, IntVT));
8889 AddToWorklist(Int.getNode());
8890 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8894 // (fneg (fmul c, x)) -> (fmul -c, x)
8895 if (N0.getOpcode() == ISD::FMUL &&
8896 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
8897 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8899 APFloat CVal = CFP1->getValueAPF();
8901 if (Level >= AfterLegalizeDAG &&
8902 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8903 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8905 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8906 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8913 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8914 SDValue N0 = N->getOperand(0);
8915 SDValue N1 = N->getOperand(1);
8916 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8917 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8919 if (N0CFP && N1CFP) {
8920 const APFloat &C0 = N0CFP->getValueAPF();
8921 const APFloat &C1 = N1CFP->getValueAPF();
8922 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8926 EVT VT = N->getValueType(0);
8927 // Canonicalize to constant on RHS.
8928 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8934 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8935 SDValue N0 = N->getOperand(0);
8936 SDValue N1 = N->getOperand(1);
8937 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8938 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8940 if (N0CFP && N1CFP) {
8941 const APFloat &C0 = N0CFP->getValueAPF();
8942 const APFloat &C1 = N1CFP->getValueAPF();
8943 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8947 EVT VT = N->getValueType(0);
8948 // Canonicalize to constant on RHS.
8949 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8955 SDValue DAGCombiner::visitFABS(SDNode *N) {
8956 SDValue N0 = N->getOperand(0);
8957 EVT VT = N->getValueType(0);
8959 // fold (fabs c1) -> fabs(c1)
8960 if (isConstantFPBuildVectorOrConstantFP(N0))
8961 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8963 // fold (fabs (fabs x)) -> (fabs x)
8964 if (N0.getOpcode() == ISD::FABS)
8965 return N->getOperand(0);
8967 // fold (fabs (fneg x)) -> (fabs x)
8968 // fold (fabs (fcopysign x, y)) -> (fabs x)
8969 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8970 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8972 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8973 // constant pool values.
8974 if (!TLI.isFAbsFree(VT) &&
8975 N0.getOpcode() == ISD::BITCAST &&
8976 N0.getNode()->hasOneUse()) {
8977 SDValue Int = N0.getOperand(0);
8978 EVT IntVT = Int.getValueType();
8979 if (IntVT.isInteger() && !IntVT.isVector()) {
8981 if (N0.getValueType().isVector()) {
8982 // For a vector, get a mask such as 0x7f... per scalar element
8984 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8985 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8987 // For a scalar, just generate 0x7f...
8988 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8991 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8992 DAG.getConstant(SignMask, DL, IntVT));
8993 AddToWorklist(Int.getNode());
8994 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
9001 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9002 SDValue Chain = N->getOperand(0);
9003 SDValue N1 = N->getOperand(1);
9004 SDValue N2 = N->getOperand(2);
9006 // If N is a constant we could fold this into a fallthrough or unconditional
9007 // branch. However that doesn't happen very often in normal code, because
9008 // Instcombine/SimplifyCFG should have handled the available opportunities.
9009 // If we did this folding here, it would be necessary to update the
9010 // MachineBasicBlock CFG, which is awkward.
9012 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9014 if (N1.getOpcode() == ISD::SETCC &&
9015 TLI.isOperationLegalOrCustom(ISD::BR_CC,
9016 N1.getOperand(0).getValueType())) {
9017 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9018 Chain, N1.getOperand(2),
9019 N1.getOperand(0), N1.getOperand(1), N2);
9022 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9023 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9024 (N1.getOperand(0).hasOneUse() &&
9025 N1.getOperand(0).getOpcode() == ISD::SRL))) {
9026 SDNode *Trunc = nullptr;
9027 if (N1.getOpcode() == ISD::TRUNCATE) {
9028 // Look pass the truncate.
9029 Trunc = N1.getNode();
9030 N1 = N1.getOperand(0);
9033 // Match this pattern so that we can generate simpler code:
9036 // %b = and i32 %a, 2
9037 // %c = srl i32 %b, 1
9038 // brcond i32 %c ...
9043 // %b = and i32 %a, 2
9044 // %c = setcc eq %b, 0
9047 // This applies only when the AND constant value has one bit set and the
9048 // SRL constant is equal to the log2 of the AND constant. The back-end is
9049 // smart enough to convert the result into a TEST/JMP sequence.
9050 SDValue Op0 = N1.getOperand(0);
9051 SDValue Op1 = N1.getOperand(1);
9053 if (Op0.getOpcode() == ISD::AND &&
9054 Op1.getOpcode() == ISD::Constant) {
9055 SDValue AndOp1 = Op0.getOperand(1);
9057 if (AndOp1.getOpcode() == ISD::Constant) {
9058 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9060 if (AndConst.isPowerOf2() &&
9061 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9065 getSetCCResultType(Op0.getValueType()),
9066 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9069 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9070 MVT::Other, Chain, SetCC, N2);
9071 // Don't add the new BRCond into the worklist or else SimplifySelectCC
9072 // will convert it back to (X & C1) >> C2.
9073 CombineTo(N, NewBRCond, false);
9074 // Truncate is dead.
9076 deleteAndRecombine(Trunc);
9077 // Replace the uses of SRL with SETCC
9078 WorklistRemover DeadNodes(*this);
9079 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9080 deleteAndRecombine(N1.getNode());
9081 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9087 // Restore N1 if the above transformation doesn't match.
9088 N1 = N->getOperand(1);
9091 // Transform br(xor(x, y)) -> br(x != y)
9092 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9093 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9094 SDNode *TheXor = N1.getNode();
9095 SDValue Op0 = TheXor->getOperand(0);
9096 SDValue Op1 = TheXor->getOperand(1);
9097 if (Op0.getOpcode() == Op1.getOpcode()) {
9098 // Avoid missing important xor optimizations.
9099 if (SDValue Tmp = visitXOR(TheXor)) {
9100 if (Tmp.getNode() != TheXor) {
9101 DEBUG(dbgs() << "\nReplacing.8 ";
9103 dbgs() << "\nWith: ";
9104 Tmp.getNode()->dump(&DAG);
9106 WorklistRemover DeadNodes(*this);
9107 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9108 deleteAndRecombine(TheXor);
9109 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9110 MVT::Other, Chain, Tmp, N2);
9113 // visitXOR has changed XOR's operands or replaced the XOR completely,
9115 return SDValue(N, 0);
9119 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9121 if (isOneConstant(Op0) && Op0.hasOneUse() &&
9122 Op0.getOpcode() == ISD::XOR) {
9123 TheXor = Op0.getNode();
9127 EVT SetCCVT = N1.getValueType();
9129 SetCCVT = getSetCCResultType(SetCCVT);
9130 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9133 Equal ? ISD::SETEQ : ISD::SETNE);
9134 // Replace the uses of XOR with SETCC
9135 WorklistRemover DeadNodes(*this);
9136 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9137 deleteAndRecombine(N1.getNode());
9138 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9139 MVT::Other, Chain, SetCC, N2);
9146 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9148 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9149 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9150 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9152 // If N is a constant we could fold this into a fallthrough or unconditional
9153 // branch. However that doesn't happen very often in normal code, because
9154 // Instcombine/SimplifyCFG should have handled the available opportunities.
9155 // If we did this folding here, it would be necessary to update the
9156 // MachineBasicBlock CFG, which is awkward.
9158 // Use SimplifySetCC to simplify SETCC's.
9159 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9160 CondLHS, CondRHS, CC->get(), SDLoc(N),
9162 if (Simp.getNode()) AddToWorklist(Simp.getNode());
9164 // fold to a simpler setcc
9165 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9166 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9167 N->getOperand(0), Simp.getOperand(2),
9168 Simp.getOperand(0), Simp.getOperand(1),
9174 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9175 /// and that N may be folded in the load / store addressing mode.
9176 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9178 const TargetLowering &TLI) {
9182 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
9183 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9185 VT = LD->getMemoryVT();
9186 AS = LD->getAddressSpace();
9187 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
9188 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9190 VT = ST->getMemoryVT();
9191 AS = ST->getAddressSpace();
9195 TargetLowering::AddrMode AM;
9196 if (N->getOpcode() == ISD::ADD) {
9197 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9200 AM.BaseOffs = Offset->getSExtValue();
9204 } else if (N->getOpcode() == ISD::SUB) {
9205 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9208 AM.BaseOffs = -Offset->getSExtValue();
9215 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9216 VT.getTypeForEVT(*DAG.getContext()), AS);
9219 /// Try turning a load/store into a pre-indexed load/store when the base
9220 /// pointer is an add or subtract and it has other uses besides the load/store.
9221 /// After the transformation, the new indexed load/store has effectively folded
9222 /// the add/subtract in and all of its other uses are redirected to the
9224 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9225 if (Level < AfterLegalizeDAG)
9231 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9232 if (LD->isIndexed())
9234 VT = LD->getMemoryVT();
9235 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9236 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9238 Ptr = LD->getBasePtr();
9239 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9240 if (ST->isIndexed())
9242 VT = ST->getMemoryVT();
9243 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9244 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9246 Ptr = ST->getBasePtr();
9252 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9253 // out. There is no reason to make this a preinc/predec.
9254 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9255 Ptr.getNode()->hasOneUse())
9258 // Ask the target to do addressing mode selection.
9261 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9262 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9265 // Backends without true r+i pre-indexed forms may need to pass a
9266 // constant base with a variable offset so that constant coercion
9267 // will work with the patterns in canonical form.
9268 bool Swapped = false;
9269 if (isa<ConstantSDNode>(BasePtr)) {
9270 std::swap(BasePtr, Offset);
9274 // Don't create a indexed load / store with zero offset.
9275 if (isNullConstant(Offset))
9278 // Try turning it into a pre-indexed load / store except when:
9279 // 1) The new base ptr is a frame index.
9280 // 2) If N is a store and the new base ptr is either the same as or is a
9281 // predecessor of the value being stored.
9282 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9283 // that would create a cycle.
9284 // 4) All uses are load / store ops that use it as old base ptr.
9286 // Check #1. Preinc'ing a frame index would require copying the stack pointer
9287 // (plus the implicit offset) to a register to preinc anyway.
9288 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9293 SDValue Val = cast<StoreSDNode>(N)->getValue();
9294 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9298 // If the offset is a constant, there may be other adds of constants that
9299 // can be folded with this one. We should do this to avoid having to keep
9300 // a copy of the original base pointer.
9301 SmallVector<SDNode *, 16> OtherUses;
9302 if (isa<ConstantSDNode>(Offset))
9303 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9304 UE = BasePtr.getNode()->use_end();
9306 SDUse &Use = UI.getUse();
9307 // Skip the use that is Ptr and uses of other results from BasePtr's
9308 // node (important for nodes that return multiple results).
9309 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9312 if (Use.getUser()->isPredecessorOf(N))
9315 if (Use.getUser()->getOpcode() != ISD::ADD &&
9316 Use.getUser()->getOpcode() != ISD::SUB) {
9321 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9322 if (!isa<ConstantSDNode>(Op1)) {
9327 // FIXME: In some cases, we can be smarter about this.
9328 if (Op1.getValueType() != Offset.getValueType()) {
9333 OtherUses.push_back(Use.getUser());
9337 std::swap(BasePtr, Offset);
9339 // Now check for #3 and #4.
9340 bool RealUse = false;
9342 // Caches for hasPredecessorHelper
9343 SmallPtrSet<const SDNode *, 32> Visited;
9344 SmallVector<const SDNode *, 16> Worklist;
9346 for (SDNode *Use : Ptr.getNode()->uses()) {
9349 if (N->hasPredecessorHelper(Use, Visited, Worklist))
9352 // If Ptr may be folded in addressing mode of other use, then it's
9353 // not profitable to do this transformation.
9354 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9363 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9364 BasePtr, Offset, AM);
9366 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9367 BasePtr, Offset, AM);
9370 DEBUG(dbgs() << "\nReplacing.4 ";
9372 dbgs() << "\nWith: ";
9373 Result.getNode()->dump(&DAG);
9375 WorklistRemover DeadNodes(*this);
9377 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9378 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9380 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9383 // Finally, since the node is now dead, remove it from the graph.
9384 deleteAndRecombine(N);
9387 std::swap(BasePtr, Offset);
9389 // Replace other uses of BasePtr that can be updated to use Ptr
9390 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9391 unsigned OffsetIdx = 1;
9392 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9394 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9395 BasePtr.getNode() && "Expected BasePtr operand");
9397 // We need to replace ptr0 in the following expression:
9398 // x0 * offset0 + y0 * ptr0 = t0
9400 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9402 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9403 // indexed load/store and the expresion that needs to be re-written.
9405 // Therefore, we have:
9406 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9408 ConstantSDNode *CN =
9409 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9411 APInt Offset0 = CN->getAPIntValue();
9412 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9414 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9415 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9416 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9417 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9419 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9421 APInt CNV = Offset0;
9422 if (X0 < 0) CNV = -CNV;
9423 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9424 else CNV = CNV - Offset1;
9426 SDLoc DL(OtherUses[i]);
9428 // We can now generate the new expression.
9429 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9430 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9432 SDValue NewUse = DAG.getNode(Opcode,
9434 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9435 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9436 deleteAndRecombine(OtherUses[i]);
9439 // Replace the uses of Ptr with uses of the updated base value.
9440 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9441 deleteAndRecombine(Ptr.getNode());
9446 /// Try to combine a load/store with a add/sub of the base pointer node into a
9447 /// post-indexed load/store. The transformation folded the add/subtract into the
9448 /// new indexed load/store effectively and all of its uses are redirected to the
9450 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9451 if (Level < AfterLegalizeDAG)
9457 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9458 if (LD->isIndexed())
9460 VT = LD->getMemoryVT();
9461 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9462 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9464 Ptr = LD->getBasePtr();
9465 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9466 if (ST->isIndexed())
9468 VT = ST->getMemoryVT();
9469 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9470 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9472 Ptr = ST->getBasePtr();
9478 if (Ptr.getNode()->hasOneUse())
9481 for (SDNode *Op : Ptr.getNode()->uses()) {
9483 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9488 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9489 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9490 // Don't create a indexed load / store with zero offset.
9491 if (isNullConstant(Offset))
9494 // Try turning it into a post-indexed load / store except when
9495 // 1) All uses are load / store ops that use it as base ptr (and
9496 // it may be folded as addressing mmode).
9497 // 2) Op must be independent of N, i.e. Op is neither a predecessor
9498 // nor a successor of N. Otherwise, if Op is folded that would
9501 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9505 bool TryNext = false;
9506 for (SDNode *Use : BasePtr.getNode()->uses()) {
9507 if (Use == Ptr.getNode())
9510 // If all the uses are load / store addresses, then don't do the
9512 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9513 bool RealUse = false;
9514 for (SDNode *UseUse : Use->uses()) {
9515 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9530 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9531 SDValue Result = isLoad
9532 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9533 BasePtr, Offset, AM)
9534 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9535 BasePtr, Offset, AM);
9538 DEBUG(dbgs() << "\nReplacing.5 ";
9540 dbgs() << "\nWith: ";
9541 Result.getNode()->dump(&DAG);
9543 WorklistRemover DeadNodes(*this);
9545 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9546 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9548 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9551 // Finally, since the node is now dead, remove it from the graph.
9552 deleteAndRecombine(N);
9554 // Replace the uses of Use with uses of the updated base value.
9555 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9556 Result.getValue(isLoad ? 1 : 0));
9557 deleteAndRecombine(Op);
9566 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9567 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9568 ISD::MemIndexedMode AM = LD->getAddressingMode();
9569 assert(AM != ISD::UNINDEXED);
9570 SDValue BP = LD->getOperand(1);
9571 SDValue Inc = LD->getOperand(2);
9573 // Some backends use TargetConstants for load offsets, but don't expect
9574 // TargetConstants in general ADD nodes. We can convert these constants into
9575 // regular Constants (if the constant is not opaque).
9576 assert((Inc.getOpcode() != ISD::TargetConstant ||
9577 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9578 "Cannot split out indexing using opaque target constants");
9579 if (Inc.getOpcode() == ISD::TargetConstant) {
9580 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9581 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9582 ConstInc->getValueType(0));
9586 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9587 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9590 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9591 LoadSDNode *LD = cast<LoadSDNode>(N);
9592 SDValue Chain = LD->getChain();
9593 SDValue Ptr = LD->getBasePtr();
9595 // If load is not volatile and there are no uses of the loaded value (and
9596 // the updated indexed value in case of indexed loads), change uses of the
9597 // chain value into uses of the chain input (i.e. delete the dead load).
9598 if (!LD->isVolatile()) {
9599 if (N->getValueType(1) == MVT::Other) {
9601 if (!N->hasAnyUseOfValue(0)) {
9602 // It's not safe to use the two value CombineTo variant here. e.g.
9603 // v1, chain2 = load chain1, loc
9604 // v2, chain3 = load chain2, loc
9606 // Now we replace use of chain2 with chain1. This makes the second load
9607 // isomorphic to the one we are deleting, and thus makes this load live.
9608 DEBUG(dbgs() << "\nReplacing.6 ";
9610 dbgs() << "\nWith chain: ";
9611 Chain.getNode()->dump(&DAG);
9613 WorklistRemover DeadNodes(*this);
9614 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9617 deleteAndRecombine(N);
9619 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9623 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9625 // If this load has an opaque TargetConstant offset, then we cannot split
9626 // the indexing into an add/sub directly (that TargetConstant may not be
9627 // valid for a different type of node, and we cannot convert an opaque
9628 // target constant into a regular constant).
9629 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9630 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9632 if (!N->hasAnyUseOfValue(0) &&
9633 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9634 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9636 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9637 Index = SplitIndexingFromLoad(LD);
9638 // Try to fold the base pointer arithmetic into subsequent loads and
9640 AddUsersToWorklist(N);
9642 Index = DAG.getUNDEF(N->getValueType(1));
9643 DEBUG(dbgs() << "\nReplacing.7 ";
9645 dbgs() << "\nWith: ";
9646 Undef.getNode()->dump(&DAG);
9647 dbgs() << " and 2 other values\n");
9648 WorklistRemover DeadNodes(*this);
9649 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9650 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9651 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9652 deleteAndRecombine(N);
9653 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9658 // If this load is directly stored, replace the load value with the stored
9660 // TODO: Handle store large -> read small portion.
9661 // TODO: Handle TRUNCSTORE/LOADEXT
9662 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9663 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9664 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9665 if (PrevST->getBasePtr() == Ptr &&
9666 PrevST->getValue().getValueType() == N->getValueType(0))
9667 return CombineTo(N, Chain.getOperand(1), Chain);
9671 // Try to infer better alignment information than the load already has.
9672 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9673 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9674 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9676 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9677 LD->getValueType(0),
9678 Chain, Ptr, LD->getPointerInfo(),
9680 LD->isVolatile(), LD->isNonTemporal(),
9681 LD->isInvariant(), Align, LD->getAAInfo());
9682 if (NewLoad.getNode() != N)
9683 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9688 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9689 : DAG.getSubtarget().useAA();
9691 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9692 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9695 if (UseAA && LD->isUnindexed()) {
9696 // Walk up chain skipping non-aliasing memory nodes.
9697 SDValue BetterChain = FindBetterChain(N, Chain);
9699 // If there is a better chain.
9700 if (Chain != BetterChain) {
9703 // Replace the chain to void dependency.
9704 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9705 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9706 BetterChain, Ptr, LD->getMemOperand());
9708 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9709 LD->getValueType(0),
9710 BetterChain, Ptr, LD->getMemoryVT(),
9711 LD->getMemOperand());
9714 // Create token factor to keep old chain connected.
9715 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9716 MVT::Other, Chain, ReplLoad.getValue(1));
9718 // Make sure the new and old chains are cleaned up.
9719 AddToWorklist(Token.getNode());
9721 // Replace uses with load result and token factor. Don't add users
9723 return CombineTo(N, ReplLoad.getValue(0), Token, false);
9727 // Try transforming N to an indexed load.
9728 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9729 return SDValue(N, 0);
9731 // Try to slice up N to more direct loads if the slices are mapped to
9732 // different register banks or pairing can take place.
9734 return SDValue(N, 0);
9740 /// \brief Helper structure used to slice a load in smaller loads.
9741 /// Basically a slice is obtained from the following sequence:
9742 /// Origin = load Ty1, Base
9743 /// Shift = srl Ty1 Origin, CstTy Amount
9744 /// Inst = trunc Shift to Ty2
9746 /// Then, it will be rewriten into:
9747 /// Slice = load SliceTy, Base + SliceOffset
9748 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9750 /// SliceTy is deduced from the number of bits that are actually used to
9752 struct LoadedSlice {
9753 /// \brief Helper structure used to compute the cost of a slice.
9755 /// Are we optimizing for code size.
9760 unsigned CrossRegisterBanksCopies;
9764 Cost(bool ForCodeSize = false)
9765 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9766 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9768 /// \brief Get the cost of one isolated slice.
9769 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9770 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9771 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9772 EVT TruncType = LS.Inst->getValueType(0);
9773 EVT LoadedType = LS.getLoadedType();
9774 if (TruncType != LoadedType &&
9775 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9779 /// \brief Account for slicing gain in the current cost.
9780 /// Slicing provide a few gains like removing a shift or a
9781 /// truncate. This method allows to grow the cost of the original
9782 /// load with the gain from this slice.
9783 void addSliceGain(const LoadedSlice &LS) {
9784 // Each slice saves a truncate.
9785 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9786 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
9787 LS.Inst->getValueType(0)))
9789 // If there is a shift amount, this slice gets rid of it.
9792 // If this slice can merge a cross register bank copy, account for it.
9793 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9794 ++CrossRegisterBanksCopies;
9797 Cost &operator+=(const Cost &RHS) {
9799 Truncates += RHS.Truncates;
9800 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9806 bool operator==(const Cost &RHS) const {
9807 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9808 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9809 ZExts == RHS.ZExts && Shift == RHS.Shift;
9812 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9814 bool operator<(const Cost &RHS) const {
9815 // Assume cross register banks copies are as expensive as loads.
9816 // FIXME: Do we want some more target hooks?
9817 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9818 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9819 // Unless we are optimizing for code size, consider the
9820 // expensive operation first.
9821 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9822 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9823 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9824 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9827 bool operator>(const Cost &RHS) const { return RHS < *this; }
9829 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9831 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9833 // The last instruction that represent the slice. This should be a
9834 // truncate instruction.
9836 // The original load instruction.
9838 // The right shift amount in bits from the original load.
9840 // The DAG from which Origin came from.
9841 // This is used to get some contextual information about legal types, etc.
9844 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9845 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9846 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9848 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9849 /// \return Result is \p BitWidth and has used bits set to 1 and
9850 /// not used bits set to 0.
9851 APInt getUsedBits() const {
9852 // Reproduce the trunc(lshr) sequence:
9853 // - Start from the truncated value.
9854 // - Zero extend to the desired bit width.
9856 assert(Origin && "No original load to compare against.");
9857 unsigned BitWidth = Origin->getValueSizeInBits(0);
9858 assert(Inst && "This slice is not bound to an instruction");
9859 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9860 "Extracted slice is bigger than the whole type!");
9861 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9862 UsedBits.setAllBits();
9863 UsedBits = UsedBits.zext(BitWidth);
9868 /// \brief Get the size of the slice to be loaded in bytes.
9869 unsigned getLoadedSize() const {
9870 unsigned SliceSize = getUsedBits().countPopulation();
9871 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9872 return SliceSize / 8;
9875 /// \brief Get the type that will be loaded for this slice.
9876 /// Note: This may not be the final type for the slice.
9877 EVT getLoadedType() const {
9878 assert(DAG && "Missing context");
9879 LLVMContext &Ctxt = *DAG->getContext();
9880 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9883 /// \brief Get the alignment of the load used for this slice.
9884 unsigned getAlignment() const {
9885 unsigned Alignment = Origin->getAlignment();
9886 unsigned Offset = getOffsetFromBase();
9888 Alignment = MinAlign(Alignment, Alignment + Offset);
9892 /// \brief Check if this slice can be rewritten with legal operations.
9893 bool isLegal() const {
9894 // An invalid slice is not legal.
9895 if (!Origin || !Inst || !DAG)
9898 // Offsets are for indexed load only, we do not handle that.
9899 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9902 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9904 // Check that the type is legal.
9905 EVT SliceType = getLoadedType();
9906 if (!TLI.isTypeLegal(SliceType))
9909 // Check that the load is legal for this type.
9910 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9913 // Check that the offset can be computed.
9914 // 1. Check its type.
9915 EVT PtrType = Origin->getBasePtr().getValueType();
9916 if (PtrType == MVT::Untyped || PtrType.isExtended())
9919 // 2. Check that it fits in the immediate.
9920 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9923 // 3. Check that the computation is legal.
9924 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9927 // Check that the zext is legal if it needs one.
9928 EVT TruncateType = Inst->getValueType(0);
9929 if (TruncateType != SliceType &&
9930 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9936 /// \brief Get the offset in bytes of this slice in the original chunk of
9938 /// \pre DAG != nullptr.
9939 uint64_t getOffsetFromBase() const {
9940 assert(DAG && "Missing context.");
9941 bool IsBigEndian = DAG->getDataLayout().isBigEndian();
9942 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9943 uint64_t Offset = Shift / 8;
9944 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9945 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9946 "The size of the original loaded type is not a multiple of a"
9948 // If Offset is bigger than TySizeInBytes, it means we are loading all
9949 // zeros. This should have been optimized before in the process.
9950 assert(TySizeInBytes > Offset &&
9951 "Invalid shift amount for given loaded size");
9953 Offset = TySizeInBytes - Offset - getLoadedSize();
9957 /// \brief Generate the sequence of instructions to load the slice
9958 /// represented by this object and redirect the uses of this slice to
9959 /// this new sequence of instructions.
9960 /// \pre this->Inst && this->Origin are valid Instructions and this
9961 /// object passed the legal check: LoadedSlice::isLegal returned true.
9962 /// \return The last instruction of the sequence used to load the slice.
9963 SDValue loadSlice() const {
9964 assert(Inst && Origin && "Unable to replace a non-existing slice.");
9965 const SDValue &OldBaseAddr = Origin->getBasePtr();
9966 SDValue BaseAddr = OldBaseAddr;
9967 // Get the offset in that chunk of bytes w.r.t. the endianess.
9968 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9969 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9971 // BaseAddr = BaseAddr + Offset.
9972 EVT ArithType = BaseAddr.getValueType();
9974 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9975 DAG->getConstant(Offset, DL, ArithType));
9978 // Create the type of the loaded slice according to its size.
9979 EVT SliceType = getLoadedType();
9981 // Create the load for the slice.
9982 SDValue LastInst = DAG->getLoad(
9983 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9984 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9985 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9986 // If the final type is not the same as the loaded type, this means that
9987 // we have to pad with zero. Create a zero extend for that.
9988 EVT FinalType = Inst->getValueType(0);
9989 if (SliceType != FinalType)
9991 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9995 /// \brief Check if this slice can be merged with an expensive cross register
9996 /// bank copy. E.g.,
9998 /// f = bitcast i32 i to float
9999 bool canMergeExpensiveCrossRegisterBankCopy() const {
10000 if (!Inst || !Inst->hasOneUse())
10002 SDNode *Use = *Inst->use_begin();
10003 if (Use->getOpcode() != ISD::BITCAST)
10005 assert(DAG && "Missing context");
10006 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10007 EVT ResVT = Use->getValueType(0);
10008 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10009 const TargetRegisterClass *ArgRC =
10010 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10011 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10014 // At this point, we know that we perform a cross-register-bank copy.
10015 // Check if it is expensive.
10016 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10017 // Assume bitcasts are cheap, unless both register classes do not
10018 // explicitly share a common sub class.
10019 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10022 // Check if it will be merged with the load.
10023 // 1. Check the alignment constraint.
10024 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10025 ResVT.getTypeForEVT(*DAG->getContext()));
10027 if (RequiredAlignment > getAlignment())
10030 // 2. Check that the load is a legal operation for that type.
10031 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10034 // 3. Check that we do not have a zext in the way.
10035 if (Inst->getValueType(0) != getLoadedType())
10043 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10044 /// \p UsedBits looks like 0..0 1..1 0..0.
10045 static bool areUsedBitsDense(const APInt &UsedBits) {
10046 // If all the bits are one, this is dense!
10047 if (UsedBits.isAllOnesValue())
10050 // Get rid of the unused bits on the right.
10051 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10052 // Get rid of the unused bits on the left.
10053 if (NarrowedUsedBits.countLeadingZeros())
10054 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10055 // Check that the chunk of bits is completely used.
10056 return NarrowedUsedBits.isAllOnesValue();
10059 /// \brief Check whether or not \p First and \p Second are next to each other
10060 /// in memory. This means that there is no hole between the bits loaded
10061 /// by \p First and the bits loaded by \p Second.
10062 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10063 const LoadedSlice &Second) {
10064 assert(First.Origin == Second.Origin && First.Origin &&
10065 "Unable to match different memory origins.");
10066 APInt UsedBits = First.getUsedBits();
10067 assert((UsedBits & Second.getUsedBits()) == 0 &&
10068 "Slices are not supposed to overlap.");
10069 UsedBits |= Second.getUsedBits();
10070 return areUsedBitsDense(UsedBits);
10073 /// \brief Adjust the \p GlobalLSCost according to the target
10074 /// paring capabilities and the layout of the slices.
10075 /// \pre \p GlobalLSCost should account for at least as many loads as
10076 /// there is in the slices in \p LoadedSlices.
10077 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10078 LoadedSlice::Cost &GlobalLSCost) {
10079 unsigned NumberOfSlices = LoadedSlices.size();
10080 // If there is less than 2 elements, no pairing is possible.
10081 if (NumberOfSlices < 2)
10084 // Sort the slices so that elements that are likely to be next to each
10085 // other in memory are next to each other in the list.
10086 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10087 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10088 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10089 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10091 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10092 // First (resp. Second) is the first (resp. Second) potentially candidate
10093 // to be placed in a paired load.
10094 const LoadedSlice *First = nullptr;
10095 const LoadedSlice *Second = nullptr;
10096 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10097 // Set the beginning of the pair.
10100 Second = &LoadedSlices[CurrSlice];
10102 // If First is NULL, it means we start a new pair.
10103 // Get to the next slice.
10107 EVT LoadedType = First->getLoadedType();
10109 // If the types of the slices are different, we cannot pair them.
10110 if (LoadedType != Second->getLoadedType())
10113 // Check if the target supplies paired loads for this type.
10114 unsigned RequiredAlignment = 0;
10115 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10116 // move to the next pair, this type is hopeless.
10120 // Check if we meet the alignment requirement.
10121 if (RequiredAlignment > First->getAlignment())
10124 // Check that both loads are next to each other in memory.
10125 if (!areSlicesNextToEachOther(*First, *Second))
10128 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10129 --GlobalLSCost.Loads;
10130 // Move to the next pair.
10135 /// \brief Check the profitability of all involved LoadedSlice.
10136 /// Currently, it is considered profitable if there is exactly two
10137 /// involved slices (1) which are (2) next to each other in memory, and
10138 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10140 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10141 /// the elements themselves.
10143 /// FIXME: When the cost model will be mature enough, we can relax
10144 /// constraints (1) and (2).
10145 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10146 const APInt &UsedBits, bool ForCodeSize) {
10147 unsigned NumberOfSlices = LoadedSlices.size();
10148 if (StressLoadSlicing)
10149 return NumberOfSlices > 1;
10152 if (NumberOfSlices != 2)
10156 if (!areUsedBitsDense(UsedBits))
10160 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10161 // The original code has one big load.
10162 OrigCost.Loads = 1;
10163 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10164 const LoadedSlice &LS = LoadedSlices[CurrSlice];
10165 // Accumulate the cost of all the slices.
10166 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10167 GlobalSlicingCost += SliceCost;
10169 // Account as cost in the original configuration the gain obtained
10170 // with the current slices.
10171 OrigCost.addSliceGain(LS);
10174 // If the target supports paired load, adjust the cost accordingly.
10175 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10176 return OrigCost > GlobalSlicingCost;
10179 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10180 /// operations, split it in the various pieces being extracted.
10182 /// This sort of thing is introduced by SROA.
10183 /// This slicing takes care not to insert overlapping loads.
10184 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10185 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10186 if (Level < AfterLegalizeDAG)
10189 LoadSDNode *LD = cast<LoadSDNode>(N);
10190 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10191 !LD->getValueType(0).isInteger())
10194 // Keep track of already used bits to detect overlapping values.
10195 // In that case, we will just abort the transformation.
10196 APInt UsedBits(LD->getValueSizeInBits(0), 0);
10198 SmallVector<LoadedSlice, 4> LoadedSlices;
10200 // Check if this load is used as several smaller chunks of bits.
10201 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10202 // of computation for each trunc.
10203 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10204 UI != UIEnd; ++UI) {
10205 // Skip the uses of the chain.
10206 if (UI.getUse().getResNo() != 0)
10209 SDNode *User = *UI;
10210 unsigned Shift = 0;
10212 // Check if this is a trunc(lshr).
10213 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10214 isa<ConstantSDNode>(User->getOperand(1))) {
10215 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10216 User = *User->use_begin();
10219 // At this point, User is a Truncate, iff we encountered, trunc or
10221 if (User->getOpcode() != ISD::TRUNCATE)
10224 // The width of the type must be a power of 2 and greater than 8-bits.
10225 // Otherwise the load cannot be represented in LLVM IR.
10226 // Moreover, if we shifted with a non-8-bits multiple, the slice
10227 // will be across several bytes. We do not support that.
10228 unsigned Width = User->getValueSizeInBits(0);
10229 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10232 // Build the slice for this chain of computations.
10233 LoadedSlice LS(User, LD, Shift, &DAG);
10234 APInt CurrentUsedBits = LS.getUsedBits();
10236 // Check if this slice overlaps with another.
10237 if ((CurrentUsedBits & UsedBits) != 0)
10239 // Update the bits used globally.
10240 UsedBits |= CurrentUsedBits;
10242 // Check if the new slice would be legal.
10246 // Record the slice.
10247 LoadedSlices.push_back(LS);
10250 // Abort slicing if it does not seem to be profitable.
10251 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10256 // Rewrite each chain to use an independent load.
10257 // By construction, each chain can be represented by a unique load.
10259 // Prepare the argument for the new token factor for all the slices.
10260 SmallVector<SDValue, 8> ArgChains;
10261 for (SmallVectorImpl<LoadedSlice>::const_iterator
10262 LSIt = LoadedSlices.begin(),
10263 LSItEnd = LoadedSlices.end();
10264 LSIt != LSItEnd; ++LSIt) {
10265 SDValue SliceInst = LSIt->loadSlice();
10266 CombineTo(LSIt->Inst, SliceInst, true);
10267 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10268 SliceInst = SliceInst.getOperand(0);
10269 assert(SliceInst->getOpcode() == ISD::LOAD &&
10270 "It takes more than a zext to get to the loaded slice!!");
10271 ArgChains.push_back(SliceInst.getValue(1));
10274 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10276 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10280 /// Check to see if V is (and load (ptr), imm), where the load is having
10281 /// specific bytes cleared out. If so, return the byte size being masked out
10282 /// and the shift amount.
10283 static std::pair<unsigned, unsigned>
10284 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10285 std::pair<unsigned, unsigned> Result(0, 0);
10287 // Check for the structure we're looking for.
10288 if (V->getOpcode() != ISD::AND ||
10289 !isa<ConstantSDNode>(V->getOperand(1)) ||
10290 !ISD::isNormalLoad(V->getOperand(0).getNode()))
10293 // Check the chain and pointer.
10294 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10295 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
10297 // The store should be chained directly to the load or be an operand of a
10299 if (LD == Chain.getNode())
10301 else if (Chain->getOpcode() != ISD::TokenFactor)
10302 return Result; // Fail.
10305 for (const SDValue &ChainOp : Chain->op_values())
10306 if (ChainOp.getNode() == LD) {
10310 if (!isOk) return Result;
10313 // This only handles simple types.
10314 if (V.getValueType() != MVT::i16 &&
10315 V.getValueType() != MVT::i32 &&
10316 V.getValueType() != MVT::i64)
10319 // Check the constant mask. Invert it so that the bits being masked out are
10320 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
10321 // follow the sign bit for uniformity.
10322 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10323 unsigned NotMaskLZ = countLeadingZeros(NotMask);
10324 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
10325 unsigned NotMaskTZ = countTrailingZeros(NotMask);
10326 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
10327 if (NotMaskLZ == 64) return Result; // All zero mask.
10329 // See if we have a continuous run of bits. If so, we have 0*1+0*
10330 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10333 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10334 if (V.getValueType() != MVT::i64 && NotMaskLZ)
10335 NotMaskLZ -= 64-V.getValueSizeInBits();
10337 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10338 switch (MaskedBytes) {
10342 default: return Result; // All one mask, or 5-byte mask.
10345 // Verify that the first bit starts at a multiple of mask so that the access
10346 // is aligned the same as the access width.
10347 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10349 Result.first = MaskedBytes;
10350 Result.second = NotMaskTZ/8;
10355 /// Check to see if IVal is something that provides a value as specified by
10356 /// MaskInfo. If so, replace the specified store with a narrower store of
10357 /// truncated IVal.
10359 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10360 SDValue IVal, StoreSDNode *St,
10362 unsigned NumBytes = MaskInfo.first;
10363 unsigned ByteShift = MaskInfo.second;
10364 SelectionDAG &DAG = DC->getDAG();
10366 // Check to see if IVal is all zeros in the part being masked in by the 'or'
10367 // that uses this. If not, this is not a replacement.
10368 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10369 ByteShift*8, (ByteShift+NumBytes)*8);
10370 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10372 // Check that it is legal on the target to do this. It is legal if the new
10373 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10375 MVT VT = MVT::getIntegerVT(NumBytes*8);
10376 if (!DC->isTypeLegal(VT))
10379 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
10380 // shifted by ByteShift and truncated down to NumBytes.
10383 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10384 DAG.getConstant(ByteShift*8, DL,
10385 DC->getShiftAmountTy(IVal.getValueType())));
10388 // Figure out the offset for the store and the alignment of the access.
10390 unsigned NewAlign = St->getAlignment();
10392 if (DAG.getDataLayout().isLittleEndian())
10393 StOffset = ByteShift;
10395 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10397 SDValue Ptr = St->getBasePtr();
10400 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10401 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10402 NewAlign = MinAlign(NewAlign, StOffset);
10405 // Truncate down to the new size.
10406 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10409 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10410 St->getPointerInfo().getWithOffset(StOffset),
10411 false, false, NewAlign).getNode();
10415 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10416 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10417 /// narrowing the load and store if it would end up being a win for performance
10419 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10420 StoreSDNode *ST = cast<StoreSDNode>(N);
10421 if (ST->isVolatile())
10424 SDValue Chain = ST->getChain();
10425 SDValue Value = ST->getValue();
10426 SDValue Ptr = ST->getBasePtr();
10427 EVT VT = Value.getValueType();
10429 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10432 unsigned Opc = Value.getOpcode();
10434 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10435 // is a byte mask indicating a consecutive number of bytes, check to see if
10436 // Y is known to provide just those bytes. If so, we try to replace the
10437 // load + replace + store sequence with a single (narrower) store, which makes
10439 if (Opc == ISD::OR) {
10440 std::pair<unsigned, unsigned> MaskedLoad;
10441 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10442 if (MaskedLoad.first)
10443 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10444 Value.getOperand(1), ST,this))
10445 return SDValue(NewST, 0);
10447 // Or is commutative, so try swapping X and Y.
10448 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10449 if (MaskedLoad.first)
10450 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10451 Value.getOperand(0), ST,this))
10452 return SDValue(NewST, 0);
10455 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10456 Value.getOperand(1).getOpcode() != ISD::Constant)
10459 SDValue N0 = Value.getOperand(0);
10460 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10461 Chain == SDValue(N0.getNode(), 1)) {
10462 LoadSDNode *LD = cast<LoadSDNode>(N0);
10463 if (LD->getBasePtr() != Ptr ||
10464 LD->getPointerInfo().getAddrSpace() !=
10465 ST->getPointerInfo().getAddrSpace())
10468 // Find the type to narrow it the load / op / store to.
10469 SDValue N1 = Value.getOperand(1);
10470 unsigned BitWidth = N1.getValueSizeInBits();
10471 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10472 if (Opc == ISD::AND)
10473 Imm ^= APInt::getAllOnesValue(BitWidth);
10474 if (Imm == 0 || Imm.isAllOnesValue())
10476 unsigned ShAmt = Imm.countTrailingZeros();
10477 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10478 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10479 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10480 // The narrowing should be profitable, the load/store operation should be
10481 // legal (or custom) and the store size should be equal to the NewVT width.
10482 while (NewBW < BitWidth &&
10483 (NewVT.getStoreSizeInBits() != NewBW ||
10484 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10485 !TLI.isNarrowingProfitable(VT, NewVT))) {
10486 NewBW = NextPowerOf2(NewBW);
10487 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10489 if (NewBW >= BitWidth)
10492 // If the lsb changed does not start at the type bitwidth boundary,
10493 // start at the previous one.
10495 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10496 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10497 std::min(BitWidth, ShAmt + NewBW));
10498 if ((Imm & Mask) == Imm) {
10499 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10500 if (Opc == ISD::AND)
10501 NewImm ^= APInt::getAllOnesValue(NewBW);
10502 uint64_t PtrOff = ShAmt / 8;
10503 // For big endian targets, we need to adjust the offset to the pointer to
10504 // load the correct bytes.
10505 if (DAG.getDataLayout().isBigEndian())
10506 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10508 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10509 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10510 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10513 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10514 Ptr.getValueType(), Ptr,
10515 DAG.getConstant(PtrOff, SDLoc(LD),
10516 Ptr.getValueType()));
10517 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10518 LD->getChain(), NewPtr,
10519 LD->getPointerInfo().getWithOffset(PtrOff),
10520 LD->isVolatile(), LD->isNonTemporal(),
10521 LD->isInvariant(), NewAlign,
10523 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10524 DAG.getConstant(NewImm, SDLoc(Value),
10526 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10528 ST->getPointerInfo().getWithOffset(PtrOff),
10529 false, false, NewAlign);
10531 AddToWorklist(NewPtr.getNode());
10532 AddToWorklist(NewLD.getNode());
10533 AddToWorklist(NewVal.getNode());
10534 WorklistRemover DeadNodes(*this);
10535 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10544 /// For a given floating point load / store pair, if the load value isn't used
10545 /// by any other operations, then consider transforming the pair to integer
10546 /// load / store operations if the target deems the transformation profitable.
10547 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10548 StoreSDNode *ST = cast<StoreSDNode>(N);
10549 SDValue Chain = ST->getChain();
10550 SDValue Value = ST->getValue();
10551 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10552 Value.hasOneUse() &&
10553 Chain == SDValue(Value.getNode(), 1)) {
10554 LoadSDNode *LD = cast<LoadSDNode>(Value);
10555 EVT VT = LD->getMemoryVT();
10556 if (!VT.isFloatingPoint() ||
10557 VT != ST->getMemoryVT() ||
10558 LD->isNonTemporal() ||
10559 ST->isNonTemporal() ||
10560 LD->getPointerInfo().getAddrSpace() != 0 ||
10561 ST->getPointerInfo().getAddrSpace() != 0)
10564 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10565 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10566 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10567 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10568 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10571 unsigned LDAlign = LD->getAlignment();
10572 unsigned STAlign = ST->getAlignment();
10573 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10574 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10575 if (LDAlign < ABIAlign || STAlign < ABIAlign)
10578 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10579 LD->getChain(), LD->getBasePtr(),
10580 LD->getPointerInfo(),
10581 false, false, false, LDAlign);
10583 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10584 NewLD, ST->getBasePtr(),
10585 ST->getPointerInfo(),
10586 false, false, STAlign);
10588 AddToWorklist(NewLD.getNode());
10589 AddToWorklist(NewST.getNode());
10590 WorklistRemover DeadNodes(*this);
10591 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10600 /// Helper struct to parse and store a memory address as base + index + offset.
10601 /// We ignore sign extensions when it is safe to do so.
10602 /// The following two expressions are not equivalent. To differentiate we need
10603 /// to store whether there was a sign extension involved in the index
10605 /// (load (i64 add (i64 copyfromreg %c)
10606 /// (i64 signextend (add (i8 load %index)
10610 /// (load (i64 add (i64 copyfromreg %c)
10611 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
10613 struct BaseIndexOffset {
10617 bool IsIndexSignExt;
10619 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10621 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10622 bool IsIndexSignExt) :
10623 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10625 bool equalBaseIndex(const BaseIndexOffset &Other) {
10626 return Other.Base == Base && Other.Index == Index &&
10627 Other.IsIndexSignExt == IsIndexSignExt;
10630 /// Parses tree in Ptr for base, index, offset addresses.
10631 static BaseIndexOffset match(SDValue Ptr) {
10632 bool IsIndexSignExt = false;
10634 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10635 // instruction, then it could be just the BASE or everything else we don't
10636 // know how to handle. Just use Ptr as BASE and give up.
10637 if (Ptr->getOpcode() != ISD::ADD)
10638 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10640 // We know that we have at least an ADD instruction. Try to pattern match
10641 // the simple case of BASE + OFFSET.
10642 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10643 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10644 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10648 // Inside a loop the current BASE pointer is calculated using an ADD and a
10649 // MUL instruction. In this case Ptr is the actual BASE pointer.
10650 // (i64 add (i64 %array_ptr)
10651 // (i64 mul (i64 %induction_var)
10652 // (i64 %element_size)))
10653 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10654 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10656 // Look at Base + Index + Offset cases.
10657 SDValue Base = Ptr->getOperand(0);
10658 SDValue IndexOffset = Ptr->getOperand(1);
10660 // Skip signextends.
10661 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10662 IndexOffset = IndexOffset->getOperand(0);
10663 IsIndexSignExt = true;
10666 // Either the case of Base + Index (no offset) or something else.
10667 if (IndexOffset->getOpcode() != ISD::ADD)
10668 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10670 // Now we have the case of Base + Index + offset.
10671 SDValue Index = IndexOffset->getOperand(0);
10672 SDValue Offset = IndexOffset->getOperand(1);
10674 if (!isa<ConstantSDNode>(Offset))
10675 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10677 // Ignore signextends.
10678 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10679 Index = Index->getOperand(0);
10680 IsIndexSignExt = true;
10681 } else IsIndexSignExt = false;
10683 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10684 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10689 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10691 ArrayRef<MemOpLink> Stores,
10693 SmallVector<SDValue, 8> BuildVector;
10695 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I)
10696 BuildVector.push_back(cast<StoreSDNode>(Stores[I].MemNode)->getValue());
10698 return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10701 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10702 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10703 unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10704 // Make sure we have something to merge.
10708 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10709 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10710 unsigned LatestNodeUsed = 0;
10712 for (unsigned i=0; i < NumElem; ++i) {
10713 // Find a chain for the new wide-store operand. Notice that some
10714 // of the store nodes that we found may not be selected for inclusion
10715 // in the wide store. The chain we use needs to be the chain of the
10716 // latest store node which is *used* and replaced by the wide store.
10717 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10718 LatestNodeUsed = i;
10721 // The latest Node in the DAG.
10722 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10723 SDLoc DL(StoreNodes[0].MemNode);
10727 // Find a legal type for the vector store.
10728 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10729 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10730 if (IsConstantSrc) {
10731 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Ty);
10733 SmallVector<SDValue, 8> Ops;
10734 for (unsigned i = 0; i < NumElem ; ++i) {
10735 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10736 SDValue Val = St->getValue();
10737 // All of the operands of a BUILD_VECTOR must have the same type.
10738 if (Val.getValueType() != MemVT)
10740 Ops.push_back(Val);
10743 // Build the extracted vector elements back into a vector.
10744 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10747 // We should always use a vector store when merging extracted vector
10748 // elements, so this path implies a store of constants.
10749 assert(IsConstantSrc && "Merged vector elements should use vector store");
10751 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
10752 APInt StoreInt(SizeInBits, 0);
10754 // Construct a single integer constant which is made of the smaller
10755 // constant inputs.
10756 bool IsLE = DAG.getDataLayout().isLittleEndian();
10757 for (unsigned i = 0; i < NumElem ; ++i) {
10758 unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10759 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10760 SDValue Val = St->getValue();
10761 StoreInt <<= ElementSizeBytes * 8;
10762 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10763 StoreInt |= C->getAPIntValue().zext(SizeInBits);
10764 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10765 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
10767 llvm_unreachable("Invalid constant element type");
10771 // Create the new Load and Store operations.
10772 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
10773 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10776 SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10777 FirstInChain->getBasePtr(),
10778 FirstInChain->getPointerInfo(),
10780 FirstInChain->getAlignment());
10782 // Replace the last store with the new store
10783 CombineTo(LatestOp, NewStore);
10784 // Erase all other stores.
10785 for (unsigned i = 0; i < NumElem ; ++i) {
10786 if (StoreNodes[i].MemNode == LatestOp)
10788 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10789 // ReplaceAllUsesWith will replace all uses that existed when it was
10790 // called, but graph optimizations may cause new ones to appear. For
10791 // example, the case in pr14333 looks like
10793 // St's chain -> St -> another store -> X
10795 // And the only difference from St to the other store is the chain.
10796 // When we change it's chain to be St's chain they become identical,
10797 // get CSEed and the net result is that X is now a use of St.
10798 // Since we know that St is redundant, just iterate.
10799 while (!St->use_empty())
10800 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10801 deleteAndRecombine(St);
10807 void DAGCombiner::getStoreMergeAndAliasCandidates(
10808 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
10809 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
10810 // This holds the base pointer, index, and the offset in bytes from the base
10812 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10814 // We must have a base and an offset.
10815 if (!BasePtr.Base.getNode())
10818 // Do not handle stores to undef base pointers.
10819 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10822 // Walk up the chain and look for nodes with offsets from the same
10823 // base pointer. Stop when reaching an instruction with a different kind
10824 // or instruction which has a different base pointer.
10825 EVT MemVT = St->getMemoryVT();
10827 StoreSDNode *Index = St;
10829 // If the chain has more than one use, then we can't reorder the mem ops.
10830 if (Index != St && !SDValue(Index, 0)->hasOneUse())
10833 // Find the base pointer and offset for this memory node.
10834 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10836 // Check that the base pointer is the same as the original one.
10837 if (!Ptr.equalBaseIndex(BasePtr))
10840 // The memory operands must not be volatile.
10841 if (Index->isVolatile() || Index->isIndexed())
10845 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10846 if (St->isTruncatingStore())
10849 // The stored memory type must be the same.
10850 if (Index->getMemoryVT() != MemVT)
10853 // We found a potential memory operand to merge.
10854 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10856 // Find the next memory operand in the chain. If the next operand in the
10857 // chain is a store then move up and continue the scan with the next
10858 // memory operand. If the next operand is a load save it and use alias
10859 // information to check if it interferes with anything.
10860 SDNode *NextInChain = Index->getChain().getNode();
10862 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10863 // We found a store node. Use it for the next iteration.
10866 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10867 if (Ldn->isVolatile()) {
10872 // Save the load node for later. Continue the scan.
10873 AliasLoadNodes.push_back(Ldn);
10874 NextInChain = Ldn->getChain().getNode();
10884 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10885 if (OptLevel == CodeGenOpt::None)
10888 EVT MemVT = St->getMemoryVT();
10889 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10890 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10891 Attribute::NoImplicitFloat);
10893 // This function cannot currently deal with non-byte-sized memory sizes.
10894 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10897 // Don't merge vectors into wider inputs.
10898 if (MemVT.isVector() || !MemVT.isSimple())
10901 // Perform an early exit check. Do not bother looking at stored values that
10902 // are not constants, loads, or extracted vector elements.
10903 SDValue StoredVal = St->getValue();
10904 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10905 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10906 isa<ConstantFPSDNode>(StoredVal);
10907 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10909 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10912 // Only look at ends of store sequences.
10913 SDValue Chain = SDValue(St, 0);
10914 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10917 // Save the LoadSDNodes that we find in the chain.
10918 // We need to make sure that these nodes do not interfere with
10919 // any of the store nodes.
10920 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10922 // Save the StoreSDNodes that we find in the chain.
10923 SmallVector<MemOpLink, 8> StoreNodes;
10925 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
10927 // Check if there is anything to merge.
10928 if (StoreNodes.size() < 2)
10931 // Sort the memory operands according to their distance from the base pointer.
10932 std::sort(StoreNodes.begin(), StoreNodes.end(),
10933 [](MemOpLink LHS, MemOpLink RHS) {
10934 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10935 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10936 LHS.SequenceNum > RHS.SequenceNum);
10939 // Scan the memory operations on the chain and find the first non-consecutive
10940 // store memory address.
10941 unsigned LastConsecutiveStore = 0;
10942 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10943 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10945 // Check that the addresses are consecutive starting from the second
10946 // element in the list of stores.
10948 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10949 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10953 bool Alias = false;
10954 // Check if this store interferes with any of the loads that we found.
10955 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10956 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10960 // We found a load that alias with this store. Stop the sequence.
10964 // Mark this node as useful.
10965 LastConsecutiveStore = i;
10968 // The node with the lowest store address.
10969 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10970 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
10971 unsigned FirstStoreAlign = FirstInChain->getAlignment();
10972 LLVMContext &Context = *DAG.getContext();
10973 const DataLayout &DL = DAG.getDataLayout();
10975 // Store the constants into memory as one consecutive store.
10976 if (IsConstantSrc) {
10977 unsigned LastLegalType = 0;
10978 unsigned LastLegalVectorType = 0;
10979 bool NonZero = false;
10980 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10981 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10982 SDValue StoredVal = St->getValue();
10984 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10985 NonZero |= !C->isNullValue();
10986 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10987 NonZero |= !C->getConstantFPValue()->isNullValue();
10993 // Find a legal type for the constant store.
10994 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
10995 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
10996 if (TLI.isTypeLegal(StoreTy) &&
10997 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
10998 FirstStoreAlign)) {
10999 LastLegalType = i+1;
11000 // Or check whether a truncstore is legal.
11001 } else if (TLI.getTypeAction(Context, StoreTy) ==
11002 TargetLowering::TypePromoteInteger) {
11003 EVT LegalizedStoredValueTy =
11004 TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11005 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11006 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11007 FirstStoreAS, FirstStoreAlign)) {
11008 LastLegalType = i + 1;
11012 // Find a legal type for the vector store.
11013 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11014 if (TLI.isTypeLegal(Ty) &&
11015 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11016 FirstStoreAlign)) {
11017 LastLegalVectorType = i + 1;
11022 // We only use vectors if the constant is known to be zero or the target
11023 // allows it and the function is not marked with the noimplicitfloat
11026 LastLegalVectorType = 0;
11027 } else if (NonZero && !TLI.storeOfVectorConstantIsCheap(MemVT,
11028 LastLegalVectorType,
11030 LastLegalVectorType = 0;
11033 // Check if we found a legal integer type to store.
11034 if (LastLegalType == 0 && LastLegalVectorType == 0)
11037 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11038 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11040 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11044 // When extracting multiple vector elements, try to store them
11045 // in one vector store rather than a sequence of scalar stores.
11046 if (IsExtractVecEltSrc) {
11047 unsigned NumElem = 0;
11048 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11049 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11050 SDValue StoredVal = St->getValue();
11051 // This restriction could be loosened.
11052 // Bail out if any stored values are not elements extracted from a vector.
11053 // It should be possible to handle mixed sources, but load sources need
11054 // more careful handling (see the block of code below that handles
11055 // consecutive loads).
11056 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11059 // Find a legal type for the vector store.
11060 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11061 if (TLI.isTypeLegal(Ty) &&
11062 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11067 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11071 // Below we handle the case of multiple consecutive stores that
11072 // come from multiple consecutive loads. We merge them into a single
11073 // wide load and a single wide store.
11075 // Look for load nodes which are used by the stored values.
11076 SmallVector<MemOpLink, 8> LoadNodes;
11078 // Find acceptable loads. Loads need to have the same chain (token factor),
11079 // must not be zext, volatile, indexed, and they must be consecutive.
11080 BaseIndexOffset LdBasePtr;
11081 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11082 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11083 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11086 // Loads must only have one use.
11087 if (!Ld->hasNUsesOfValue(1, 0))
11090 // The memory operands must not be volatile.
11091 if (Ld->isVolatile() || Ld->isIndexed())
11094 // We do not accept ext loads.
11095 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11098 // The stored memory type must be the same.
11099 if (Ld->getMemoryVT() != MemVT)
11102 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11103 // If this is not the first ptr that we check.
11104 if (LdBasePtr.Base.getNode()) {
11105 // The base ptr must be the same.
11106 if (!LdPtr.equalBaseIndex(LdBasePtr))
11109 // Check that all other base pointers are the same as this one.
11113 // We found a potential memory operand to merge.
11114 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11117 if (LoadNodes.size() < 2)
11120 // If we have load/store pair instructions and we only have two values,
11122 unsigned RequiredAlignment;
11123 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11124 St->getAlignment() >= RequiredAlignment)
11127 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11128 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11129 unsigned FirstLoadAlign = FirstLoad->getAlignment();
11131 // Scan the memory operations on the chain and find the first non-consecutive
11132 // load memory address. These variables hold the index in the store node
11134 unsigned LastConsecutiveLoad = 0;
11135 // This variable refers to the size and not index in the array.
11136 unsigned LastLegalVectorType = 0;
11137 unsigned LastLegalIntegerType = 0;
11138 StartAddress = LoadNodes[0].OffsetFromBase;
11139 SDValue FirstChain = FirstLoad->getChain();
11140 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11141 // All loads much share the same chain.
11142 if (LoadNodes[i].MemNode->getChain() != FirstChain)
11145 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11146 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11148 LastConsecutiveLoad = i;
11150 // Find a legal type for the vector store.
11151 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11152 if (TLI.isTypeLegal(StoreTy) &&
11153 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11154 FirstStoreAlign) &&
11155 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11157 LastLegalVectorType = i + 1;
11160 // Find a legal type for the integer store.
11161 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11162 StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11163 if (TLI.isTypeLegal(StoreTy) &&
11164 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11165 FirstStoreAlign) &&
11166 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11168 LastLegalIntegerType = i + 1;
11169 // Or check whether a truncstore and extload is legal.
11170 else if (TLI.getTypeAction(Context, StoreTy) ==
11171 TargetLowering::TypePromoteInteger) {
11172 EVT LegalizedStoredValueTy =
11173 TLI.getTypeToTransformTo(Context, StoreTy);
11174 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11175 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11176 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11177 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11178 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11179 FirstStoreAS, FirstStoreAlign) &&
11180 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11181 FirstLoadAS, FirstLoadAlign))
11182 LastLegalIntegerType = i+1;
11186 // Only use vector types if the vector type is larger than the integer type.
11187 // If they are the same, use integers.
11188 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11189 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11191 // We add +1 here because the LastXXX variables refer to location while
11192 // the NumElem refers to array/index size.
11193 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11194 NumElem = std::min(LastLegalType, NumElem);
11199 // The latest Node in the DAG.
11200 unsigned LatestNodeUsed = 0;
11201 for (unsigned i=1; i<NumElem; ++i) {
11202 // Find a chain for the new wide-store operand. Notice that some
11203 // of the store nodes that we found may not be selected for inclusion
11204 // in the wide store. The chain we use needs to be the chain of the
11205 // latest store node which is *used* and replaced by the wide store.
11206 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11207 LatestNodeUsed = i;
11210 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11212 // Find if it is better to use vectors or integers to load and store
11216 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11218 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11219 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11222 SDLoc LoadDL(LoadNodes[0].MemNode);
11223 SDLoc StoreDL(StoreNodes[0].MemNode);
11225 SDValue NewLoad = DAG.getLoad(
11226 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11227 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11229 SDValue NewStore = DAG.getStore(
11230 LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11231 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11233 // Replace one of the loads with the new load.
11234 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11235 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11236 SDValue(NewLoad.getNode(), 1));
11238 // Remove the rest of the load chains.
11239 for (unsigned i = 1; i < NumElem ; ++i) {
11240 // Replace all chain users of the old load nodes with the chain of the new
11242 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11243 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11246 // Replace the last store with the new store.
11247 CombineTo(LatestOp, NewStore);
11248 // Erase all other stores.
11249 for (unsigned i = 0; i < NumElem ; ++i) {
11250 // Remove all Store nodes.
11251 if (StoreNodes[i].MemNode == LatestOp)
11253 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11254 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11255 deleteAndRecombine(St);
11261 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11262 StoreSDNode *ST = cast<StoreSDNode>(N);
11263 SDValue Chain = ST->getChain();
11264 SDValue Value = ST->getValue();
11265 SDValue Ptr = ST->getBasePtr();
11267 // If this is a store of a bit convert, store the input value if the
11268 // resultant store does not need a higher alignment than the original.
11269 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11270 ST->isUnindexed()) {
11271 unsigned OrigAlign = ST->getAlignment();
11272 EVT SVT = Value.getOperand(0).getValueType();
11273 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11274 SVT.getTypeForEVT(*DAG.getContext()));
11275 if (Align <= OrigAlign &&
11276 ((!LegalOperations && !ST->isVolatile()) ||
11277 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11278 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11279 Ptr, ST->getPointerInfo(), ST->isVolatile(),
11280 ST->isNonTemporal(), OrigAlign,
11284 // Turn 'store undef, Ptr' -> nothing.
11285 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11288 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11289 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11290 // NOTE: If the original store is volatile, this transform must not increase
11291 // the number of stores. For example, on x86-32 an f64 can be stored in one
11292 // processor operation but an i64 (which is not legal) requires two. So the
11293 // transform should not be done in this case.
11294 if (Value.getOpcode() != ISD::TargetConstantFP) {
11296 switch (CFP->getSimpleValueType(0).SimpleTy) {
11297 default: llvm_unreachable("Unknown FP type");
11298 case MVT::f16: // We don't do this for these yet.
11304 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11305 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11307 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11308 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11310 return DAG.getStore(Chain, SDLoc(N), Tmp,
11311 Ptr, ST->getMemOperand());
11315 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11316 !ST->isVolatile()) ||
11317 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11319 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11320 getZExtValue(), SDLoc(CFP), MVT::i64);
11321 return DAG.getStore(Chain, SDLoc(N), Tmp,
11322 Ptr, ST->getMemOperand());
11325 if (!ST->isVolatile() &&
11326 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11327 // Many FP stores are not made apparent until after legalize, e.g. for
11328 // argument passing. Since this is so common, custom legalize the
11329 // 64-bit integer store into two 32-bit stores.
11330 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11331 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11332 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11333 if (DAG.getDataLayout().isBigEndian())
11336 unsigned Alignment = ST->getAlignment();
11337 bool isVolatile = ST->isVolatile();
11338 bool isNonTemporal = ST->isNonTemporal();
11339 AAMDNodes AAInfo = ST->getAAInfo();
11343 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11344 Ptr, ST->getPointerInfo(),
11345 isVolatile, isNonTemporal,
11346 ST->getAlignment(), AAInfo);
11347 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11348 DAG.getConstant(4, DL, Ptr.getValueType()));
11349 Alignment = MinAlign(Alignment, 4U);
11350 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11351 Ptr, ST->getPointerInfo().getWithOffset(4),
11352 isVolatile, isNonTemporal,
11353 Alignment, AAInfo);
11354 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11363 // Try to infer better alignment information than the store already has.
11364 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11365 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11366 if (Align > ST->getAlignment()) {
11368 DAG.getTruncStore(Chain, SDLoc(N), Value,
11369 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11370 ST->isVolatile(), ST->isNonTemporal(), Align,
11372 if (NewStore.getNode() != N)
11373 return CombineTo(ST, NewStore, true);
11378 // Try transforming a pair floating point load / store ops to integer
11379 // load / store ops.
11380 if (SDValue NewST = TransformFPLoadStorePair(N))
11383 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11384 : DAG.getSubtarget().useAA();
11386 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11387 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11390 if (UseAA && ST->isUnindexed()) {
11391 // Walk up chain skipping non-aliasing memory nodes.
11392 SDValue BetterChain = FindBetterChain(N, Chain);
11394 // If there is a better chain.
11395 if (Chain != BetterChain) {
11398 // Replace the chain to avoid dependency.
11399 if (ST->isTruncatingStore()) {
11400 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11401 ST->getMemoryVT(), ST->getMemOperand());
11403 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11404 ST->getMemOperand());
11407 // Create token to keep both nodes around.
11408 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11409 MVT::Other, Chain, ReplStore);
11411 // Make sure the new and old chains are cleaned up.
11412 AddToWorklist(Token.getNode());
11414 // Don't add users to work list.
11415 return CombineTo(N, Token, false);
11419 // Try transforming N to an indexed store.
11420 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11421 return SDValue(N, 0);
11423 // FIXME: is there such a thing as a truncating indexed store?
11424 if (ST->isTruncatingStore() && ST->isUnindexed() &&
11425 Value.getValueType().isInteger()) {
11426 // See if we can simplify the input to this truncstore with knowledge that
11427 // only the low bits are being used. For example:
11428 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
11430 GetDemandedBits(Value,
11431 APInt::getLowBitsSet(
11432 Value.getValueType().getScalarType().getSizeInBits(),
11433 ST->getMemoryVT().getScalarType().getSizeInBits()));
11434 AddToWorklist(Value.getNode());
11435 if (Shorter.getNode())
11436 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11437 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11439 // Otherwise, see if we can simplify the operation with
11440 // SimplifyDemandedBits, which only works if the value has a single use.
11441 if (SimplifyDemandedBits(Value,
11442 APInt::getLowBitsSet(
11443 Value.getValueType().getScalarType().getSizeInBits(),
11444 ST->getMemoryVT().getScalarType().getSizeInBits())))
11445 return SDValue(N, 0);
11448 // If this is a load followed by a store to the same location, then the store
11450 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11451 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11452 ST->isUnindexed() && !ST->isVolatile() &&
11453 // There can't be any side effects between the load and store, such as
11454 // a call or store.
11455 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11456 // The store is dead, remove it.
11461 // If this is a store followed by a store with the same value to the same
11462 // location, then the store is dead/noop.
11463 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11464 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11465 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11466 ST1->isUnindexed() && !ST1->isVolatile()) {
11467 // The store is dead, remove it.
11472 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11473 // truncating store. We can do this even if this is already a truncstore.
11474 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11475 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11476 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11477 ST->getMemoryVT())) {
11478 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11479 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11482 // Only perform this optimization before the types are legal, because we
11483 // don't want to perform this optimization on every DAGCombine invocation.
11485 bool EverChanged = false;
11488 // There can be multiple store sequences on the same chain.
11489 // Keep trying to merge store sequences until we are unable to do so
11490 // or until we merge the last store on the chain.
11491 bool Changed = MergeConsecutiveStores(ST);
11492 EverChanged |= Changed;
11493 if (!Changed) break;
11494 } while (ST->getOpcode() != ISD::DELETED_NODE);
11497 return SDValue(N, 0);
11500 return ReduceLoadOpStoreWidth(N);
11503 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11504 SDValue InVec = N->getOperand(0);
11505 SDValue InVal = N->getOperand(1);
11506 SDValue EltNo = N->getOperand(2);
11509 // If the inserted element is an UNDEF, just use the input vector.
11510 if (InVal.getOpcode() == ISD::UNDEF)
11513 EVT VT = InVec.getValueType();
11515 // If we can't generate a legal BUILD_VECTOR, exit
11516 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11519 // Check that we know which element is being inserted
11520 if (!isa<ConstantSDNode>(EltNo))
11522 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11524 // Canonicalize insert_vector_elt dag nodes.
11526 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11527 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11529 // Do this only if the child insert_vector node has one use; also
11530 // do this only if indices are both constants and Idx1 < Idx0.
11531 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11532 && isa<ConstantSDNode>(InVec.getOperand(2))) {
11533 unsigned OtherElt =
11534 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11535 if (Elt < OtherElt) {
11537 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11538 InVec.getOperand(0), InVal, EltNo);
11539 AddToWorklist(NewOp.getNode());
11540 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11541 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11545 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11546 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
11547 // vector elements.
11548 SmallVector<SDValue, 8> Ops;
11549 // Do not combine these two vectors if the output vector will not replace
11550 // the input vector.
11551 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11552 Ops.append(InVec.getNode()->op_begin(),
11553 InVec.getNode()->op_end());
11554 } else if (InVec.getOpcode() == ISD::UNDEF) {
11555 unsigned NElts = VT.getVectorNumElements();
11556 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11561 // Insert the element
11562 if (Elt < Ops.size()) {
11563 // All the operands of BUILD_VECTOR must have the same type;
11564 // we enforce that here.
11565 EVT OpVT = Ops[0].getValueType();
11566 if (InVal.getValueType() != OpVT)
11567 InVal = OpVT.bitsGT(InVal.getValueType()) ?
11568 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11569 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11573 // Return the new vector
11574 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11577 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11578 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11579 EVT ResultVT = EVE->getValueType(0);
11580 EVT VecEltVT = InVecVT.getVectorElementType();
11581 unsigned Align = OriginalLoad->getAlignment();
11582 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
11583 VecEltVT.getTypeForEVT(*DAG.getContext()));
11585 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11590 SDValue NewPtr = OriginalLoad->getBasePtr();
11592 EVT PtrType = NewPtr.getValueType();
11593 MachinePointerInfo MPI;
11595 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11596 int Elt = ConstEltNo->getZExtValue();
11597 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11598 Offset = DAG.getConstant(PtrOff, DL, PtrType);
11599 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11601 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11602 Offset = DAG.getNode(
11603 ISD::MUL, DL, PtrType, Offset,
11604 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11605 MPI = OriginalLoad->getPointerInfo();
11607 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11609 // The replacement we need to do here is a little tricky: we need to
11610 // replace an extractelement of a load with a load.
11611 // Use ReplaceAllUsesOfValuesWith to do the replacement.
11612 // Note that this replacement assumes that the extractvalue is the only
11613 // use of the load; that's okay because we don't want to perform this
11614 // transformation in other cases anyway.
11617 if (ResultVT.bitsGT(VecEltVT)) {
11618 // If the result type of vextract is wider than the load, then issue an
11619 // extending load instead.
11620 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11624 Load = DAG.getExtLoad(
11625 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11626 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11627 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11628 Chain = Load.getValue(1);
11630 Load = DAG.getLoad(
11631 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11632 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11633 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11634 Chain = Load.getValue(1);
11635 if (ResultVT.bitsLT(VecEltVT))
11636 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11638 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11640 WorklistRemover DeadNodes(*this);
11641 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11642 SDValue To[] = { Load, Chain };
11643 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11644 // Since we're explicitly calling ReplaceAllUses, add the new node to the
11645 // worklist explicitly as well.
11646 AddToWorklist(Load.getNode());
11647 AddUsersToWorklist(Load.getNode()); // Add users too
11648 // Make sure to revisit this node to clean it up; it will usually be dead.
11649 AddToWorklist(EVE);
11651 return SDValue(EVE, 0);
11654 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11655 // (vextract (scalar_to_vector val, 0) -> val
11656 SDValue InVec = N->getOperand(0);
11657 EVT VT = InVec.getValueType();
11658 EVT NVT = N->getValueType(0);
11660 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11661 // Check if the result type doesn't match the inserted element type. A
11662 // SCALAR_TO_VECTOR may truncate the inserted element and the
11663 // EXTRACT_VECTOR_ELT may widen the extracted vector.
11664 SDValue InOp = InVec.getOperand(0);
11665 if (InOp.getValueType() != NVT) {
11666 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11667 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11672 SDValue EltNo = N->getOperand(1);
11673 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11675 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11676 // We only perform this optimization before the op legalization phase because
11677 // we may introduce new vector instructions which are not backed by TD
11678 // patterns. For example on AVX, extracting elements from a wide vector
11679 // without using extract_subvector. However, if we can find an underlying
11680 // scalar value, then we can always use that.
11681 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11683 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11684 int NumElem = VT.getVectorNumElements();
11685 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11686 // Find the new index to extract from.
11687 int OrigElt = SVOp->getMaskElt(Elt);
11689 // Extracting an undef index is undef.
11691 return DAG.getUNDEF(NVT);
11693 // Select the right vector half to extract from.
11695 if (OrigElt < NumElem) {
11696 SVInVec = InVec->getOperand(0);
11698 SVInVec = InVec->getOperand(1);
11699 OrigElt -= NumElem;
11702 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11703 SDValue InOp = SVInVec.getOperand(OrigElt);
11704 if (InOp.getValueType() != NVT) {
11705 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11706 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11712 // FIXME: We should handle recursing on other vector shuffles and
11713 // scalar_to_vector here as well.
11715 if (!LegalOperations) {
11716 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
11717 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11718 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11722 bool BCNumEltsChanged = false;
11723 EVT ExtVT = VT.getVectorElementType();
11726 // If the result of load has to be truncated, then it's not necessarily
11728 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11731 if (InVec.getOpcode() == ISD::BITCAST) {
11732 // Don't duplicate a load with other uses.
11733 if (!InVec.hasOneUse())
11736 EVT BCVT = InVec.getOperand(0).getValueType();
11737 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11739 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11740 BCNumEltsChanged = true;
11741 InVec = InVec.getOperand(0);
11742 ExtVT = BCVT.getVectorElementType();
11745 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11746 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11747 ISD::isNormalLoad(InVec.getNode()) &&
11748 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11749 SDValue Index = N->getOperand(1);
11750 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11751 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11755 // Perform only after legalization to ensure build_vector / vector_shuffle
11756 // optimizations have already been done.
11757 if (!LegalOperations) return SDValue();
11759 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11760 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11761 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11764 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11766 LoadSDNode *LN0 = nullptr;
11767 const ShuffleVectorSDNode *SVN = nullptr;
11768 if (ISD::isNormalLoad(InVec.getNode())) {
11769 LN0 = cast<LoadSDNode>(InVec);
11770 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11771 InVec.getOperand(0).getValueType() == ExtVT &&
11772 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11773 // Don't duplicate a load with other uses.
11774 if (!InVec.hasOneUse())
11777 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11778 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11779 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11781 // (load $addr+1*size)
11783 // Don't duplicate a load with other uses.
11784 if (!InVec.hasOneUse())
11787 // If the bit convert changed the number of elements, it is unsafe
11788 // to examine the mask.
11789 if (BCNumEltsChanged)
11792 // Select the input vector, guarding against out of range extract vector.
11793 unsigned NumElems = VT.getVectorNumElements();
11794 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11795 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11797 if (InVec.getOpcode() == ISD::BITCAST) {
11798 // Don't duplicate a load with other uses.
11799 if (!InVec.hasOneUse())
11802 InVec = InVec.getOperand(0);
11804 if (ISD::isNormalLoad(InVec.getNode())) {
11805 LN0 = cast<LoadSDNode>(InVec);
11806 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11807 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11811 // Make sure we found a non-volatile load and the extractelement is
11813 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11816 // If Idx was -1 above, Elt is going to be -1, so just return undef.
11818 return DAG.getUNDEF(LVT);
11820 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11826 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11827 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11828 // We perform this optimization post type-legalization because
11829 // the type-legalizer often scalarizes integer-promoted vectors.
11830 // Performing this optimization before may create bit-casts which
11831 // will be type-legalized to complex code sequences.
11832 // We perform this optimization only before the operation legalizer because we
11833 // may introduce illegal operations.
11834 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11837 unsigned NumInScalars = N->getNumOperands();
11839 EVT VT = N->getValueType(0);
11841 // Check to see if this is a BUILD_VECTOR of a bunch of values
11842 // which come from any_extend or zero_extend nodes. If so, we can create
11843 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11844 // optimizations. We do not handle sign-extend because we can't fill the sign
11846 EVT SourceType = MVT::Other;
11847 bool AllAnyExt = true;
11849 for (unsigned i = 0; i != NumInScalars; ++i) {
11850 SDValue In = N->getOperand(i);
11851 // Ignore undef inputs.
11852 if (In.getOpcode() == ISD::UNDEF) continue;
11854 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
11855 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11857 // Abort if the element is not an extension.
11858 if (!ZeroExt && !AnyExt) {
11859 SourceType = MVT::Other;
11863 // The input is a ZeroExt or AnyExt. Check the original type.
11864 EVT InTy = In.getOperand(0).getValueType();
11866 // Check that all of the widened source types are the same.
11867 if (SourceType == MVT::Other)
11870 else if (InTy != SourceType) {
11871 // Multiple income types. Abort.
11872 SourceType = MVT::Other;
11876 // Check if all of the extends are ANY_EXTENDs.
11877 AllAnyExt &= AnyExt;
11880 // In order to have valid types, all of the inputs must be extended from the
11881 // same source type and all of the inputs must be any or zero extend.
11882 // Scalar sizes must be a power of two.
11883 EVT OutScalarTy = VT.getScalarType();
11884 bool ValidTypes = SourceType != MVT::Other &&
11885 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11886 isPowerOf2_32(SourceType.getSizeInBits());
11888 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11889 // turn into a single shuffle instruction.
11893 bool isLE = DAG.getDataLayout().isLittleEndian();
11894 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11895 assert(ElemRatio > 1 && "Invalid element size ratio");
11896 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11897 DAG.getConstant(0, SDLoc(N), SourceType);
11899 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11900 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11902 // Populate the new build_vector
11903 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11904 SDValue Cast = N->getOperand(i);
11905 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11906 Cast.getOpcode() == ISD::ZERO_EXTEND ||
11907 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11909 if (Cast.getOpcode() == ISD::UNDEF)
11910 In = DAG.getUNDEF(SourceType);
11912 In = Cast->getOperand(0);
11913 unsigned Index = isLE ? (i * ElemRatio) :
11914 (i * ElemRatio + (ElemRatio - 1));
11916 assert(Index < Ops.size() && "Invalid index");
11920 // The type of the new BUILD_VECTOR node.
11921 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11922 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11923 "Invalid vector size");
11924 // Check if the new vector type is legal.
11925 if (!isTypeLegal(VecVT)) return SDValue();
11927 // Make the new BUILD_VECTOR.
11928 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11930 // The new BUILD_VECTOR node has the potential to be further optimized.
11931 AddToWorklist(BV.getNode());
11932 // Bitcast to the desired type.
11933 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11936 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11937 EVT VT = N->getValueType(0);
11939 unsigned NumInScalars = N->getNumOperands();
11942 EVT SrcVT = MVT::Other;
11943 unsigned Opcode = ISD::DELETED_NODE;
11944 unsigned NumDefs = 0;
11946 for (unsigned i = 0; i != NumInScalars; ++i) {
11947 SDValue In = N->getOperand(i);
11948 unsigned Opc = In.getOpcode();
11950 if (Opc == ISD::UNDEF)
11953 // If all scalar values are floats and converted from integers.
11954 if (Opcode == ISD::DELETED_NODE &&
11955 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11962 EVT InVT = In.getOperand(0).getValueType();
11964 // If all scalar values are typed differently, bail out. It's chosen to
11965 // simplify BUILD_VECTOR of integer types.
11966 if (SrcVT == MVT::Other)
11973 // If the vector has just one element defined, it's not worth to fold it into
11974 // a vectorized one.
11978 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11979 && "Should only handle conversion from integer to float.");
11980 assert(SrcVT != MVT::Other && "Cannot determine source type!");
11982 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11984 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11987 // Just because the floating-point vector type is legal does not necessarily
11988 // mean that the corresponding integer vector type is.
11989 if (!isTypeLegal(NVT))
11992 SmallVector<SDValue, 8> Opnds;
11993 for (unsigned i = 0; i != NumInScalars; ++i) {
11994 SDValue In = N->getOperand(i);
11996 if (In.getOpcode() == ISD::UNDEF)
11997 Opnds.push_back(DAG.getUNDEF(SrcVT));
11999 Opnds.push_back(In.getOperand(0));
12001 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
12002 AddToWorklist(BV.getNode());
12004 return DAG.getNode(Opcode, dl, VT, BV);
12007 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12008 unsigned NumInScalars = N->getNumOperands();
12010 EVT VT = N->getValueType(0);
12012 // A vector built entirely of undefs is undef.
12013 if (ISD::allOperandsUndef(N))
12014 return DAG.getUNDEF(VT);
12016 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12019 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12022 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12023 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12024 // at most two distinct vectors, turn this into a shuffle node.
12026 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12027 if (!isTypeLegal(VT))
12030 // May only combine to shuffle after legalize if shuffle is legal.
12031 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12034 SDValue VecIn1, VecIn2;
12035 bool UsesZeroVector = false;
12036 for (unsigned i = 0; i != NumInScalars; ++i) {
12037 SDValue Op = N->getOperand(i);
12038 // Ignore undef inputs.
12039 if (Op.getOpcode() == ISD::UNDEF) continue;
12041 // See if we can combine this build_vector into a blend with a zero vector.
12042 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12043 UsesZeroVector = true;
12047 // If this input is something other than a EXTRACT_VECTOR_ELT with a
12048 // constant index, bail out.
12049 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12050 !isa<ConstantSDNode>(Op.getOperand(1))) {
12051 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12055 // We allow up to two distinct input vectors.
12056 SDValue ExtractedFromVec = Op.getOperand(0);
12057 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12060 if (!VecIn1.getNode()) {
12061 VecIn1 = ExtractedFromVec;
12062 } else if (!VecIn2.getNode() && !UsesZeroVector) {
12063 VecIn2 = ExtractedFromVec;
12065 // Too many inputs.
12066 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12071 // If everything is good, we can make a shuffle operation.
12072 if (VecIn1.getNode()) {
12073 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12074 SmallVector<int, 8> Mask;
12075 for (unsigned i = 0; i != NumInScalars; ++i) {
12076 unsigned Opcode = N->getOperand(i).getOpcode();
12077 if (Opcode == ISD::UNDEF) {
12078 Mask.push_back(-1);
12082 // Operands can also be zero.
12083 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12084 assert(UsesZeroVector &&
12085 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12086 "Unexpected node found!");
12087 Mask.push_back(NumInScalars+i);
12091 // If extracting from the first vector, just use the index directly.
12092 SDValue Extract = N->getOperand(i);
12093 SDValue ExtVal = Extract.getOperand(1);
12094 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12095 if (Extract.getOperand(0) == VecIn1) {
12096 Mask.push_back(ExtIndex);
12100 // Otherwise, use InIdx + InputVecSize
12101 Mask.push_back(InNumElements + ExtIndex);
12104 // Avoid introducing illegal shuffles with zero.
12105 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12108 // We can't generate a shuffle node with mismatched input and output types.
12109 // Attempt to transform a single input vector to the correct type.
12110 if ((VT != VecIn1.getValueType())) {
12111 // If the input vector type has a different base type to the output
12112 // vector type, bail out.
12113 EVT VTElemType = VT.getVectorElementType();
12114 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12115 (VecIn2.getNode() &&
12116 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12119 // If the input vector is too small, widen it.
12120 // We only support widening of vectors which are half the size of the
12121 // output registers. For example XMM->YMM widening on X86 with AVX.
12122 EVT VecInT = VecIn1.getValueType();
12123 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12124 // If we only have one small input, widen it by adding undef values.
12125 if (!VecIn2.getNode())
12126 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12127 DAG.getUNDEF(VecIn1.getValueType()));
12128 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12129 // If we have two small inputs of the same type, try to concat them.
12130 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12131 VecIn2 = SDValue(nullptr, 0);
12134 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12135 // If the input vector is too large, try to split it.
12136 // We don't support having two input vectors that are too large.
12137 // If the zero vector was used, we can not split the vector,
12138 // since we'd need 3 inputs.
12139 if (UsesZeroVector || VecIn2.getNode())
12142 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12145 // Try to replace VecIn1 with two extract_subvectors
12146 // No need to update the masks, they should still be correct.
12147 VecIn2 = DAG.getNode(
12148 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12149 DAG.getConstant(VT.getVectorNumElements(), dl,
12150 TLI.getVectorIdxTy(DAG.getDataLayout())));
12151 VecIn1 = DAG.getNode(
12152 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12153 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12158 if (UsesZeroVector)
12159 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12160 DAG.getConstantFP(0.0, dl, VT);
12162 // If VecIn2 is unused then change it to undef.
12163 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12165 // Check that we were able to transform all incoming values to the same
12167 if (VecIn2.getValueType() != VecIn1.getValueType() ||
12168 VecIn1.getValueType() != VT)
12171 // Return the new VECTOR_SHUFFLE node.
12175 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12181 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12182 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12183 EVT OpVT = N->getOperand(0).getValueType();
12185 // If the operands are legal vectors, leave them alone.
12186 if (TLI.isTypeLegal(OpVT))
12190 EVT VT = N->getValueType(0);
12191 SmallVector<SDValue, 8> Ops;
12193 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12194 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12196 // Keep track of what we encounter.
12197 bool AnyInteger = false;
12198 bool AnyFP = false;
12199 for (const SDValue &Op : N->ops()) {
12200 if (ISD::BITCAST == Op.getOpcode() &&
12201 !Op.getOperand(0).getValueType().isVector())
12202 Ops.push_back(Op.getOperand(0));
12203 else if (ISD::UNDEF == Op.getOpcode())
12204 Ops.push_back(ScalarUndef);
12208 // Note whether we encounter an integer or floating point scalar.
12209 // If it's neither, bail out, it could be something weird like x86mmx.
12210 EVT LastOpVT = Ops.back().getValueType();
12211 if (LastOpVT.isFloatingPoint())
12213 else if (LastOpVT.isInteger())
12219 // If any of the operands is a floating point scalar bitcast to a vector,
12220 // use floating point types throughout, and bitcast everything.
12221 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12223 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12224 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12226 for (SDValue &Op : Ops) {
12227 if (Op.getValueType() == SVT)
12229 if (Op.getOpcode() == ISD::UNDEF)
12232 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12237 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12238 VT.getSizeInBits() / SVT.getSizeInBits());
12239 return DAG.getNode(ISD::BITCAST, DL, VT,
12240 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12243 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12244 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12245 // most two distinct vectors the same size as the result, attempt to turn this
12246 // into a legal shuffle.
12247 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12248 EVT VT = N->getValueType(0);
12249 EVT OpVT = N->getOperand(0).getValueType();
12250 int NumElts = VT.getVectorNumElements();
12251 int NumOpElts = OpVT.getVectorNumElements();
12253 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12254 SmallVector<int, 8> Mask;
12256 for (SDValue Op : N->ops()) {
12257 // Peek through any bitcast.
12258 while (Op.getOpcode() == ISD::BITCAST)
12259 Op = Op.getOperand(0);
12261 // UNDEF nodes convert to UNDEF shuffle mask values.
12262 if (Op.getOpcode() == ISD::UNDEF) {
12263 Mask.append((unsigned)NumOpElts, -1);
12267 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12270 // What vector are we extracting the subvector from and at what index?
12271 SDValue ExtVec = Op.getOperand(0);
12273 // We want the EVT of the original extraction to correctly scale the
12274 // extraction index.
12275 EVT ExtVT = ExtVec.getValueType();
12277 // Peek through any bitcast.
12278 while (ExtVec.getOpcode() == ISD::BITCAST)
12279 ExtVec = ExtVec.getOperand(0);
12281 // UNDEF nodes convert to UNDEF shuffle mask values.
12282 if (ExtVec.getOpcode() == ISD::UNDEF) {
12283 Mask.append((unsigned)NumOpElts, -1);
12287 if (!isa<ConstantSDNode>(Op.getOperand(1)))
12289 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12291 // Ensure that we are extracting a subvector from a vector the same
12292 // size as the result.
12293 if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12296 // Scale the subvector index to account for any bitcast.
12297 int NumExtElts = ExtVT.getVectorNumElements();
12298 if (0 == (NumExtElts % NumElts))
12299 ExtIdx /= (NumExtElts / NumElts);
12300 else if (0 == (NumElts % NumExtElts))
12301 ExtIdx *= (NumElts / NumExtElts);
12305 // At most we can reference 2 inputs in the final shuffle.
12306 if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) {
12308 for (int i = 0; i != NumOpElts; ++i)
12309 Mask.push_back(i + ExtIdx);
12310 } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) {
12312 for (int i = 0; i != NumOpElts; ++i)
12313 Mask.push_back(i + ExtIdx + NumElts);
12319 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
12322 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
12323 DAG.getBitcast(VT, SV1), Mask);
12326 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12327 // If we only have one input vector, we don't need to do any concatenation.
12328 if (N->getNumOperands() == 1)
12329 return N->getOperand(0);
12331 // Check if all of the operands are undefs.
12332 EVT VT = N->getValueType(0);
12333 if (ISD::allOperandsUndef(N))
12334 return DAG.getUNDEF(VT);
12336 // Optimize concat_vectors where all but the first of the vectors are undef.
12337 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12338 return Op.getOpcode() == ISD::UNDEF;
12340 SDValue In = N->getOperand(0);
12341 assert(In.getValueType().isVector() && "Must concat vectors");
12343 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12344 if (In->getOpcode() == ISD::BITCAST &&
12345 !In->getOperand(0)->getValueType(0).isVector()) {
12346 SDValue Scalar = In->getOperand(0);
12348 // If the bitcast type isn't legal, it might be a trunc of a legal type;
12349 // look through the trunc so we can still do the transform:
12350 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12351 if (Scalar->getOpcode() == ISD::TRUNCATE &&
12352 !TLI.isTypeLegal(Scalar.getValueType()) &&
12353 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12354 Scalar = Scalar->getOperand(0);
12356 EVT SclTy = Scalar->getValueType(0);
12358 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12361 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12362 VT.getSizeInBits() / SclTy.getSizeInBits());
12363 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12366 SDLoc dl = SDLoc(N);
12367 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12368 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12372 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12373 // We have already tested above for an UNDEF only concatenation.
12374 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12375 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12376 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12377 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12379 bool AllBuildVectorsOrUndefs =
12380 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12381 if (AllBuildVectorsOrUndefs) {
12382 SmallVector<SDValue, 8> Opnds;
12383 EVT SVT = VT.getScalarType();
12386 if (!SVT.isFloatingPoint()) {
12387 // If BUILD_VECTOR are from built from integer, they may have different
12388 // operand types. Get the smallest type and truncate all operands to it.
12389 bool FoundMinVT = false;
12390 for (const SDValue &Op : N->ops())
12391 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12392 EVT OpSVT = Op.getOperand(0)->getValueType(0);
12393 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12396 assert(FoundMinVT && "Concat vector type mismatch");
12399 for (const SDValue &Op : N->ops()) {
12400 EVT OpVT = Op.getValueType();
12401 unsigned NumElts = OpVT.getVectorNumElements();
12403 if (ISD::UNDEF == Op.getOpcode())
12404 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12406 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12407 if (SVT.isFloatingPoint()) {
12408 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12409 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12411 for (unsigned i = 0; i != NumElts; ++i)
12413 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12418 assert(VT.getVectorNumElements() == Opnds.size() &&
12419 "Concat vector type mismatch");
12420 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12423 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12424 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12427 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
12428 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
12429 if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
12432 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12433 // nodes often generate nop CONCAT_VECTOR nodes.
12434 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12435 // place the incoming vectors at the exact same location.
12436 SDValue SingleSource = SDValue();
12437 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12439 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12440 SDValue Op = N->getOperand(i);
12442 if (Op.getOpcode() == ISD::UNDEF)
12445 // Check if this is the identity extract:
12446 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12449 // Find the single incoming vector for the extract_subvector.
12450 if (SingleSource.getNode()) {
12451 if (Op.getOperand(0) != SingleSource)
12454 SingleSource = Op.getOperand(0);
12456 // Check the source type is the same as the type of the result.
12457 // If not, this concat may extend the vector, so we can not
12458 // optimize it away.
12459 if (SingleSource.getValueType() != N->getValueType(0))
12463 unsigned IdentityIndex = i * PartNumElem;
12464 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12465 // The extract index must be constant.
12469 // Check that we are reading from the identity index.
12470 if (CS->getZExtValue() != IdentityIndex)
12474 if (SingleSource.getNode())
12475 return SingleSource;
12480 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12481 EVT NVT = N->getValueType(0);
12482 SDValue V = N->getOperand(0);
12484 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12486 // (extract_subvec (concat V1, V2, ...), i)
12489 // Only operand 0 is checked as 'concat' assumes all inputs of the same
12491 if (V->getOperand(0).getValueType() != NVT)
12493 unsigned Idx = N->getConstantOperandVal(1);
12494 unsigned NumElems = NVT.getVectorNumElements();
12495 assert((Idx % NumElems) == 0 &&
12496 "IDX in concat is not a multiple of the result vector length.");
12497 return V->getOperand(Idx / NumElems);
12501 if (V->getOpcode() == ISD::BITCAST)
12502 V = V.getOperand(0);
12504 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12506 // Handle only simple case where vector being inserted and vector
12507 // being extracted are of same type, and are half size of larger vectors.
12508 EVT BigVT = V->getOperand(0).getValueType();
12509 EVT SmallVT = V->getOperand(1).getValueType();
12510 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12513 // Only handle cases where both indexes are constants with the same type.
12514 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12515 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12517 if (InsIdx && ExtIdx &&
12518 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12519 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12521 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12523 // indices are equal or bit offsets are equal => V1
12524 // otherwise => (extract_subvec V1, ExtIdx)
12525 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12526 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12527 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12528 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12529 DAG.getNode(ISD::BITCAST, dl,
12530 N->getOperand(0).getValueType(),
12531 V->getOperand(0)), N->getOperand(1));
12538 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12539 SDValue V, SelectionDAG &DAG) {
12541 EVT VT = V.getValueType();
12543 switch (V.getOpcode()) {
12547 case ISD::CONCAT_VECTORS: {
12548 EVT OpVT = V->getOperand(0).getValueType();
12549 int OpSize = OpVT.getVectorNumElements();
12550 SmallBitVector OpUsedElements(OpSize, false);
12551 bool FoundSimplification = false;
12552 SmallVector<SDValue, 4> NewOps;
12553 NewOps.reserve(V->getNumOperands());
12554 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12555 SDValue Op = V->getOperand(i);
12556 bool OpUsed = false;
12557 for (int j = 0; j < OpSize; ++j)
12558 if (UsedElements[i * OpSize + j]) {
12559 OpUsedElements[j] = true;
12563 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12564 : DAG.getUNDEF(OpVT));
12565 FoundSimplification |= Op == NewOps.back();
12566 OpUsedElements.reset();
12568 if (FoundSimplification)
12569 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12573 case ISD::INSERT_SUBVECTOR: {
12574 SDValue BaseV = V->getOperand(0);
12575 SDValue SubV = V->getOperand(1);
12576 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12580 int SubSize = SubV.getValueType().getVectorNumElements();
12581 int Idx = IdxN->getZExtValue();
12582 bool SubVectorUsed = false;
12583 SmallBitVector SubUsedElements(SubSize, false);
12584 for (int i = 0; i < SubSize; ++i)
12585 if (UsedElements[i + Idx]) {
12586 SubVectorUsed = true;
12587 SubUsedElements[i] = true;
12588 UsedElements[i + Idx] = false;
12591 // Now recurse on both the base and sub vectors.
12592 SDValue SimplifiedSubV =
12594 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12595 : DAG.getUNDEF(SubV.getValueType());
12596 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12597 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12598 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12599 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12605 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12606 SDValue N1, SelectionDAG &DAG) {
12607 EVT VT = SVN->getValueType(0);
12608 int NumElts = VT.getVectorNumElements();
12609 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12610 for (int M : SVN->getMask())
12611 if (M >= 0 && M < NumElts)
12612 N0UsedElements[M] = true;
12613 else if (M >= NumElts)
12614 N1UsedElements[M - NumElts] = true;
12616 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12617 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12618 if (S0 == N0 && S1 == N1)
12621 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12624 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12625 // or turn a shuffle of a single concat into simpler shuffle then concat.
12626 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12627 EVT VT = N->getValueType(0);
12628 unsigned NumElts = VT.getVectorNumElements();
12630 SDValue N0 = N->getOperand(0);
12631 SDValue N1 = N->getOperand(1);
12632 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12634 SmallVector<SDValue, 4> Ops;
12635 EVT ConcatVT = N0.getOperand(0).getValueType();
12636 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12637 unsigned NumConcats = NumElts / NumElemsPerConcat;
12639 // Special case: shuffle(concat(A,B)) can be more efficiently represented
12640 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12641 // half vector elements.
12642 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12643 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12644 SVN->getMask().end(), [](int i) { return i == -1; })) {
12645 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12646 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12647 N1 = DAG.getUNDEF(ConcatVT);
12648 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12651 // Look at every vector that's inserted. We're looking for exact
12652 // subvector-sized copies from a concatenated vector
12653 for (unsigned I = 0; I != NumConcats; ++I) {
12654 // Make sure we're dealing with a copy.
12655 unsigned Begin = I * NumElemsPerConcat;
12656 bool AllUndef = true, NoUndef = true;
12657 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12658 if (SVN->getMaskElt(J) >= 0)
12665 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12668 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12669 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12672 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12673 if (FirstElt < N0.getNumOperands())
12674 Ops.push_back(N0.getOperand(FirstElt));
12676 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12678 } else if (AllUndef) {
12679 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12680 } else { // Mixed with general masks and undefs, can't do optimization.
12685 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12688 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12689 EVT VT = N->getValueType(0);
12690 unsigned NumElts = VT.getVectorNumElements();
12692 SDValue N0 = N->getOperand(0);
12693 SDValue N1 = N->getOperand(1);
12695 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12697 // Canonicalize shuffle undef, undef -> undef
12698 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12699 return DAG.getUNDEF(VT);
12701 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12703 // Canonicalize shuffle v, v -> v, undef
12705 SmallVector<int, 8> NewMask;
12706 for (unsigned i = 0; i != NumElts; ++i) {
12707 int Idx = SVN->getMaskElt(i);
12708 if (Idx >= (int)NumElts) Idx -= NumElts;
12709 NewMask.push_back(Idx);
12711 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12715 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
12716 if (N0.getOpcode() == ISD::UNDEF) {
12717 SmallVector<int, 8> NewMask;
12718 for (unsigned i = 0; i != NumElts; ++i) {
12719 int Idx = SVN->getMaskElt(i);
12721 if (Idx >= (int)NumElts)
12724 Idx = -1; // remove reference to lhs
12726 NewMask.push_back(Idx);
12728 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12732 // Remove references to rhs if it is undef
12733 if (N1.getOpcode() == ISD::UNDEF) {
12734 bool Changed = false;
12735 SmallVector<int, 8> NewMask;
12736 for (unsigned i = 0; i != NumElts; ++i) {
12737 int Idx = SVN->getMaskElt(i);
12738 if (Idx >= (int)NumElts) {
12742 NewMask.push_back(Idx);
12745 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12748 // If it is a splat, check if the argument vector is another splat or a
12750 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12751 SDNode *V = N0.getNode();
12753 // If this is a bit convert that changes the element type of the vector but
12754 // not the number of vector elements, look through it. Be careful not to
12755 // look though conversions that change things like v4f32 to v2f64.
12756 if (V->getOpcode() == ISD::BITCAST) {
12757 SDValue ConvInput = V->getOperand(0);
12758 if (ConvInput.getValueType().isVector() &&
12759 ConvInput.getValueType().getVectorNumElements() == NumElts)
12760 V = ConvInput.getNode();
12763 if (V->getOpcode() == ISD::BUILD_VECTOR) {
12764 assert(V->getNumOperands() == NumElts &&
12765 "BUILD_VECTOR has wrong number of operands");
12767 bool AllSame = true;
12768 for (unsigned i = 0; i != NumElts; ++i) {
12769 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12770 Base = V->getOperand(i);
12774 // Splat of <u, u, u, u>, return <u, u, u, u>
12775 if (!Base.getNode())
12777 for (unsigned i = 0; i != NumElts; ++i) {
12778 if (V->getOperand(i) != Base) {
12783 // Splat of <x, x, x, x>, return <x, x, x, x>
12787 // Canonicalize any other splat as a build_vector.
12788 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12789 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12790 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12791 V->getValueType(0), Ops);
12793 // We may have jumped through bitcasts, so the type of the
12794 // BUILD_VECTOR may not match the type of the shuffle.
12795 if (V->getValueType(0) != VT)
12796 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12801 // There are various patterns used to build up a vector from smaller vectors,
12802 // subvectors, or elements. Scan chains of these and replace unused insertions
12803 // or components with undef.
12804 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12807 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12808 Level < AfterLegalizeVectorOps &&
12809 (N1.getOpcode() == ISD::UNDEF ||
12810 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12811 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12812 SDValue V = partitionShuffleOfConcats(N, DAG);
12818 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12819 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12820 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12821 SmallVector<SDValue, 8> Ops;
12822 for (int M : SVN->getMask()) {
12823 SDValue Op = DAG.getUNDEF(VT.getScalarType());
12825 int Idx = M % NumElts;
12826 SDValue &S = (M < (int)NumElts ? N0 : N1);
12827 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12828 Op = S.getOperand(Idx);
12829 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12831 Op = S.getOperand(0);
12833 // Operand can't be combined - bail out.
12839 if (Ops.size() == VT.getVectorNumElements()) {
12840 // BUILD_VECTOR requires all inputs to be of the same type, find the
12841 // maximum type and extend them all.
12842 EVT SVT = VT.getScalarType();
12843 if (SVT.isInteger())
12844 for (SDValue &Op : Ops)
12845 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12846 if (SVT != VT.getScalarType())
12847 for (SDValue &Op : Ops)
12848 Op = TLI.isZExtFree(Op.getValueType(), SVT)
12849 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12850 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12851 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12855 // If this shuffle only has a single input that is a bitcasted shuffle,
12856 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12857 // back to their original types.
12858 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12859 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12860 TLI.isTypeLegal(VT)) {
12862 // Peek through the bitcast only if there is one user.
12864 while (BC0.getOpcode() == ISD::BITCAST) {
12865 if (!BC0.hasOneUse())
12867 BC0 = BC0.getOperand(0);
12870 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12872 return SmallVector<int, 8>(Mask.begin(), Mask.end());
12874 SmallVector<int, 8> NewMask;
12876 for (int s = 0; s != Scale; ++s)
12877 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12881 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12882 EVT SVT = VT.getScalarType();
12883 EVT InnerVT = BC0->getValueType(0);
12884 EVT InnerSVT = InnerVT.getScalarType();
12886 // Determine which shuffle works with the smaller scalar type.
12887 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12888 EVT ScaleSVT = ScaleVT.getScalarType();
12890 if (TLI.isTypeLegal(ScaleVT) &&
12891 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12892 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12894 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12895 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12897 // Scale the shuffle masks to the smaller scalar type.
12898 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12899 SmallVector<int, 8> InnerMask =
12900 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12901 SmallVector<int, 8> OuterMask =
12902 ScaleShuffleMask(SVN->getMask(), OuterScale);
12904 // Merge the shuffle masks.
12905 SmallVector<int, 8> NewMask;
12906 for (int M : OuterMask)
12907 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12909 // Test for shuffle mask legality over both commutations.
12910 SDValue SV0 = BC0->getOperand(0);
12911 SDValue SV1 = BC0->getOperand(1);
12912 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12914 std::swap(SV0, SV1);
12915 ShuffleVectorSDNode::commuteMask(NewMask);
12916 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12920 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12921 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12922 return DAG.getNode(
12923 ISD::BITCAST, SDLoc(N), VT,
12924 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12930 // Canonicalize shuffles according to rules:
12931 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12932 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12933 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12934 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12935 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12936 TLI.isTypeLegal(VT)) {
12937 // The incoming shuffle must be of the same type as the result of the
12938 // current shuffle.
12939 assert(N1->getOperand(0).getValueType() == VT &&
12940 "Shuffle types don't match");
12942 SDValue SV0 = N1->getOperand(0);
12943 SDValue SV1 = N1->getOperand(1);
12944 bool HasSameOp0 = N0 == SV0;
12945 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12946 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12947 // Commute the operands of this shuffle so that next rule
12949 return DAG.getCommutedVectorShuffle(*SVN);
12952 // Try to fold according to rules:
12953 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12954 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12955 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12956 // Don't try to fold shuffles with illegal type.
12957 // Only fold if this shuffle is the only user of the other shuffle.
12958 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12959 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12960 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12962 // The incoming shuffle must be of the same type as the result of the
12963 // current shuffle.
12964 assert(OtherSV->getOperand(0).getValueType() == VT &&
12965 "Shuffle types don't match");
12968 SmallVector<int, 4> Mask;
12969 // Compute the combined shuffle mask for a shuffle with SV0 as the first
12970 // operand, and SV1 as the second operand.
12971 for (unsigned i = 0; i != NumElts; ++i) {
12972 int Idx = SVN->getMaskElt(i);
12974 // Propagate Undef.
12975 Mask.push_back(Idx);
12979 SDValue CurrentVec;
12980 if (Idx < (int)NumElts) {
12981 // This shuffle index refers to the inner shuffle N0. Lookup the inner
12982 // shuffle mask to identify which vector is actually referenced.
12983 Idx = OtherSV->getMaskElt(Idx);
12985 // Propagate Undef.
12986 Mask.push_back(Idx);
12990 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12991 : OtherSV->getOperand(1);
12993 // This shuffle index references an element within N1.
12997 // Simple case where 'CurrentVec' is UNDEF.
12998 if (CurrentVec.getOpcode() == ISD::UNDEF) {
12999 Mask.push_back(-1);
13003 // Canonicalize the shuffle index. We don't know yet if CurrentVec
13004 // will be the first or second operand of the combined shuffle.
13005 Idx = Idx % NumElts;
13006 if (!SV0.getNode() || SV0 == CurrentVec) {
13007 // Ok. CurrentVec is the left hand side.
13008 // Update the mask accordingly.
13010 Mask.push_back(Idx);
13014 // Bail out if we cannot convert the shuffle pair into a single shuffle.
13015 if (SV1.getNode() && SV1 != CurrentVec)
13018 // Ok. CurrentVec is the right hand side.
13019 // Update the mask accordingly.
13021 Mask.push_back(Idx + NumElts);
13024 // Check if all indices in Mask are Undef. In case, propagate Undef.
13025 bool isUndefMask = true;
13026 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13027 isUndefMask &= Mask[i] < 0;
13030 return DAG.getUNDEF(VT);
13032 if (!SV0.getNode())
13033 SV0 = DAG.getUNDEF(VT);
13034 if (!SV1.getNode())
13035 SV1 = DAG.getUNDEF(VT);
13037 // Avoid introducing shuffles with illegal mask.
13038 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13039 ShuffleVectorSDNode::commuteMask(Mask);
13041 if (!TLI.isShuffleMaskLegal(Mask, VT))
13044 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13045 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13046 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13047 std::swap(SV0, SV1);
13050 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13051 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13052 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13053 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13059 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13060 SDValue InVal = N->getOperand(0);
13061 EVT VT = N->getValueType(0);
13063 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13064 // with a VECTOR_SHUFFLE.
13065 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13066 SDValue InVec = InVal->getOperand(0);
13067 SDValue EltNo = InVal->getOperand(1);
13069 // FIXME: We could support implicit truncation if the shuffle can be
13070 // scaled to a smaller vector scalar type.
13071 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13072 if (C0 && VT == InVec.getValueType() &&
13073 VT.getScalarType() == InVal.getValueType()) {
13074 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13075 int Elt = C0->getZExtValue();
13078 if (TLI.isShuffleMaskLegal(NewMask, VT))
13079 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13087 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13088 SDValue N0 = N->getOperand(0);
13089 SDValue N2 = N->getOperand(2);
13091 // If the input vector is a concatenation, and the insert replaces
13092 // one of the halves, we can optimize into a single concat_vectors.
13093 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13094 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13095 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13096 EVT VT = N->getValueType(0);
13098 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13099 // (concat_vectors Z, Y)
13101 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13102 N->getOperand(1), N0.getOperand(1));
13104 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13105 // (concat_vectors X, Z)
13106 if (InsIdx == VT.getVectorNumElements()/2)
13107 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13108 N0.getOperand(0), N->getOperand(1));
13114 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13115 SDValue N0 = N->getOperand(0);
13117 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13118 if (N0->getOpcode() == ISD::FP16_TO_FP)
13119 return N0->getOperand(0);
13124 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13125 SDValue N0 = N->getOperand(0);
13127 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13128 if (N0->getOpcode() == ISD::AND) {
13129 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13130 if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13131 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13139 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13140 /// with the destination vector and a zero vector.
13141 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13142 /// vector_shuffle V, Zero, <0, 4, 2, 4>
13143 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13144 EVT VT = N->getValueType(0);
13145 SDValue LHS = N->getOperand(0);
13146 SDValue RHS = N->getOperand(1);
13149 // Make sure we're not running after operation legalization where it
13150 // may have custom lowered the vector shuffles.
13151 if (LegalOperations)
13154 if (N->getOpcode() != ISD::AND)
13157 if (RHS.getOpcode() == ISD::BITCAST)
13158 RHS = RHS.getOperand(0);
13160 if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13163 EVT RVT = RHS.getValueType();
13164 unsigned NumElts = RHS.getNumOperands();
13166 // Attempt to create a valid clear mask, splitting the mask into
13167 // sub elements and checking to see if each is
13168 // all zeros or all ones - suitable for shuffle masking.
13169 auto BuildClearMask = [&](int Split) {
13170 int NumSubElts = NumElts * Split;
13171 int NumSubBits = RVT.getScalarSizeInBits() / Split;
13173 SmallVector<int, 8> Indices;
13174 for (int i = 0; i != NumSubElts; ++i) {
13175 int EltIdx = i / Split;
13176 int SubIdx = i % Split;
13177 SDValue Elt = RHS.getOperand(EltIdx);
13178 if (Elt.getOpcode() == ISD::UNDEF) {
13179 Indices.push_back(-1);
13184 if (isa<ConstantSDNode>(Elt))
13185 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13186 else if (isa<ConstantFPSDNode>(Elt))
13187 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13191 // Extract the sub element from the constant bit mask.
13192 if (DAG.getDataLayout().isBigEndian()) {
13193 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13195 Bits = Bits.lshr(SubIdx * NumSubBits);
13199 Bits = Bits.trunc(NumSubBits);
13201 if (Bits.isAllOnesValue())
13202 Indices.push_back(i);
13203 else if (Bits == 0)
13204 Indices.push_back(i + NumSubElts);
13209 // Let's see if the target supports this vector_shuffle.
13210 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13211 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13212 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13215 SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13216 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13217 DAG.getBitcast(ClearVT, LHS),
13218 Zero, &Indices[0]));
13221 // Determine maximum split level (byte level masking).
13223 if (RVT.getScalarSizeInBits() % 8 == 0)
13224 MaxSplit = RVT.getScalarSizeInBits() / 8;
13226 for (int Split = 1; Split <= MaxSplit; ++Split)
13227 if (RVT.getScalarSizeInBits() % Split == 0)
13228 if (SDValue S = BuildClearMask(Split))
13234 /// Visit a binary vector operation, like ADD.
13235 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13236 assert(N->getValueType(0).isVector() &&
13237 "SimplifyVBinOp only works on vectors!");
13239 SDValue LHS = N->getOperand(0);
13240 SDValue RHS = N->getOperand(1);
13242 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
13244 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
13245 RHS.getOpcode() == ISD::BUILD_VECTOR) {
13246 // Check if both vectors are constants. If not bail out.
13247 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
13248 cast<BuildVectorSDNode>(RHS)->isConstant()))
13251 SmallVector<SDValue, 8> Ops;
13252 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
13253 SDValue LHSOp = LHS.getOperand(i);
13254 SDValue RHSOp = RHS.getOperand(i);
13256 // Can't fold divide by zero.
13257 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
13258 N->getOpcode() == ISD::FDIV) {
13259 if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP &&
13260 cast<ConstantFPSDNode>(RHSOp.getNode())->isZero()))
13264 EVT VT = LHSOp.getValueType();
13265 EVT RVT = RHSOp.getValueType();
13267 // Integer BUILD_VECTOR operands may have types larger than the element
13268 // size (e.g., when the element type is not legal). Prior to type
13269 // legalization, the types may not match between the two BUILD_VECTORS.
13270 // Truncate one of the operands to make them match.
13271 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
13272 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
13274 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
13278 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
13280 if (FoldOp.getOpcode() != ISD::UNDEF &&
13281 FoldOp.getOpcode() != ISD::Constant &&
13282 FoldOp.getOpcode() != ISD::ConstantFP)
13284 Ops.push_back(FoldOp);
13285 AddToWorklist(FoldOp.getNode());
13288 if (Ops.size() == LHS.getNumOperands())
13289 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
13292 // Try to convert a constant mask AND into a shuffle clear mask.
13293 if (SDValue Shuffle = XformToShuffleWithZero(N))
13296 // Type legalization might introduce new shuffles in the DAG.
13297 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13298 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
13299 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13300 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13301 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13302 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13303 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13304 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13306 if (SVN0->getMask().equals(SVN1->getMask())) {
13307 EVT VT = N->getValueType(0);
13308 SDValue UndefVector = LHS.getOperand(1);
13309 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13310 LHS.getOperand(0), RHS.getOperand(0));
13311 AddUsersToWorklist(N);
13312 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13313 &SVN0->getMask()[0]);
13320 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13321 SDValue N1, SDValue N2){
13322 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13324 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13325 cast<CondCodeSDNode>(N0.getOperand(2))->get());
13327 // If we got a simplified select_cc node back from SimplifySelectCC, then
13328 // break it down into a new SETCC node, and a new SELECT node, and then return
13329 // the SELECT node, since we were called with a SELECT node.
13330 if (SCC.getNode()) {
13331 // Check to see if we got a select_cc back (to turn into setcc/select).
13332 // Otherwise, just return whatever node we got back, like fabs.
13333 if (SCC.getOpcode() == ISD::SELECT_CC) {
13334 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13336 SCC.getOperand(0), SCC.getOperand(1),
13337 SCC.getOperand(4));
13338 AddToWorklist(SETCC.getNode());
13339 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13340 SCC.getOperand(2), SCC.getOperand(3));
13348 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13349 /// being selected between, see if we can simplify the select. Callers of this
13350 /// should assume that TheSelect is deleted if this returns true. As such, they
13351 /// should return the appropriate thing (e.g. the node) back to the top-level of
13352 /// the DAG combiner loop to avoid it being looked at.
13353 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13356 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13357 // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13358 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13359 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13360 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13361 SDValue Sqrt = RHS;
13364 const ConstantFPSDNode *NegZero = nullptr;
13366 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13367 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13368 CmpLHS = TheSelect->getOperand(0);
13369 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13371 // SELECT or VSELECT
13372 SDValue Cmp = TheSelect->getOperand(0);
13373 if (Cmp.getOpcode() == ISD::SETCC) {
13374 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13375 CmpLHS = Cmp.getOperand(0);
13376 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13379 if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13380 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13381 CC == ISD::SETULT || CC == ISD::SETLT)) {
13382 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13383 CombineTo(TheSelect, Sqrt);
13388 // Cannot simplify select with vector condition
13389 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13391 // If this is a select from two identical things, try to pull the operation
13392 // through the select.
13393 if (LHS.getOpcode() != RHS.getOpcode() ||
13394 !LHS.hasOneUse() || !RHS.hasOneUse())
13397 // If this is a load and the token chain is identical, replace the select
13398 // of two loads with a load through a select of the address to load from.
13399 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13400 // constants have been dropped into the constant pool.
13401 if (LHS.getOpcode() == ISD::LOAD) {
13402 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13403 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13405 // Token chains must be identical.
13406 if (LHS.getOperand(0) != RHS.getOperand(0) ||
13407 // Do not let this transformation reduce the number of volatile loads.
13408 LLD->isVolatile() || RLD->isVolatile() ||
13409 // FIXME: If either is a pre/post inc/dec load,
13410 // we'd need to split out the address adjustment.
13411 LLD->isIndexed() || RLD->isIndexed() ||
13412 // If this is an EXTLOAD, the VT's must match.
13413 LLD->getMemoryVT() != RLD->getMemoryVT() ||
13414 // If this is an EXTLOAD, the kind of extension must match.
13415 (LLD->getExtensionType() != RLD->getExtensionType() &&
13416 // The only exception is if one of the extensions is anyext.
13417 LLD->getExtensionType() != ISD::EXTLOAD &&
13418 RLD->getExtensionType() != ISD::EXTLOAD) ||
13419 // FIXME: this discards src value information. This is
13420 // over-conservative. It would be beneficial to be able to remember
13421 // both potential memory locations. Since we are discarding
13422 // src value info, don't do the transformation if the memory
13423 // locations are not in the default address space.
13424 LLD->getPointerInfo().getAddrSpace() != 0 ||
13425 RLD->getPointerInfo().getAddrSpace() != 0 ||
13426 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13427 LLD->getBasePtr().getValueType()))
13430 // Check that the select condition doesn't reach either load. If so,
13431 // folding this will induce a cycle into the DAG. If not, this is safe to
13432 // xform, so create a select of the addresses.
13434 if (TheSelect->getOpcode() == ISD::SELECT) {
13435 SDNode *CondNode = TheSelect->getOperand(0).getNode();
13436 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13437 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13439 // The loads must not depend on one another.
13440 if (LLD->isPredecessorOf(RLD) ||
13441 RLD->isPredecessorOf(LLD))
13443 Addr = DAG.getSelect(SDLoc(TheSelect),
13444 LLD->getBasePtr().getValueType(),
13445 TheSelect->getOperand(0), LLD->getBasePtr(),
13446 RLD->getBasePtr());
13447 } else { // Otherwise SELECT_CC
13448 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13449 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13451 if ((LLD->hasAnyUseOfValue(1) &&
13452 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13453 (RLD->hasAnyUseOfValue(1) &&
13454 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13457 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13458 LLD->getBasePtr().getValueType(),
13459 TheSelect->getOperand(0),
13460 TheSelect->getOperand(1),
13461 LLD->getBasePtr(), RLD->getBasePtr(),
13462 TheSelect->getOperand(4));
13466 // It is safe to replace the two loads if they have different alignments,
13467 // but the new load must be the minimum (most restrictive) alignment of the
13469 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13470 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13471 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13472 Load = DAG.getLoad(TheSelect->getValueType(0),
13474 // FIXME: Discards pointer and AA info.
13475 LLD->getChain(), Addr, MachinePointerInfo(),
13476 LLD->isVolatile(), LLD->isNonTemporal(),
13477 isInvariant, Alignment);
13479 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13480 RLD->getExtensionType() : LLD->getExtensionType(),
13482 TheSelect->getValueType(0),
13483 // FIXME: Discards pointer and AA info.
13484 LLD->getChain(), Addr, MachinePointerInfo(),
13485 LLD->getMemoryVT(), LLD->isVolatile(),
13486 LLD->isNonTemporal(), isInvariant, Alignment);
13489 // Users of the select now use the result of the load.
13490 CombineTo(TheSelect, Load);
13492 // Users of the old loads now use the new load's chain. We know the
13493 // old-load value is dead now.
13494 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13495 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13502 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13503 /// where 'cond' is the comparison specified by CC.
13504 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13505 SDValue N2, SDValue N3,
13506 ISD::CondCode CC, bool NotExtCompare) {
13507 // (x ? y : y) -> y.
13508 if (N2 == N3) return N2;
13510 EVT VT = N2.getValueType();
13511 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13512 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13514 // Determine if the condition we're dealing with is constant
13515 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13516 N0, N1, CC, DL, false);
13517 if (SCC.getNode()) AddToWorklist(SCC.getNode());
13519 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13520 // fold select_cc true, x, y -> x
13521 // fold select_cc false, x, y -> y
13522 return !SCCC->isNullValue() ? N2 : N3;
13525 // Check to see if we can simplify the select into an fabs node
13526 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13527 // Allow either -0.0 or 0.0
13528 if (CFP->isZero()) {
13529 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13530 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13531 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13532 N2 == N3.getOperand(0))
13533 return DAG.getNode(ISD::FABS, DL, VT, N0);
13535 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13536 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13537 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13538 N2.getOperand(0) == N3)
13539 return DAG.getNode(ISD::FABS, DL, VT, N3);
13543 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13544 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13545 // in it. This is a win when the constant is not otherwise available because
13546 // it replaces two constant pool loads with one. We only do this if the FP
13547 // type is known to be legal, because if it isn't, then we are before legalize
13548 // types an we want the other legalization to happen first (e.g. to avoid
13549 // messing with soft float) and if the ConstantFP is not legal, because if
13550 // it is legal, we may not need to store the FP constant in a constant pool.
13551 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13552 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13553 if (TLI.isTypeLegal(N2.getValueType()) &&
13554 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13555 TargetLowering::Legal &&
13556 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13557 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13558 // If both constants have multiple uses, then we won't need to do an
13559 // extra load, they are likely around in registers for other users.
13560 (TV->hasOneUse() || FV->hasOneUse())) {
13561 Constant *Elts[] = {
13562 const_cast<ConstantFP*>(FV->getConstantFPValue()),
13563 const_cast<ConstantFP*>(TV->getConstantFPValue())
13565 Type *FPTy = Elts[0]->getType();
13566 const DataLayout &TD = DAG.getDataLayout();
13568 // Create a ConstantArray of the two constants.
13569 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13571 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
13572 TD.getPrefTypeAlignment(FPTy));
13573 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13575 // Get the offsets to the 0 and 1 element of the array so that we can
13576 // select between them.
13577 SDValue Zero = DAG.getIntPtrConstant(0, DL);
13578 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13579 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13581 SDValue Cond = DAG.getSetCC(DL,
13582 getSetCCResultType(N0.getValueType()),
13584 AddToWorklist(Cond.getNode());
13585 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13587 AddToWorklist(CstOffset.getNode());
13588 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13590 AddToWorklist(CPIdx.getNode());
13591 return DAG.getLoad(
13592 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13593 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13594 false, false, false, Alignment);
13598 // Check to see if we can perform the "gzip trick", transforming
13599 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13600 if (isNullConstant(N3) && CC == ISD::SETLT &&
13601 (isNullConstant(N1) || // (a < 0) ? b : 0
13602 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0
13603 EVT XType = N0.getValueType();
13604 EVT AType = N2.getValueType();
13605 if (XType.bitsGE(AType)) {
13606 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13607 // single-bit constant.
13608 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13609 unsigned ShCtV = N2C->getAPIntValue().logBase2();
13610 ShCtV = XType.getSizeInBits() - ShCtV - 1;
13611 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13612 getShiftAmountTy(N0.getValueType()));
13613 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13615 AddToWorklist(Shift.getNode());
13617 if (XType.bitsGT(AType)) {
13618 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13619 AddToWorklist(Shift.getNode());
13622 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13625 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13627 DAG.getConstant(XType.getSizeInBits() - 1,
13629 getShiftAmountTy(N0.getValueType())));
13630 AddToWorklist(Shift.getNode());
13632 if (XType.bitsGT(AType)) {
13633 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13634 AddToWorklist(Shift.getNode());
13637 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13641 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13642 // where y is has a single bit set.
13643 // A plaintext description would be, we can turn the SELECT_CC into an AND
13644 // when the condition can be materialized as an all-ones register. Any
13645 // single bit-test can be materialized as an all-ones register with
13646 // shift-left and shift-right-arith.
13647 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13648 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13649 SDValue AndLHS = N0->getOperand(0);
13650 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13651 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13652 // Shift the tested bit over the sign bit.
13653 APInt AndMask = ConstAndRHS->getAPIntValue();
13655 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13656 getShiftAmountTy(AndLHS.getValueType()));
13657 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13659 // Now arithmetic right shift it all the way over, so the result is either
13660 // all-ones, or zero.
13662 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13663 getShiftAmountTy(Shl.getValueType()));
13664 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13666 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13670 // fold select C, 16, 0 -> shl C, 4
13671 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13672 TLI.getBooleanContents(N0.getValueType()) ==
13673 TargetLowering::ZeroOrOneBooleanContent) {
13675 // If the caller doesn't want us to simplify this into a zext of a compare,
13677 if (NotExtCompare && N2C->isOne())
13680 // Get a SetCC of the condition
13681 // NOTE: Don't create a SETCC if it's not legal on this target.
13682 if (!LegalOperations ||
13683 TLI.isOperationLegal(ISD::SETCC,
13684 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13686 // cast from setcc result type to select result type
13688 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13690 if (N2.getValueType().bitsLT(SCC.getValueType()))
13691 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13692 N2.getValueType());
13694 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13695 N2.getValueType(), SCC);
13697 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13698 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13699 N2.getValueType(), SCC);
13702 AddToWorklist(SCC.getNode());
13703 AddToWorklist(Temp.getNode());
13708 // shl setcc result by log2 n2c
13709 return DAG.getNode(
13710 ISD::SHL, DL, N2.getValueType(), Temp,
13711 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13712 getShiftAmountTy(Temp.getValueType())));
13716 // Check to see if this is the equivalent of setcc
13717 // FIXME: Turn all of these into setcc if setcc if setcc is legal
13718 // otherwise, go ahead with the folds.
13719 if (0 && isNullConstant(N3) && isOneConstant(N2)) {
13720 EVT XType = N0.getValueType();
13721 if (!LegalOperations ||
13722 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13723 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13724 if (Res.getValueType() != VT)
13725 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13729 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13730 if (isNullConstant(N1) && CC == ISD::SETEQ &&
13731 (!LegalOperations ||
13732 TLI.isOperationLegal(ISD::CTLZ, XType))) {
13733 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13734 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13735 DAG.getConstant(Log2_32(XType.getSizeInBits()),
13737 getShiftAmountTy(Ctlz.getValueType())));
13739 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13740 if (isNullConstant(N1) && CC == ISD::SETGT) {
13742 SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13743 XType, DAG.getConstant(0, DL, XType), N0);
13744 SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13745 return DAG.getNode(ISD::SRL, DL, XType,
13746 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13747 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13748 getShiftAmountTy(XType)));
13750 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13751 if (isAllOnesConstant(N1) && CC == ISD::SETGT) {
13753 SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13754 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13755 getShiftAmountTy(N0.getValueType())));
13756 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13761 // Check to see if this is an integer abs.
13762 // select_cc setg[te] X, 0, X, -X ->
13763 // select_cc setgt X, -1, X, -X ->
13764 // select_cc setl[te] X, 0, -X, X ->
13765 // select_cc setlt X, 1, -X, X ->
13766 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13768 ConstantSDNode *SubC = nullptr;
13769 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13770 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13771 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13772 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13773 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13774 (N1C->isOne() && CC == ISD::SETLT)) &&
13775 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13776 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13778 EVT XType = N0.getValueType();
13779 if (SubC && SubC->isNullValue() && XType.isInteger()) {
13781 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13783 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13784 getShiftAmountTy(N0.getValueType())));
13785 SDValue Add = DAG.getNode(ISD::ADD, DL,
13787 AddToWorklist(Shift.getNode());
13788 AddToWorklist(Add.getNode());
13789 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13796 /// This is a stub for TargetLowering::SimplifySetCC.
13797 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13798 SDValue N1, ISD::CondCode Cond,
13799 SDLoc DL, bool foldBooleans) {
13800 TargetLowering::DAGCombinerInfo
13801 DagCombineInfo(DAG, Level, false, this);
13802 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13805 /// Given an ISD::SDIV node expressing a divide by constant, return
13806 /// a DAG expression to select that will generate the same value by multiplying
13807 /// by a magic number.
13808 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13809 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13810 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13814 // Avoid division by zero.
13815 if (C->isNullValue())
13818 std::vector<SDNode*> Built;
13820 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13822 for (SDNode *N : Built)
13827 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13828 /// DAG expression that will generate the same value by right shifting.
13829 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13830 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13834 // Avoid division by zero.
13835 if (C->isNullValue())
13838 std::vector<SDNode *> Built;
13839 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13841 for (SDNode *N : Built)
13846 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13847 /// expression that will generate the same value by multiplying by a magic
13849 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13850 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13851 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13855 // Avoid division by zero.
13856 if (C->isNullValue())
13859 std::vector<SDNode*> Built;
13861 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13863 for (SDNode *N : Built)
13868 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13869 if (Level >= AfterLegalizeDAG)
13872 // Expose the DAG combiner to the target combiner implementations.
13873 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13875 unsigned Iterations = 0;
13876 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13878 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13879 // For the reciprocal, we need to find the zero of the function:
13880 // F(X) = A X - 1 [which has a zero at X = 1/A]
13882 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13883 // does not require additional intermediate precision]
13884 EVT VT = Op.getValueType();
13886 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13888 AddToWorklist(Est.getNode());
13890 // Newton iterations: Est = Est + Est (1 - Arg * Est)
13891 for (unsigned i = 0; i < Iterations; ++i) {
13892 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13893 AddToWorklist(NewEst.getNode());
13895 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13896 AddToWorklist(NewEst.getNode());
13898 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13899 AddToWorklist(NewEst.getNode());
13901 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13902 AddToWorklist(Est.getNode());
13911 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13912 /// For the reciprocal sqrt, we need to find the zero of the function:
13913 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13915 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13916 /// As a result, we precompute A/2 prior to the iteration loop.
13917 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13918 unsigned Iterations) {
13919 EVT VT = Arg.getValueType();
13921 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13923 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13924 // this entire sequence requires only one FP constant.
13925 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13926 AddToWorklist(HalfArg.getNode());
13928 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13929 AddToWorklist(HalfArg.getNode());
13931 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13932 for (unsigned i = 0; i < Iterations; ++i) {
13933 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13934 AddToWorklist(NewEst.getNode());
13936 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13937 AddToWorklist(NewEst.getNode());
13939 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13940 AddToWorklist(NewEst.getNode());
13942 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13943 AddToWorklist(Est.getNode());
13948 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13949 /// For the reciprocal sqrt, we need to find the zero of the function:
13950 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13952 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13953 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13954 unsigned Iterations) {
13955 EVT VT = Arg.getValueType();
13957 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13958 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13960 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13961 for (unsigned i = 0; i < Iterations; ++i) {
13962 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13963 AddToWorklist(HalfEst.getNode());
13965 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13966 AddToWorklist(Est.getNode());
13968 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13969 AddToWorklist(Est.getNode());
13971 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13972 AddToWorklist(Est.getNode());
13974 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13975 AddToWorklist(Est.getNode());
13980 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13981 if (Level >= AfterLegalizeDAG)
13984 // Expose the DAG combiner to the target combiner implementations.
13985 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13986 unsigned Iterations = 0;
13987 bool UseOneConstNR = false;
13988 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13989 AddToWorklist(Est.getNode());
13991 Est = UseOneConstNR ?
13992 BuildRsqrtNROneConst(Op, Est, Iterations) :
13993 BuildRsqrtNRTwoConst(Op, Est, Iterations);
14001 /// Return true if base is a frame index, which is known not to alias with
14002 /// anything but itself. Provides base object and offset as results.
14003 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14004 const GlobalValue *&GV, const void *&CV) {
14005 // Assume it is a primitive operation.
14006 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14008 // If it's an adding a simple constant then integrate the offset.
14009 if (Base.getOpcode() == ISD::ADD) {
14010 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14011 Base = Base.getOperand(0);
14012 Offset += C->getZExtValue();
14016 // Return the underlying GlobalValue, and update the Offset. Return false
14017 // for GlobalAddressSDNode since the same GlobalAddress may be represented
14018 // by multiple nodes with different offsets.
14019 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14020 GV = G->getGlobal();
14021 Offset += G->getOffset();
14025 // Return the underlying Constant value, and update the Offset. Return false
14026 // for ConstantSDNodes since the same constant pool entry may be represented
14027 // by multiple nodes with different offsets.
14028 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14029 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14030 : (const void *)C->getConstVal();
14031 Offset += C->getOffset();
14034 // If it's any of the following then it can't alias with anything but itself.
14035 return isa<FrameIndexSDNode>(Base);
14038 /// Return true if there is any possibility that the two addresses overlap.
14039 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14040 // If they are the same then they must be aliases.
14041 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14043 // If they are both volatile then they cannot be reordered.
14044 if (Op0->isVolatile() && Op1->isVolatile()) return true;
14046 // If one operation reads from invariant memory, and the other may store, they
14047 // cannot alias. These should really be checking the equivalent of mayWrite,
14048 // but it only matters for memory nodes other than load /store.
14049 if (Op0->isInvariant() && Op1->writeMem())
14052 if (Op1->isInvariant() && Op0->writeMem())
14055 // Gather base node and offset information.
14056 SDValue Base1, Base2;
14057 int64_t Offset1, Offset2;
14058 const GlobalValue *GV1, *GV2;
14059 const void *CV1, *CV2;
14060 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14061 Base1, Offset1, GV1, CV1);
14062 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14063 Base2, Offset2, GV2, CV2);
14065 // If they have a same base address then check to see if they overlap.
14066 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14067 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14068 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14070 // It is possible for different frame indices to alias each other, mostly
14071 // when tail call optimization reuses return address slots for arguments.
14072 // To catch this case, look up the actual index of frame indices to compute
14073 // the real alias relationship.
14074 if (isFrameIndex1 && isFrameIndex2) {
14075 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14076 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14077 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14078 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14079 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14082 // Otherwise, if we know what the bases are, and they aren't identical, then
14083 // we know they cannot alias.
14084 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14087 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14088 // compared to the size and offset of the access, we may be able to prove they
14089 // do not alias. This check is conservative for now to catch cases created by
14090 // splitting vector types.
14091 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14092 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14093 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14094 Op1->getMemoryVT().getSizeInBits() >> 3) &&
14095 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14096 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14097 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14099 // There is no overlap between these relatively aligned accesses of similar
14100 // size, return no alias.
14101 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14102 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14106 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14108 : DAG.getSubtarget().useAA();
14110 if (CombinerAAOnlyFunc.getNumOccurrences() &&
14111 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14115 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14116 // Use alias analysis information.
14117 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14118 Op1->getSrcValueOffset());
14119 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14120 Op0->getSrcValueOffset() - MinOffset;
14121 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14122 Op1->getSrcValueOffset() - MinOffset;
14123 AliasResult AAResult =
14124 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14125 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14126 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14127 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14128 if (AAResult == NoAlias)
14132 // Otherwise we have to assume they alias.
14136 /// Walk up chain skipping non-aliasing memory nodes,
14137 /// looking for aliasing nodes and adding them to the Aliases vector.
14138 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14139 SmallVectorImpl<SDValue> &Aliases) {
14140 SmallVector<SDValue, 8> Chains; // List of chains to visit.
14141 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
14143 // Get alias information for node.
14144 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14147 Chains.push_back(OriginalChain);
14148 unsigned Depth = 0;
14150 // Look at each chain and determine if it is an alias. If so, add it to the
14151 // aliases list. If not, then continue up the chain looking for the next
14153 while (!Chains.empty()) {
14154 SDValue Chain = Chains.pop_back_val();
14156 // For TokenFactor nodes, look at each operand and only continue up the
14157 // chain until we find two aliases. If we've seen two aliases, assume we'll
14158 // find more and revert to original chain since the xform is unlikely to be
14161 // FIXME: The depth check could be made to return the last non-aliasing
14162 // chain we found before we hit a tokenfactor rather than the original
14164 if (Depth > 6 || Aliases.size() == 2) {
14166 Aliases.push_back(OriginalChain);
14170 // Don't bother if we've been before.
14171 if (!Visited.insert(Chain.getNode()).second)
14174 switch (Chain.getOpcode()) {
14175 case ISD::EntryToken:
14176 // Entry token is ideal chain operand, but handled in FindBetterChain.
14181 // Get alias information for Chain.
14182 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14183 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14185 // If chain is alias then stop here.
14186 if (!(IsLoad && IsOpLoad) &&
14187 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14188 Aliases.push_back(Chain);
14190 // Look further up the chain.
14191 Chains.push_back(Chain.getOperand(0));
14197 case ISD::TokenFactor:
14198 // We have to check each of the operands of the token factor for "small"
14199 // token factors, so we queue them up. Adding the operands to the queue
14200 // (stack) in reverse order maintains the original order and increases the
14201 // likelihood that getNode will find a matching token factor (CSE.)
14202 if (Chain.getNumOperands() > 16) {
14203 Aliases.push_back(Chain);
14206 for (unsigned n = Chain.getNumOperands(); n;)
14207 Chains.push_back(Chain.getOperand(--n));
14212 // For all other instructions we will just have to take what we can get.
14213 Aliases.push_back(Chain);
14218 // We need to be careful here to also search for aliases through the
14219 // value operand of a store, etc. Consider the following situation:
14221 // L1 = load Token1, %52
14222 // S1 = store Token1, L1, %51
14223 // L2 = load Token1, %52+8
14224 // S2 = store Token1, L2, %51+8
14225 // Token2 = Token(S1, S2)
14226 // L3 = load Token2, %53
14227 // S3 = store Token2, L3, %52
14228 // L4 = load Token2, %53+8
14229 // S4 = store Token2, L4, %52+8
14230 // If we search for aliases of S3 (which loads address %52), and we look
14231 // only through the chain, then we'll miss the trivial dependence on L1
14232 // (which also loads from %52). We then might change all loads and
14233 // stores to use Token1 as their chain operand, which could result in
14234 // copying %53 into %52 before copying %52 into %51 (which should
14237 // The problem is, however, that searching for such data dependencies
14238 // can become expensive, and the cost is not directly related to the
14239 // chain depth. Instead, we'll rule out such configurations here by
14240 // insisting that we've visited all chain users (except for users
14241 // of the original chain, which is not necessary). When doing this,
14242 // we need to look through nodes we don't care about (otherwise, things
14243 // like register copies will interfere with trivial cases).
14245 SmallVector<const SDNode *, 16> Worklist;
14246 for (const SDNode *N : Visited)
14247 if (N != OriginalChain.getNode())
14248 Worklist.push_back(N);
14250 while (!Worklist.empty()) {
14251 const SDNode *M = Worklist.pop_back_val();
14253 // We have already visited M, and want to make sure we've visited any uses
14254 // of M that we care about. For uses that we've not visisted, and don't
14255 // care about, queue them to the worklist.
14257 for (SDNode::use_iterator UI = M->use_begin(),
14258 UIE = M->use_end(); UI != UIE; ++UI)
14259 if (UI.getUse().getValueType() == MVT::Other &&
14260 Visited.insert(*UI).second) {
14261 if (isa<MemSDNode>(*UI)) {
14262 // We've not visited this use, and we care about it (it could have an
14263 // ordering dependency with the original node).
14265 Aliases.push_back(OriginalChain);
14269 // We've not visited this use, but we don't care about it. Mark it as
14270 // visited and enqueue it to the worklist.
14271 Worklist.push_back(*UI);
14276 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14277 /// (aliasing node.)
14278 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14279 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
14281 // Accumulate all the aliases to this node.
14282 GatherAllAliases(N, OldChain, Aliases);
14284 // If no operands then chain to entry token.
14285 if (Aliases.size() == 0)
14286 return DAG.getEntryNode();
14288 // If a single operand then chain to it. We don't need to revisit it.
14289 if (Aliases.size() == 1)
14292 // Construct a custom tailored token factor.
14293 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14296 /// This is the entry point for the file.
14297 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14298 CodeGenOpt::Level OptLevel) {
14299 /// This is the main entry point to this class.
14300 DAGCombiner(*this, AA, OptLevel).Run(Level);