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 bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
2187 // fold (sdiv X, pow2) -> simple ops after legalize
2188 // FIXME: We check for the exact bit here because the generic lowering gives
2189 // better results in that case. The target-specific lowering should learn how
2190 // to handle exact sdivs efficiently.
2191 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2192 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2193 (N1C->getAPIntValue().isPowerOf2() ||
2194 (-N1C->getAPIntValue()).isPowerOf2())) {
2195 // If integer division is cheap, then don't perform the following fold.
2196 if (TLI.isIntDivCheap(N->getValueType(0), MinSize))
2199 // Target-specific implementation of sdiv x, pow2.
2200 if (SDValue Res = BuildSDIVPow2(N))
2203 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2206 // Splat the sign bit into the register
2208 DAG.getNode(ISD::SRA, DL, VT, N0,
2209 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2210 getShiftAmountTy(N0.getValueType())));
2211 AddToWorklist(SGN.getNode());
2213 // Add (N0 < 0) ? abs2 - 1 : 0;
2215 DAG.getNode(ISD::SRL, DL, VT, SGN,
2216 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2217 getShiftAmountTy(SGN.getValueType())));
2218 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2219 AddToWorklist(SRL.getNode());
2220 AddToWorklist(ADD.getNode()); // Divide by pow2
2221 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2222 DAG.getConstant(lg2, DL,
2223 getShiftAmountTy(ADD.getValueType())));
2225 // If we're dividing by a positive value, we're done. Otherwise, we must
2226 // negate the result.
2227 if (N1C->getAPIntValue().isNonNegative())
2230 AddToWorklist(SRA.getNode());
2231 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2234 // If integer divide is expensive and we satisfy the requirements, emit an
2235 // alternate sequence.
2236 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), MinSize))
2237 if (SDValue Op = BuildSDIV(N))
2241 if (N0.getOpcode() == ISD::UNDEF)
2242 return DAG.getConstant(0, SDLoc(N), VT);
2243 // X / undef -> undef
2244 if (N1.getOpcode() == ISD::UNDEF)
2250 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2251 SDValue N0 = N->getOperand(0);
2252 SDValue N1 = N->getOperand(1);
2253 EVT VT = N->getValueType(0);
2257 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2260 // fold (udiv c1, c2) -> c1/c2
2261 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2262 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2264 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT,
2267 // fold (udiv x, (1 << c)) -> x >>u c
2268 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) {
2270 return DAG.getNode(ISD::SRL, DL, VT, N0,
2271 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2272 getShiftAmountTy(N0.getValueType())));
2274 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2275 if (N1.getOpcode() == ISD::SHL) {
2276 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2277 if (SHC->getAPIntValue().isPowerOf2()) {
2278 EVT ADDVT = N1.getOperand(1).getValueType();
2280 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2282 DAG.getConstant(SHC->getAPIntValue()
2285 AddToWorklist(Add.getNode());
2286 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2291 // fold (udiv x, c) -> alternate
2292 bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
2293 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), MinSize))
2294 if (SDValue Op = BuildUDIV(N))
2298 if (N0.getOpcode() == ISD::UNDEF)
2299 return DAG.getConstant(0, SDLoc(N), VT);
2300 // X / undef -> undef
2301 if (N1.getOpcode() == ISD::UNDEF)
2307 SDValue DAGCombiner::visitSREM(SDNode *N) {
2308 SDValue N0 = N->getOperand(0);
2309 SDValue N1 = N->getOperand(1);
2310 EVT VT = N->getValueType(0);
2312 // fold (srem c1, c2) -> c1%c2
2313 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2314 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2316 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT,
2319 // If we know the sign bits of both operands are zero, strength reduce to a
2320 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2321 if (!VT.isVector()) {
2322 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2323 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2326 // If X/C can be simplified by the division-by-constant logic, lower
2327 // X%C to the equivalent of X-X/C*C.
2328 if (N1C && !N1C->isNullValue()) {
2329 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2330 AddToWorklist(Div.getNode());
2331 SDValue OptimizedDiv = combine(Div.getNode());
2332 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2333 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2335 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2336 AddToWorklist(Mul.getNode());
2342 if (N0.getOpcode() == ISD::UNDEF)
2343 return DAG.getConstant(0, SDLoc(N), VT);
2344 // X % undef -> undef
2345 if (N1.getOpcode() == ISD::UNDEF)
2351 SDValue DAGCombiner::visitUREM(SDNode *N) {
2352 SDValue N0 = N->getOperand(0);
2353 SDValue N1 = N->getOperand(1);
2354 EVT VT = N->getValueType(0);
2356 // fold (urem c1, c2) -> c1%c2
2357 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2358 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2360 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT,
2363 // fold (urem x, pow2) -> (and x, pow2-1)
2364 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2365 N1C->getAPIntValue().isPowerOf2()) {
2367 return DAG.getNode(ISD::AND, DL, VT, N0,
2368 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2370 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2371 if (N1.getOpcode() == ISD::SHL) {
2372 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2373 if (SHC->getAPIntValue().isPowerOf2()) {
2376 DAG.getNode(ISD::ADD, DL, VT, N1,
2377 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2379 AddToWorklist(Add.getNode());
2380 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2385 // If X/C can be simplified by the division-by-constant logic, lower
2386 // X%C to the equivalent of X-X/C*C.
2387 if (N1C && !N1C->isNullValue()) {
2388 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2389 AddToWorklist(Div.getNode());
2390 SDValue OptimizedDiv = combine(Div.getNode());
2391 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2392 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2394 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2395 AddToWorklist(Mul.getNode());
2401 if (N0.getOpcode() == ISD::UNDEF)
2402 return DAG.getConstant(0, SDLoc(N), VT);
2403 // X % undef -> undef
2404 if (N1.getOpcode() == ISD::UNDEF)
2410 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2411 SDValue N0 = N->getOperand(0);
2412 SDValue N1 = N->getOperand(1);
2413 EVT VT = N->getValueType(0);
2416 // fold (mulhs x, 0) -> 0
2417 if (isNullConstant(N1))
2419 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2420 if (isOneConstant(N1)) {
2422 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2423 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2425 getShiftAmountTy(N0.getValueType())));
2427 // fold (mulhs x, undef) -> 0
2428 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2429 return DAG.getConstant(0, SDLoc(N), VT);
2431 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2433 if (VT.isSimple() && !VT.isVector()) {
2434 MVT Simple = VT.getSimpleVT();
2435 unsigned SimpleSize = Simple.getSizeInBits();
2436 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2437 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2438 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2439 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2440 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2441 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2442 DAG.getConstant(SimpleSize, DL,
2443 getShiftAmountTy(N1.getValueType())));
2444 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2451 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2452 SDValue N0 = N->getOperand(0);
2453 SDValue N1 = N->getOperand(1);
2454 EVT VT = N->getValueType(0);
2457 // fold (mulhu x, 0) -> 0
2458 if (isNullConstant(N1))
2460 // fold (mulhu x, 1) -> 0
2461 if (isOneConstant(N1))
2462 return DAG.getConstant(0, DL, N0.getValueType());
2463 // fold (mulhu x, undef) -> 0
2464 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2465 return DAG.getConstant(0, DL, VT);
2467 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2469 if (VT.isSimple() && !VT.isVector()) {
2470 MVT Simple = VT.getSimpleVT();
2471 unsigned SimpleSize = Simple.getSizeInBits();
2472 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2473 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2474 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2475 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2476 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2477 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2478 DAG.getConstant(SimpleSize, DL,
2479 getShiftAmountTy(N1.getValueType())));
2480 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2487 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2488 /// give the opcodes for the two computations that are being performed. Return
2489 /// true if a simplification was made.
2490 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2492 // If the high half is not needed, just compute the low half.
2493 bool HiExists = N->hasAnyUseOfValue(1);
2495 (!LegalOperations ||
2496 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2497 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2498 return CombineTo(N, Res, Res);
2501 // If the low half is not needed, just compute the high half.
2502 bool LoExists = N->hasAnyUseOfValue(0);
2504 (!LegalOperations ||
2505 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2506 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2507 return CombineTo(N, Res, Res);
2510 // If both halves are used, return as it is.
2511 if (LoExists && HiExists)
2514 // If the two computed results can be simplified separately, separate them.
2516 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2517 AddToWorklist(Lo.getNode());
2518 SDValue LoOpt = combine(Lo.getNode());
2519 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2520 (!LegalOperations ||
2521 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2522 return CombineTo(N, LoOpt, LoOpt);
2526 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2527 AddToWorklist(Hi.getNode());
2528 SDValue HiOpt = combine(Hi.getNode());
2529 if (HiOpt.getNode() && HiOpt != Hi &&
2530 (!LegalOperations ||
2531 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2532 return CombineTo(N, HiOpt, HiOpt);
2538 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2539 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2542 EVT VT = N->getValueType(0);
2545 // If the type is twice as wide is legal, transform the mulhu to a wider
2546 // multiply plus a shift.
2547 if (VT.isSimple() && !VT.isVector()) {
2548 MVT Simple = VT.getSimpleVT();
2549 unsigned SimpleSize = Simple.getSizeInBits();
2550 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2551 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2552 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2553 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2554 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2555 // Compute the high part as N1.
2556 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2557 DAG.getConstant(SimpleSize, DL,
2558 getShiftAmountTy(Lo.getValueType())));
2559 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2560 // Compute the low part as N0.
2561 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2562 return CombineTo(N, Lo, Hi);
2569 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2570 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2573 EVT VT = N->getValueType(0);
2576 // If the type is twice as wide is legal, transform the mulhu to a wider
2577 // multiply plus a shift.
2578 if (VT.isSimple() && !VT.isVector()) {
2579 MVT Simple = VT.getSimpleVT();
2580 unsigned SimpleSize = Simple.getSizeInBits();
2581 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2582 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2583 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2584 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2585 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2586 // Compute the high part as N1.
2587 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2588 DAG.getConstant(SimpleSize, DL,
2589 getShiftAmountTy(Lo.getValueType())));
2590 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2591 // Compute the low part as N0.
2592 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2593 return CombineTo(N, Lo, Hi);
2600 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2601 // (smulo x, 2) -> (saddo x, x)
2602 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2603 if (C2->getAPIntValue() == 2)
2604 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2605 N->getOperand(0), N->getOperand(0));
2610 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2611 // (umulo x, 2) -> (uaddo x, x)
2612 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2613 if (C2->getAPIntValue() == 2)
2614 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2615 N->getOperand(0), N->getOperand(0));
2620 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2621 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM))
2627 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2628 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM))
2634 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2635 SDValue N0 = N->getOperand(0);
2636 SDValue N1 = N->getOperand(1);
2637 EVT VT = N0.getValueType();
2641 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2644 // fold (add c1, c2) -> c1+c2
2645 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2646 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2648 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2650 // canonicalize constant to RHS
2651 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2652 !isConstantIntBuildVectorOrConstantInt(N1))
2653 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2658 /// If this is a binary operator with two operands of the same opcode, try to
2660 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2661 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2662 EVT VT = N0.getValueType();
2663 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2665 // Bail early if none of these transforms apply.
2666 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2668 // For each of OP in AND/OR/XOR:
2669 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2670 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2671 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2672 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2673 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2675 // do not sink logical op inside of a vector extend, since it may combine
2677 EVT Op0VT = N0.getOperand(0).getValueType();
2678 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2679 N0.getOpcode() == ISD::SIGN_EXTEND ||
2680 N0.getOpcode() == ISD::BSWAP ||
2681 // Avoid infinite looping with PromoteIntBinOp.
2682 (N0.getOpcode() == ISD::ANY_EXTEND &&
2683 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2684 (N0.getOpcode() == ISD::TRUNCATE &&
2685 (!TLI.isZExtFree(VT, Op0VT) ||
2686 !TLI.isTruncateFree(Op0VT, VT)) &&
2687 TLI.isTypeLegal(Op0VT))) &&
2689 Op0VT == N1.getOperand(0).getValueType() &&
2690 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2691 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2692 N0.getOperand(0).getValueType(),
2693 N0.getOperand(0), N1.getOperand(0));
2694 AddToWorklist(ORNode.getNode());
2695 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2698 // For each of OP in SHL/SRL/SRA/AND...
2699 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2700 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2701 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2702 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2703 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2704 N0.getOperand(1) == N1.getOperand(1)) {
2705 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2706 N0.getOperand(0).getValueType(),
2707 N0.getOperand(0), N1.getOperand(0));
2708 AddToWorklist(ORNode.getNode());
2709 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2710 ORNode, N0.getOperand(1));
2713 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2714 // Only perform this optimization after type legalization and before
2715 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2716 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2717 // we don't want to undo this promotion.
2718 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2720 if ((N0.getOpcode() == ISD::BITCAST ||
2721 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2722 Level == AfterLegalizeTypes) {
2723 SDValue In0 = N0.getOperand(0);
2724 SDValue In1 = N1.getOperand(0);
2725 EVT In0Ty = In0.getValueType();
2726 EVT In1Ty = In1.getValueType();
2728 // If both incoming values are integers, and the original types are the
2730 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2731 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2732 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2733 AddToWorklist(Op.getNode());
2738 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2739 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2740 // If both shuffles use the same mask, and both shuffle within a single
2741 // vector, then it is worthwhile to move the swizzle after the operation.
2742 // The type-legalizer generates this pattern when loading illegal
2743 // vector types from memory. In many cases this allows additional shuffle
2745 // There are other cases where moving the shuffle after the xor/and/or
2746 // is profitable even if shuffles don't perform a swizzle.
2747 // If both shuffles use the same mask, and both shuffles have the same first
2748 // or second operand, then it might still be profitable to move the shuffle
2749 // after the xor/and/or operation.
2750 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2751 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2752 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2754 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2755 "Inputs to shuffles are not the same type");
2757 // Check that both shuffles use the same mask. The masks are known to be of
2758 // the same length because the result vector type is the same.
2759 // Check also that shuffles have only one use to avoid introducing extra
2761 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2762 SVN0->getMask().equals(SVN1->getMask())) {
2763 SDValue ShOp = N0->getOperand(1);
2765 // Don't try to fold this node if it requires introducing a
2766 // build vector of all zeros that might be illegal at this stage.
2767 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2769 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2774 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2775 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2776 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2777 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2778 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2779 N0->getOperand(0), N1->getOperand(0));
2780 AddToWorklist(NewNode.getNode());
2781 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2782 &SVN0->getMask()[0]);
2785 // Don't try to fold this node if it requires introducing a
2786 // build vector of all zeros that might be illegal at this stage.
2787 ShOp = N0->getOperand(0);
2788 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2790 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2795 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2796 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2797 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2798 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2799 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2800 N0->getOperand(1), N1->getOperand(1));
2801 AddToWorklist(NewNode.getNode());
2802 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2803 &SVN0->getMask()[0]);
2811 /// This contains all DAGCombine rules which reduce two values combined by
2812 /// an And operation to a single value. This makes them reusable in the context
2813 /// of visitSELECT(). Rules involving constants are not included as
2814 /// visitSELECT() already handles those cases.
2815 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2816 SDNode *LocReference) {
2817 EVT VT = N1.getValueType();
2819 // fold (and x, undef) -> 0
2820 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2821 return DAG.getConstant(0, SDLoc(LocReference), VT);
2822 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2823 SDValue LL, LR, RL, RR, CC0, CC1;
2824 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2825 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2826 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2828 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2829 LL.getValueType().isInteger()) {
2830 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2831 if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2832 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2833 LR.getValueType(), LL, RL);
2834 AddToWorklist(ORNode.getNode());
2835 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2837 if (isAllOnesConstant(LR)) {
2838 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2839 if (Op1 == ISD::SETEQ) {
2840 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2841 LR.getValueType(), LL, RL);
2842 AddToWorklist(ANDNode.getNode());
2843 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2845 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2846 if (Op1 == ISD::SETGT) {
2847 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2848 LR.getValueType(), LL, RL);
2849 AddToWorklist(ORNode.getNode());
2850 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2854 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2855 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2856 Op0 == Op1 && LL.getValueType().isInteger() &&
2857 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2858 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2860 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2861 LL, DAG.getConstant(1, DL,
2862 LL.getValueType()));
2863 AddToWorklist(ADDNode.getNode());
2864 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2865 DAG.getConstant(2, DL, LL.getValueType()),
2868 // canonicalize equivalent to ll == rl
2869 if (LL == RR && LR == RL) {
2870 Op1 = ISD::getSetCCSwappedOperands(Op1);
2873 if (LL == RL && LR == RR) {
2874 bool isInteger = LL.getValueType().isInteger();
2875 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2876 if (Result != ISD::SETCC_INVALID &&
2877 (!LegalOperations ||
2878 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2879 TLI.isOperationLegal(ISD::SETCC,
2880 getSetCCResultType(N0.getSimpleValueType())))))
2881 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2886 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2887 VT.getSizeInBits() <= 64) {
2888 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2889 APInt ADDC = ADDI->getAPIntValue();
2890 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2891 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2892 // immediate for an add, but it is legal if its top c2 bits are set,
2893 // transform the ADD so the immediate doesn't need to be materialized
2895 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2896 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2897 SRLI->getZExtValue());
2898 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2900 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2903 DAG.getNode(ISD::ADD, DL, VT,
2904 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2905 CombineTo(N0.getNode(), NewAdd);
2906 // Return N so it doesn't get rechecked!
2907 return SDValue(LocReference, 0);
2918 SDValue DAGCombiner::visitAND(SDNode *N) {
2919 SDValue N0 = N->getOperand(0);
2920 SDValue N1 = N->getOperand(1);
2921 EVT VT = N1.getValueType();
2924 if (VT.isVector()) {
2925 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2928 // fold (and x, 0) -> 0, vector edition
2929 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2930 // do not return N0, because undef node may exist in N0
2931 return DAG.getConstant(
2932 APInt::getNullValue(
2933 N0.getValueType().getScalarType().getSizeInBits()),
2934 SDLoc(N), N0.getValueType());
2935 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2936 // do not return N1, because undef node may exist in N1
2937 return DAG.getConstant(
2938 APInt::getNullValue(
2939 N1.getValueType().getScalarType().getSizeInBits()),
2940 SDLoc(N), N1.getValueType());
2942 // fold (and x, -1) -> x, vector edition
2943 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2945 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2949 // fold (and c1, c2) -> c1&c2
2950 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2951 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2952 if (N0C && N1C && !N1C->isOpaque())
2953 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2954 // canonicalize constant to RHS
2955 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2956 !isConstantIntBuildVectorOrConstantInt(N1))
2957 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2958 // fold (and x, -1) -> x
2959 if (isAllOnesConstant(N1))
2961 // if (and x, c) is known to be zero, return 0
2962 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2963 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2964 APInt::getAllOnesValue(BitWidth)))
2965 return DAG.getConstant(0, SDLoc(N), VT);
2967 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2969 // fold (and (or x, C), D) -> D if (C & D) == D
2970 if (N1C && N0.getOpcode() == ISD::OR)
2971 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2972 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2974 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2975 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2976 SDValue N0Op0 = N0.getOperand(0);
2977 APInt Mask = ~N1C->getAPIntValue();
2978 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2979 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2980 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2981 N0.getValueType(), N0Op0);
2983 // Replace uses of the AND with uses of the Zero extend node.
2986 // We actually want to replace all uses of the any_extend with the
2987 // zero_extend, to avoid duplicating things. This will later cause this
2988 // AND to be folded.
2989 CombineTo(N0.getNode(), Zext);
2990 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2993 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2994 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2995 // already be zero by virtue of the width of the base type of the load.
2997 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2999 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3000 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
3001 N0.getOpcode() == ISD::LOAD) {
3002 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3003 N0 : N0.getOperand(0) );
3005 // Get the constant (if applicable) the zero'th operand is being ANDed with.
3006 // This can be a pure constant or a vector splat, in which case we treat the
3007 // vector as a scalar and use the splat value.
3008 APInt Constant = APInt::getNullValue(1);
3009 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3010 Constant = C->getAPIntValue();
3011 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3012 APInt SplatValue, SplatUndef;
3013 unsigned SplatBitSize;
3015 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3016 SplatBitSize, HasAnyUndefs);
3018 // Undef bits can contribute to a possible optimisation if set, so
3020 SplatValue |= SplatUndef;
3022 // The splat value may be something like "0x00FFFFFF", which means 0 for
3023 // the first vector value and FF for the rest, repeating. We need a mask
3024 // that will apply equally to all members of the vector, so AND all the
3025 // lanes of the constant together.
3026 EVT VT = Vector->getValueType(0);
3027 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3029 // If the splat value has been compressed to a bitlength lower
3030 // than the size of the vector lane, we need to re-expand it to
3032 if (BitWidth > SplatBitSize)
3033 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3034 SplatBitSize < BitWidth;
3035 SplatBitSize = SplatBitSize * 2)
3036 SplatValue |= SplatValue.shl(SplatBitSize);
3038 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3039 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3040 if (SplatBitSize % BitWidth == 0) {
3041 Constant = APInt::getAllOnesValue(BitWidth);
3042 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3043 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3048 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3049 // actually legal and isn't going to get expanded, else this is a false
3051 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3052 Load->getValueType(0),
3053 Load->getMemoryVT());
3055 // Resize the constant to the same size as the original memory access before
3056 // extension. If it is still the AllOnesValue then this AND is completely
3059 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3062 switch (Load->getExtensionType()) {
3063 default: B = false; break;
3064 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3066 case ISD::NON_EXTLOAD: B = true; break;
3069 if (B && Constant.isAllOnesValue()) {
3070 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3071 // preserve semantics once we get rid of the AND.
3072 SDValue NewLoad(Load, 0);
3073 if (Load->getExtensionType() == ISD::EXTLOAD) {
3074 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3075 Load->getValueType(0), SDLoc(Load),
3076 Load->getChain(), Load->getBasePtr(),
3077 Load->getOffset(), Load->getMemoryVT(),
3078 Load->getMemOperand());
3079 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3080 if (Load->getNumValues() == 3) {
3081 // PRE/POST_INC loads have 3 values.
3082 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3083 NewLoad.getValue(2) };
3084 CombineTo(Load, To, 3, true);
3086 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3090 // Fold the AND away, taking care not to fold to the old load node if we
3092 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3094 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3098 // fold (and (load x), 255) -> (zextload x, i8)
3099 // fold (and (extload x, i16), 255) -> (zextload x, i8)
3100 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3101 if (N1C && (N0.getOpcode() == ISD::LOAD ||
3102 (N0.getOpcode() == ISD::ANY_EXTEND &&
3103 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3104 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3105 LoadSDNode *LN0 = HasAnyExt
3106 ? cast<LoadSDNode>(N0.getOperand(0))
3107 : cast<LoadSDNode>(N0);
3108 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3109 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3110 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3111 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3112 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3113 EVT LoadedVT = LN0->getMemoryVT();
3114 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3116 if (ExtVT == LoadedVT &&
3117 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3121 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3122 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3123 LN0->getMemOperand());
3125 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3126 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3129 // Do not change the width of a volatile load.
3130 // Do not generate loads of non-round integer types since these can
3131 // be expensive (and would be wrong if the type is not byte sized).
3132 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3133 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3135 EVT PtrType = LN0->getOperand(1).getValueType();
3137 unsigned Alignment = LN0->getAlignment();
3138 SDValue NewPtr = LN0->getBasePtr();
3140 // For big endian targets, we need to add an offset to the pointer
3141 // to load the correct bytes. For little endian systems, we merely
3142 // need to read fewer bytes from the same pointer.
3143 if (DAG.getDataLayout().isBigEndian()) {
3144 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3145 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3146 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3148 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3149 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3150 Alignment = MinAlign(Alignment, PtrOff);
3153 AddToWorklist(NewPtr.getNode());
3156 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3157 LN0->getChain(), NewPtr,
3158 LN0->getPointerInfo(),
3159 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3160 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3162 CombineTo(LN0, Load, Load.getValue(1));
3163 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3169 if (SDValue Combined = visitANDLike(N0, N1, N))
3172 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3173 if (N0.getOpcode() == N1.getOpcode())
3174 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3177 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3178 // fold (and (sra)) -> (and (srl)) when possible.
3179 if (!VT.isVector() &&
3180 SimplifyDemandedBits(SDValue(N, 0)))
3181 return SDValue(N, 0);
3183 // fold (zext_inreg (extload x)) -> (zextload x)
3184 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3185 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3186 EVT MemVT = LN0->getMemoryVT();
3187 // If we zero all the possible extended bits, then we can turn this into
3188 // a zextload if we are running before legalize or the operation is legal.
3189 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3190 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3191 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3192 ((!LegalOperations && !LN0->isVolatile()) ||
3193 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3194 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3195 LN0->getChain(), LN0->getBasePtr(),
3196 MemVT, LN0->getMemOperand());
3198 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3199 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3202 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3203 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3205 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3206 EVT MemVT = LN0->getMemoryVT();
3207 // If we zero all the possible extended bits, then we can turn this into
3208 // a zextload if we are running before legalize or the operation is legal.
3209 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3210 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3211 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3212 ((!LegalOperations && !LN0->isVolatile()) ||
3213 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3214 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3215 LN0->getChain(), LN0->getBasePtr(),
3216 MemVT, LN0->getMemOperand());
3218 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3219 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3222 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3223 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3224 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3225 N0.getOperand(1), false);
3226 if (BSwap.getNode())
3233 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3234 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3235 bool DemandHighBits) {
3236 if (!LegalOperations)
3239 EVT VT = N->getValueType(0);
3240 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3242 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3245 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3246 bool LookPassAnd0 = false;
3247 bool LookPassAnd1 = false;
3248 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3250 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3252 if (N0.getOpcode() == ISD::AND) {
3253 if (!N0.getNode()->hasOneUse())
3255 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3256 if (!N01C || N01C->getZExtValue() != 0xFF00)
3258 N0 = N0.getOperand(0);
3259 LookPassAnd0 = true;
3262 if (N1.getOpcode() == ISD::AND) {
3263 if (!N1.getNode()->hasOneUse())
3265 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3266 if (!N11C || N11C->getZExtValue() != 0xFF)
3268 N1 = N1.getOperand(0);
3269 LookPassAnd1 = true;
3272 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3274 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3276 if (!N0.getNode()->hasOneUse() ||
3277 !N1.getNode()->hasOneUse())
3280 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3281 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3284 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3287 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3288 SDValue N00 = N0->getOperand(0);
3289 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3290 if (!N00.getNode()->hasOneUse())
3292 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3293 if (!N001C || N001C->getZExtValue() != 0xFF)
3295 N00 = N00.getOperand(0);
3296 LookPassAnd0 = true;
3299 SDValue N10 = N1->getOperand(0);
3300 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3301 if (!N10.getNode()->hasOneUse())
3303 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3304 if (!N101C || N101C->getZExtValue() != 0xFF00)
3306 N10 = N10.getOperand(0);
3307 LookPassAnd1 = true;
3313 // Make sure everything beyond the low halfword gets set to zero since the SRL
3314 // 16 will clear the top bits.
3315 unsigned OpSizeInBits = VT.getSizeInBits();
3316 if (DemandHighBits && OpSizeInBits > 16) {
3317 // If the left-shift isn't masked out then the only way this is a bswap is
3318 // if all bits beyond the low 8 are 0. In that case the entire pattern
3319 // reduces to a left shift anyway: leave it for other parts of the combiner.
3323 // However, if the right shift isn't masked out then it might be because
3324 // it's not needed. See if we can spot that too.
3325 if (!LookPassAnd1 &&
3326 !DAG.MaskedValueIsZero(
3327 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3331 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3332 if (OpSizeInBits > 16) {
3334 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3335 DAG.getConstant(OpSizeInBits - 16, DL,
3336 getShiftAmountTy(VT)));
3341 /// Return true if the specified node is an element that makes up a 32-bit
3342 /// packed halfword byteswap.
3343 /// ((x & 0x000000ff) << 8) |
3344 /// ((x & 0x0000ff00) >> 8) |
3345 /// ((x & 0x00ff0000) << 8) |
3346 /// ((x & 0xff000000) >> 8)
3347 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3348 if (!N.getNode()->hasOneUse())
3351 unsigned Opc = N.getOpcode();
3352 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3355 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3360 switch (N1C->getZExtValue()) {
3363 case 0xFF: Num = 0; break;
3364 case 0xFF00: Num = 1; break;
3365 case 0xFF0000: Num = 2; break;
3366 case 0xFF000000: Num = 3; break;
3369 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3370 SDValue N0 = N.getOperand(0);
3371 if (Opc == ISD::AND) {
3372 if (Num == 0 || Num == 2) {
3374 // (x >> 8) & 0xff0000
3375 if (N0.getOpcode() != ISD::SRL)
3377 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3378 if (!C || C->getZExtValue() != 8)
3381 // (x << 8) & 0xff00
3382 // (x << 8) & 0xff000000
3383 if (N0.getOpcode() != ISD::SHL)
3385 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3386 if (!C || C->getZExtValue() != 8)
3389 } else if (Opc == ISD::SHL) {
3391 // (x & 0xff0000) << 8
3392 if (Num != 0 && Num != 2)
3394 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3395 if (!C || C->getZExtValue() != 8)
3397 } else { // Opc == ISD::SRL
3398 // (x & 0xff00) >> 8
3399 // (x & 0xff000000) >> 8
3400 if (Num != 1 && Num != 3)
3402 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3403 if (!C || C->getZExtValue() != 8)
3410 Parts[Num] = N0.getOperand(0).getNode();
3414 /// Match a 32-bit packed halfword bswap. That is
3415 /// ((x & 0x000000ff) << 8) |
3416 /// ((x & 0x0000ff00) >> 8) |
3417 /// ((x & 0x00ff0000) << 8) |
3418 /// ((x & 0xff000000) >> 8)
3419 /// => (rotl (bswap x), 16)
3420 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3421 if (!LegalOperations)
3424 EVT VT = N->getValueType(0);
3427 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3431 // (or (or (and), (and)), (or (and), (and)))
3432 // (or (or (or (and), (and)), (and)), (and))
3433 if (N0.getOpcode() != ISD::OR)
3435 SDValue N00 = N0.getOperand(0);
3436 SDValue N01 = N0.getOperand(1);
3437 SDNode *Parts[4] = {};
3439 if (N1.getOpcode() == ISD::OR &&
3440 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3441 // (or (or (and), (and)), (or (and), (and)))
3442 SDValue N000 = N00.getOperand(0);
3443 if (!isBSwapHWordElement(N000, Parts))
3446 SDValue N001 = N00.getOperand(1);
3447 if (!isBSwapHWordElement(N001, Parts))
3449 SDValue N010 = N01.getOperand(0);
3450 if (!isBSwapHWordElement(N010, Parts))
3452 SDValue N011 = N01.getOperand(1);
3453 if (!isBSwapHWordElement(N011, Parts))
3456 // (or (or (or (and), (and)), (and)), (and))
3457 if (!isBSwapHWordElement(N1, Parts))
3459 if (!isBSwapHWordElement(N01, Parts))
3461 if (N00.getOpcode() != ISD::OR)
3463 SDValue N000 = N00.getOperand(0);
3464 if (!isBSwapHWordElement(N000, Parts))
3466 SDValue N001 = N00.getOperand(1);
3467 if (!isBSwapHWordElement(N001, Parts))
3471 // Make sure the parts are all coming from the same node.
3472 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3476 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3477 SDValue(Parts[0], 0));
3479 // Result of the bswap should be rotated by 16. If it's not legal, then
3480 // do (x << 16) | (x >> 16).
3481 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3482 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3483 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3484 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3485 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3486 return DAG.getNode(ISD::OR, DL, VT,
3487 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3488 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3491 /// This contains all DAGCombine rules which reduce two values combined by
3492 /// an Or operation to a single value \see visitANDLike().
3493 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3494 EVT VT = N1.getValueType();
3495 // fold (or x, undef) -> -1
3496 if (!LegalOperations &&
3497 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3498 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3499 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3500 SDLoc(LocReference), VT);
3502 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3503 SDValue LL, LR, RL, RR, CC0, CC1;
3504 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3505 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3506 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3508 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3509 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3510 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3511 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3512 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3513 LR.getValueType(), LL, RL);
3514 AddToWorklist(ORNode.getNode());
3515 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3517 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3518 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3519 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3520 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3521 LR.getValueType(), LL, RL);
3522 AddToWorklist(ANDNode.getNode());
3523 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3526 // canonicalize equivalent to ll == rl
3527 if (LL == RR && LR == RL) {
3528 Op1 = ISD::getSetCCSwappedOperands(Op1);
3531 if (LL == RL && LR == RR) {
3532 bool isInteger = LL.getValueType().isInteger();
3533 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3534 if (Result != ISD::SETCC_INVALID &&
3535 (!LegalOperations ||
3536 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3537 TLI.isOperationLegal(ISD::SETCC,
3538 getSetCCResultType(N0.getValueType())))))
3539 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3544 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3545 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3546 // Don't increase # computations.
3547 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3548 // We can only do this xform if we know that bits from X that are set in C2
3549 // but not in C1 are already zero. Likewise for Y.
3550 if (const ConstantSDNode *N0O1C =
3551 getAsNonOpaqueConstant(N0.getOperand(1))) {
3552 if (const ConstantSDNode *N1O1C =
3553 getAsNonOpaqueConstant(N1.getOperand(1))) {
3554 // We can only do this xform if we know that bits from X that are set in
3555 // C2 but not in C1 are already zero. Likewise for Y.
3556 const APInt &LHSMask = N0O1C->getAPIntValue();
3557 const APInt &RHSMask = N1O1C->getAPIntValue();
3559 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3560 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3561 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3562 N0.getOperand(0), N1.getOperand(0));
3563 SDLoc DL(LocReference);
3564 return DAG.getNode(ISD::AND, DL, VT, X,
3565 DAG.getConstant(LHSMask | RHSMask, DL, VT));
3571 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3572 if (N0.getOpcode() == ISD::AND &&
3573 N1.getOpcode() == ISD::AND &&
3574 N0.getOperand(0) == N1.getOperand(0) &&
3575 // Don't increase # computations.
3576 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3577 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3578 N0.getOperand(1), N1.getOperand(1));
3579 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3585 SDValue DAGCombiner::visitOR(SDNode *N) {
3586 SDValue N0 = N->getOperand(0);
3587 SDValue N1 = N->getOperand(1);
3588 EVT VT = N1.getValueType();
3591 if (VT.isVector()) {
3592 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3595 // fold (or x, 0) -> x, vector edition
3596 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3598 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3601 // fold (or x, -1) -> -1, vector edition
3602 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3603 // do not return N0, because undef node may exist in N0
3604 return DAG.getConstant(
3605 APInt::getAllOnesValue(
3606 N0.getValueType().getScalarType().getSizeInBits()),
3607 SDLoc(N), N0.getValueType());
3608 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3609 // do not return N1, because undef node may exist in N1
3610 return DAG.getConstant(
3611 APInt::getAllOnesValue(
3612 N1.getValueType().getScalarType().getSizeInBits()),
3613 SDLoc(N), N1.getValueType());
3615 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3616 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3617 // Do this only if the resulting shuffle is legal.
3618 if (isa<ShuffleVectorSDNode>(N0) &&
3619 isa<ShuffleVectorSDNode>(N1) &&
3620 // Avoid folding a node with illegal type.
3621 TLI.isTypeLegal(VT) &&
3622 N0->getOperand(1) == N1->getOperand(1) &&
3623 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3624 bool CanFold = true;
3625 unsigned NumElts = VT.getVectorNumElements();
3626 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3627 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3628 // We construct two shuffle masks:
3629 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3630 // and N1 as the second operand.
3631 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3632 // and N0 as the second operand.
3633 // We do this because OR is commutable and therefore there might be
3634 // two ways to fold this node into a shuffle.
3635 SmallVector<int,4> Mask1;
3636 SmallVector<int,4> Mask2;
3638 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3639 int M0 = SV0->getMaskElt(i);
3640 int M1 = SV1->getMaskElt(i);
3642 // Both shuffle indexes are undef. Propagate Undef.
3643 if (M0 < 0 && M1 < 0) {
3644 Mask1.push_back(M0);
3645 Mask2.push_back(M0);
3649 if (M0 < 0 || M1 < 0 ||
3650 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3651 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3656 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3657 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3661 // Fold this sequence only if the resulting shuffle is 'legal'.
3662 if (TLI.isShuffleMaskLegal(Mask1, VT))
3663 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3664 N1->getOperand(0), &Mask1[0]);
3665 if (TLI.isShuffleMaskLegal(Mask2, VT))
3666 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3667 N0->getOperand(0), &Mask2[0]);
3672 // fold (or c1, c2) -> c1|c2
3673 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3674 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3675 if (N0C && N1C && !N1C->isOpaque())
3676 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3677 // canonicalize constant to RHS
3678 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3679 !isConstantIntBuildVectorOrConstantInt(N1))
3680 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3681 // fold (or x, 0) -> x
3682 if (isNullConstant(N1))
3684 // fold (or x, -1) -> -1
3685 if (isAllOnesConstant(N1))
3687 // fold (or x, c) -> c iff (x & ~c) == 0
3688 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3691 if (SDValue Combined = visitORLike(N0, N1, N))
3694 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3695 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3697 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3701 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3703 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3704 // iff (c1 & c2) == 0.
3705 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3706 isa<ConstantSDNode>(N0.getOperand(1))) {
3707 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3708 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3709 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3712 ISD::AND, SDLoc(N), VT,
3713 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3717 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3718 if (N0.getOpcode() == N1.getOpcode())
3719 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3722 // See if this is some rotate idiom.
3723 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3724 return SDValue(Rot, 0);
3726 // Simplify the operands using demanded-bits information.
3727 if (!VT.isVector() &&
3728 SimplifyDemandedBits(SDValue(N, 0)))
3729 return SDValue(N, 0);
3734 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3735 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3736 if (Op.getOpcode() == ISD::AND) {
3737 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3738 Mask = Op.getOperand(1);
3739 Op = Op.getOperand(0);
3745 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3753 // Return true if we can prove that, whenever Neg and Pos are both in the
3754 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3755 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3757 // (or (shift1 X, Neg), (shift2 X, Pos))
3759 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3760 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3761 // to consider shift amounts with defined behavior.
3762 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3763 // If OpSize is a power of 2 then:
3765 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3766 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3768 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3769 // for the stronger condition:
3771 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3773 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3774 // we can just replace Neg with Neg' for the rest of the function.
3776 // In other cases we check for the even stronger condition:
3778 // Neg == OpSize - Pos [B]
3780 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3781 // behavior if Pos == 0 (and consequently Neg == OpSize).
3783 // We could actually use [A] whenever OpSize is a power of 2, but the
3784 // only extra cases that it would match are those uninteresting ones
3785 // where Neg and Pos are never in range at the same time. E.g. for
3786 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3787 // as well as (sub 32, Pos), but:
3789 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3791 // always invokes undefined behavior for 32-bit X.
3793 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3794 unsigned MaskLoBits = 0;
3795 if (Neg.getOpcode() == ISD::AND &&
3796 isPowerOf2_64(OpSize) &&
3797 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3798 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3799 Neg = Neg.getOperand(0);
3800 MaskLoBits = Log2_64(OpSize);
3803 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3804 if (Neg.getOpcode() != ISD::SUB)
3806 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3809 SDValue NegOp1 = Neg.getOperand(1);
3811 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3812 // Pos'. The truncation is redundant for the purpose of the equality.
3814 Pos.getOpcode() == ISD::AND &&
3815 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3816 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3817 Pos = Pos.getOperand(0);
3819 // The condition we need is now:
3821 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3823 // If NegOp1 == Pos then we need:
3825 // OpSize & Mask == NegC & Mask
3827 // (because "x & Mask" is a truncation and distributes through subtraction).
3830 Width = NegC->getAPIntValue();
3831 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3832 // Then the condition we want to prove becomes:
3834 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3836 // which, again because "x & Mask" is a truncation, becomes:
3838 // NegC & Mask == (OpSize - PosC) & Mask
3839 // OpSize & Mask == (NegC + PosC) & Mask
3840 else if (Pos.getOpcode() == ISD::ADD &&
3841 Pos.getOperand(0) == NegOp1 &&
3842 Pos.getOperand(1).getOpcode() == ISD::Constant)
3843 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3844 NegC->getAPIntValue());
3848 // Now we just need to check that OpSize & Mask == Width & Mask.
3850 // Opsize & Mask is 0 since Mask is Opsize - 1.
3851 return Width.getLoBits(MaskLoBits) == 0;
3852 return Width == OpSize;
3855 // A subroutine of MatchRotate used once we have found an OR of two opposite
3856 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3857 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3858 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3859 // Neg with outer conversions stripped away.
3860 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3861 SDValue Neg, SDValue InnerPos,
3862 SDValue InnerNeg, unsigned PosOpcode,
3863 unsigned NegOpcode, SDLoc DL) {
3864 // fold (or (shl x, (*ext y)),
3865 // (srl x, (*ext (sub 32, y)))) ->
3866 // (rotl x, y) or (rotr x, (sub 32, y))
3868 // fold (or (shl x, (*ext (sub 32, y))),
3869 // (srl x, (*ext y))) ->
3870 // (rotr x, y) or (rotl x, (sub 32, y))
3871 EVT VT = Shifted.getValueType();
3872 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3873 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3874 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3875 HasPos ? Pos : Neg).getNode();
3881 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3882 // idioms for rotate, and if the target supports rotation instructions, generate
3884 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3885 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3886 EVT VT = LHS.getValueType();
3887 if (!TLI.isTypeLegal(VT)) return nullptr;
3889 // The target must have at least one rotate flavor.
3890 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3891 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3892 if (!HasROTL && !HasROTR) return nullptr;
3894 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3895 SDValue LHSShift; // The shift.
3896 SDValue LHSMask; // AND value if any.
3897 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3898 return nullptr; // Not part of a rotate.
3900 SDValue RHSShift; // The shift.
3901 SDValue RHSMask; // AND value if any.
3902 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3903 return nullptr; // Not part of a rotate.
3905 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3906 return nullptr; // Not shifting the same value.
3908 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3909 return nullptr; // Shifts must disagree.
3911 // Canonicalize shl to left side in a shl/srl pair.
3912 if (RHSShift.getOpcode() == ISD::SHL) {
3913 std::swap(LHS, RHS);
3914 std::swap(LHSShift, RHSShift);
3915 std::swap(LHSMask , RHSMask );
3918 unsigned OpSizeInBits = VT.getSizeInBits();
3919 SDValue LHSShiftArg = LHSShift.getOperand(0);
3920 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3921 SDValue RHSShiftArg = RHSShift.getOperand(0);
3922 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3924 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3925 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3926 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3927 RHSShiftAmt.getOpcode() == ISD::Constant) {
3928 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3929 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3930 if ((LShVal + RShVal) != OpSizeInBits)
3933 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3934 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3936 // If there is an AND of either shifted operand, apply it to the result.
3937 if (LHSMask.getNode() || RHSMask.getNode()) {
3938 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3940 if (LHSMask.getNode()) {
3941 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3942 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3944 if (RHSMask.getNode()) {
3945 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3946 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3949 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3952 return Rot.getNode();
3955 // If there is a mask here, and we have a variable shift, we can't be sure
3956 // that we're masking out the right stuff.
3957 if (LHSMask.getNode() || RHSMask.getNode())
3960 // If the shift amount is sign/zext/any-extended just peel it off.
3961 SDValue LExtOp0 = LHSShiftAmt;
3962 SDValue RExtOp0 = RHSShiftAmt;
3963 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3964 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3965 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3966 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3967 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3968 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3969 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3970 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3971 LExtOp0 = LHSShiftAmt.getOperand(0);
3972 RExtOp0 = RHSShiftAmt.getOperand(0);
3975 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3976 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3980 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3981 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3988 SDValue DAGCombiner::visitXOR(SDNode *N) {
3989 SDValue N0 = N->getOperand(0);
3990 SDValue N1 = N->getOperand(1);
3991 EVT VT = N0.getValueType();
3994 if (VT.isVector()) {
3995 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3998 // fold (xor x, 0) -> x, vector edition
3999 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4001 if (ISD::isBuildVectorAllZeros(N1.getNode()))
4005 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4006 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
4007 return DAG.getConstant(0, SDLoc(N), VT);
4008 // fold (xor x, undef) -> undef
4009 if (N0.getOpcode() == ISD::UNDEF)
4011 if (N1.getOpcode() == ISD::UNDEF)
4013 // fold (xor c1, c2) -> c1^c2
4014 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4015 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4017 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4018 // canonicalize constant to RHS
4019 if (isConstantIntBuildVectorOrConstantInt(N0) &&
4020 !isConstantIntBuildVectorOrConstantInt(N1))
4021 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4022 // fold (xor x, 0) -> x
4023 if (isNullConstant(N1))
4026 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4029 // fold !(x cc y) -> (x !cc y)
4030 SDValue LHS, RHS, CC;
4031 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4032 bool isInt = LHS.getValueType().isInteger();
4033 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4036 if (!LegalOperations ||
4037 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4038 switch (N0.getOpcode()) {
4040 llvm_unreachable("Unhandled SetCC Equivalent!");
4042 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4043 case ISD::SELECT_CC:
4044 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4045 N0.getOperand(3), NotCC);
4050 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4051 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4052 N0.getNode()->hasOneUse() &&
4053 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4054 SDValue V = N0.getOperand(0);
4056 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4057 DAG.getConstant(1, DL, V.getValueType()));
4058 AddToWorklist(V.getNode());
4059 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4062 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4063 if (isOneConstant(N1) && VT == MVT::i1 &&
4064 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4065 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4066 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4067 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4068 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4069 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4070 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4071 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4074 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4075 if (isAllOnesConstant(N1) &&
4076 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4077 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4078 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4079 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4080 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4081 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4082 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4083 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4086 // fold (xor (and x, y), y) -> (and (not x), y)
4087 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4088 N0->getOperand(1) == N1) {
4089 SDValue X = N0->getOperand(0);
4090 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4091 AddToWorklist(NotX.getNode());
4092 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4094 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4095 if (N1C && N0.getOpcode() == ISD::XOR) {
4096 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4098 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4099 DAG.getConstant(N1C->getAPIntValue() ^
4100 N00C->getAPIntValue(), DL, VT));
4102 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4104 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4105 DAG.getConstant(N1C->getAPIntValue() ^
4106 N01C->getAPIntValue(), DL, VT));
4109 // fold (xor x, x) -> 0
4111 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4113 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4114 // Here is a concrete example of this equivalence:
4116 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
4117 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4121 // i16 ~1 == 0b1111111111111110
4122 // i16 rol(~1, 14) == 0b1011111111111111
4124 // Some additional tips to help conceptualize this transform:
4125 // - Try to see the operation as placing a single zero in a value of all ones.
4126 // - There exists no value for x which would allow the result to contain zero.
4127 // - Values of x larger than the bitwidth are undefined and do not require a
4128 // consistent result.
4129 // - Pushing the zero left requires shifting one bits in from the right.
4130 // A rotate left of ~1 is a nice way of achieving the desired result.
4131 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4132 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4134 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4138 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4139 if (N0.getOpcode() == N1.getOpcode())
4140 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4143 // Simplify the expression using non-local knowledge.
4144 if (!VT.isVector() &&
4145 SimplifyDemandedBits(SDValue(N, 0)))
4146 return SDValue(N, 0);
4151 /// Handle transforms common to the three shifts, when the shift amount is a
4153 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4154 SDNode *LHS = N->getOperand(0).getNode();
4155 if (!LHS->hasOneUse()) return SDValue();
4157 // We want to pull some binops through shifts, so that we have (and (shift))
4158 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4159 // thing happens with address calculations, so it's important to canonicalize
4161 bool HighBitSet = false; // Can we transform this if the high bit is set?
4163 switch (LHS->getOpcode()) {
4164 default: return SDValue();
4167 HighBitSet = false; // We can only transform sra if the high bit is clear.
4170 HighBitSet = true; // We can only transform sra if the high bit is set.
4173 if (N->getOpcode() != ISD::SHL)
4174 return SDValue(); // only shl(add) not sr[al](add).
4175 HighBitSet = false; // We can only transform sra if the high bit is clear.
4179 // We require the RHS of the binop to be a constant and not opaque as well.
4180 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4181 if (!BinOpCst) return SDValue();
4183 // FIXME: disable this unless the input to the binop is a shift by a constant.
4184 // If it is not a shift, it pessimizes some common cases like:
4186 // void foo(int *X, int i) { X[i & 1235] = 1; }
4187 // int bar(int *X, int i) { return X[i & 255]; }
4188 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4189 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4190 BinOpLHSVal->getOpcode() != ISD::SRA &&
4191 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4192 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4195 EVT VT = N->getValueType(0);
4197 // If this is a signed shift right, and the high bit is modified by the
4198 // logical operation, do not perform the transformation. The highBitSet
4199 // boolean indicates the value of the high bit of the constant which would
4200 // cause it to be modified for this operation.
4201 if (N->getOpcode() == ISD::SRA) {
4202 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4203 if (BinOpRHSSignSet != HighBitSet)
4207 if (!TLI.isDesirableToCommuteWithShift(LHS))
4210 // Fold the constants, shifting the binop RHS by the shift amount.
4211 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4213 LHS->getOperand(1), N->getOperand(1));
4214 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4216 // Create the new shift.
4217 SDValue NewShift = DAG.getNode(N->getOpcode(),
4218 SDLoc(LHS->getOperand(0)),
4219 VT, LHS->getOperand(0), N->getOperand(1));
4221 // Create the new binop.
4222 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4225 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4226 assert(N->getOpcode() == ISD::TRUNCATE);
4227 assert(N->getOperand(0).getOpcode() == ISD::AND);
4229 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4230 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4231 SDValue N01 = N->getOperand(0).getOperand(1);
4233 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4234 if (!N01C->isOpaque()) {
4235 EVT TruncVT = N->getValueType(0);
4236 SDValue N00 = N->getOperand(0).getOperand(0);
4237 APInt TruncC = N01C->getAPIntValue();
4238 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4241 return DAG.getNode(ISD::AND, DL, TruncVT,
4242 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4243 DAG.getConstant(TruncC, DL, TruncVT));
4251 SDValue DAGCombiner::visitRotate(SDNode *N) {
4252 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4253 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4254 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4255 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4256 if (NewOp1.getNode())
4257 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4258 N->getOperand(0), NewOp1);
4263 SDValue DAGCombiner::visitSHL(SDNode *N) {
4264 SDValue N0 = N->getOperand(0);
4265 SDValue N1 = N->getOperand(1);
4266 EVT VT = N0.getValueType();
4267 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4270 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4271 if (VT.isVector()) {
4272 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4275 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4276 // If setcc produces all-one true value then:
4277 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4278 if (N1CV && N1CV->isConstant()) {
4279 if (N0.getOpcode() == ISD::AND) {
4280 SDValue N00 = N0->getOperand(0);
4281 SDValue N01 = N0->getOperand(1);
4282 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4284 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4285 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4286 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4287 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4289 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4292 N1C = isConstOrConstSplat(N1);
4297 // fold (shl c1, c2) -> c1<<c2
4298 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4299 if (N0C && N1C && !N1C->isOpaque())
4300 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4301 // fold (shl 0, x) -> 0
4302 if (isNullConstant(N0))
4304 // fold (shl x, c >= size(x)) -> undef
4305 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4306 return DAG.getUNDEF(VT);
4307 // fold (shl x, 0) -> x
4308 if (N1C && N1C->isNullValue())
4310 // fold (shl undef, x) -> 0
4311 if (N0.getOpcode() == ISD::UNDEF)
4312 return DAG.getConstant(0, SDLoc(N), VT);
4313 // if (shl x, c) is known to be zero, return 0
4314 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4315 APInt::getAllOnesValue(OpSizeInBits)))
4316 return DAG.getConstant(0, SDLoc(N), VT);
4317 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4318 if (N1.getOpcode() == ISD::TRUNCATE &&
4319 N1.getOperand(0).getOpcode() == ISD::AND) {
4320 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4321 if (NewOp1.getNode())
4322 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4325 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4326 return SDValue(N, 0);
4328 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4329 if (N1C && N0.getOpcode() == ISD::SHL) {
4330 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4331 uint64_t c1 = N0C1->getZExtValue();
4332 uint64_t c2 = N1C->getZExtValue();
4334 if (c1 + c2 >= OpSizeInBits)
4335 return DAG.getConstant(0, DL, VT);
4336 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4337 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4341 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4342 // For this to be valid, the second form must not preserve any of the bits
4343 // that are shifted out by the inner shift in the first form. This means
4344 // the outer shift size must be >= the number of bits added by the ext.
4345 // As a corollary, we don't care what kind of ext it is.
4346 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4347 N0.getOpcode() == ISD::ANY_EXTEND ||
4348 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4349 N0.getOperand(0).getOpcode() == ISD::SHL) {
4350 SDValue N0Op0 = N0.getOperand(0);
4351 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4352 uint64_t c1 = N0Op0C1->getZExtValue();
4353 uint64_t c2 = N1C->getZExtValue();
4354 EVT InnerShiftVT = N0Op0.getValueType();
4355 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4356 if (c2 >= OpSizeInBits - InnerShiftSize) {
4358 if (c1 + c2 >= OpSizeInBits)
4359 return DAG.getConstant(0, DL, VT);
4360 return DAG.getNode(ISD::SHL, DL, VT,
4361 DAG.getNode(N0.getOpcode(), DL, VT,
4362 N0Op0->getOperand(0)),
4363 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4368 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4369 // Only fold this if the inner zext has no other uses to avoid increasing
4370 // the total number of instructions.
4371 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4372 N0.getOperand(0).getOpcode() == ISD::SRL) {
4373 SDValue N0Op0 = N0.getOperand(0);
4374 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4375 uint64_t c1 = N0Op0C1->getZExtValue();
4376 if (c1 < VT.getScalarSizeInBits()) {
4377 uint64_t c2 = N1C->getZExtValue();
4379 SDValue NewOp0 = N0.getOperand(0);
4380 EVT CountVT = NewOp0.getOperand(1).getValueType();
4382 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4384 DAG.getConstant(c2, DL, CountVT));
4385 AddToWorklist(NewSHL.getNode());
4386 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4392 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
4393 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2
4394 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4395 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4396 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4397 uint64_t C1 = N0C1->getZExtValue();
4398 uint64_t C2 = N1C->getZExtValue();
4401 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4402 DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4403 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4404 DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4408 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4409 // (and (srl x, (sub c1, c2), MASK)
4410 // Only fold this if the inner shift has no other uses -- if it does, folding
4411 // this will increase the total number of instructions.
4412 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4413 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4414 uint64_t c1 = N0C1->getZExtValue();
4415 if (c1 < OpSizeInBits) {
4416 uint64_t c2 = N1C->getZExtValue();
4417 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4420 Mask = Mask.shl(c2 - c1);
4422 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4423 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4425 Mask = Mask.lshr(c1 - c2);
4427 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4428 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4431 return DAG.getNode(ISD::AND, DL, VT, Shift,
4432 DAG.getConstant(Mask, DL, VT));
4436 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4437 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4438 unsigned BitSize = VT.getScalarSizeInBits();
4440 SDValue HiBitsMask =
4441 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4442 BitSize - N1C->getZExtValue()),
4444 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4448 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4449 // Variant of version done on multiply, except mul by a power of 2 is turned
4452 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4453 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4454 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4455 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4456 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4457 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4460 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4461 if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4462 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4463 SDValue Folded = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C);
4464 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4468 if (N1C && !N1C->isOpaque())
4469 if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4475 SDValue DAGCombiner::visitSRA(SDNode *N) {
4476 SDValue N0 = N->getOperand(0);
4477 SDValue N1 = N->getOperand(1);
4478 EVT VT = N0.getValueType();
4479 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4482 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4483 if (VT.isVector()) {
4484 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4487 N1C = isConstOrConstSplat(N1);
4490 // fold (sra c1, c2) -> (sra c1, c2)
4491 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4492 if (N0C && N1C && !N1C->isOpaque())
4493 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4494 // fold (sra 0, x) -> 0
4495 if (isNullConstant(N0))
4497 // fold (sra -1, x) -> -1
4498 if (isAllOnesConstant(N0))
4500 // fold (sra x, (setge c, size(x))) -> undef
4501 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4502 return DAG.getUNDEF(VT);
4503 // fold (sra x, 0) -> x
4504 if (N1C && N1C->isNullValue())
4506 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4508 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4509 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4510 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4512 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4513 ExtVT, VT.getVectorNumElements());
4514 if ((!LegalOperations ||
4515 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4516 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4517 N0.getOperand(0), DAG.getValueType(ExtVT));
4520 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4521 if (N1C && N0.getOpcode() == ISD::SRA) {
4522 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4523 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4524 if (Sum >= OpSizeInBits)
4525 Sum = OpSizeInBits - 1;
4527 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4528 DAG.getConstant(Sum, DL, N1.getValueType()));
4532 // fold (sra (shl X, m), (sub result_size, n))
4533 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4534 // result_size - n != m.
4535 // If truncate is free for the target sext(shl) is likely to result in better
4537 if (N0.getOpcode() == ISD::SHL && N1C) {
4538 // Get the two constanst of the shifts, CN0 = m, CN = n.
4539 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4541 LLVMContext &Ctx = *DAG.getContext();
4542 // Determine what the truncate's result bitsize and type would be.
4543 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4546 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4548 // Determine the residual right-shift amount.
4549 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4551 // If the shift is not a no-op (in which case this should be just a sign
4552 // extend already), the truncated to type is legal, sign_extend is legal
4553 // on that type, and the truncate to that type is both legal and free,
4554 // perform the transform.
4555 if ((ShiftAmt > 0) &&
4556 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4557 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4558 TLI.isTruncateFree(VT, TruncVT)) {
4561 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4562 getShiftAmountTy(N0.getOperand(0).getValueType()));
4563 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4564 N0.getOperand(0), Amt);
4565 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4567 return DAG.getNode(ISD::SIGN_EXTEND, DL,
4568 N->getValueType(0), Trunc);
4573 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4574 if (N1.getOpcode() == ISD::TRUNCATE &&
4575 N1.getOperand(0).getOpcode() == ISD::AND) {
4576 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4577 if (NewOp1.getNode())
4578 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4581 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4582 // if c1 is equal to the number of bits the trunc removes
4583 if (N0.getOpcode() == ISD::TRUNCATE &&
4584 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4585 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4586 N0.getOperand(0).hasOneUse() &&
4587 N0.getOperand(0).getOperand(1).hasOneUse() &&
4589 SDValue N0Op0 = N0.getOperand(0);
4590 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4591 unsigned LargeShiftVal = LargeShift->getZExtValue();
4592 EVT LargeVT = N0Op0.getValueType();
4594 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4597 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4598 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4599 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4600 N0Op0.getOperand(0), Amt);
4601 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4606 // Simplify, based on bits shifted out of the LHS.
4607 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4608 return SDValue(N, 0);
4611 // If the sign bit is known to be zero, switch this to a SRL.
4612 if (DAG.SignBitIsZero(N0))
4613 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4615 if (N1C && !N1C->isOpaque())
4616 if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4622 SDValue DAGCombiner::visitSRL(SDNode *N) {
4623 SDValue N0 = N->getOperand(0);
4624 SDValue N1 = N->getOperand(1);
4625 EVT VT = N0.getValueType();
4626 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4629 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4630 if (VT.isVector()) {
4631 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4634 N1C = isConstOrConstSplat(N1);
4637 // fold (srl c1, c2) -> c1 >>u c2
4638 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4639 if (N0C && N1C && !N1C->isOpaque())
4640 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4641 // fold (srl 0, x) -> 0
4642 if (isNullConstant(N0))
4644 // fold (srl x, c >= size(x)) -> undef
4645 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4646 return DAG.getUNDEF(VT);
4647 // fold (srl x, 0) -> x
4648 if (N1C && N1C->isNullValue())
4650 // if (srl x, c) is known to be zero, return 0
4651 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4652 APInt::getAllOnesValue(OpSizeInBits)))
4653 return DAG.getConstant(0, SDLoc(N), VT);
4655 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4656 if (N1C && N0.getOpcode() == ISD::SRL) {
4657 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4658 uint64_t c1 = N01C->getZExtValue();
4659 uint64_t c2 = N1C->getZExtValue();
4661 if (c1 + c2 >= OpSizeInBits)
4662 return DAG.getConstant(0, DL, VT);
4663 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4664 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4668 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4669 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4670 N0.getOperand(0).getOpcode() == ISD::SRL &&
4671 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4673 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4674 uint64_t c2 = N1C->getZExtValue();
4675 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4676 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4677 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4678 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4679 if (c1 + OpSizeInBits == InnerShiftSize) {
4681 if (c1 + c2 >= InnerShiftSize)
4682 return DAG.getConstant(0, DL, VT);
4683 return DAG.getNode(ISD::TRUNCATE, DL, VT,
4684 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4685 N0.getOperand(0)->getOperand(0),
4686 DAG.getConstant(c1 + c2, DL,
4691 // fold (srl (shl x, c), c) -> (and x, cst2)
4692 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4693 unsigned BitSize = N0.getScalarValueSizeInBits();
4694 if (BitSize <= 64) {
4695 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4697 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4698 DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4702 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4703 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4704 // Shifting in all undef bits?
4705 EVT SmallVT = N0.getOperand(0).getValueType();
4706 unsigned BitSize = SmallVT.getScalarSizeInBits();
4707 if (N1C->getZExtValue() >= BitSize)
4708 return DAG.getUNDEF(VT);
4710 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4711 uint64_t ShiftAmt = N1C->getZExtValue();
4713 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4715 DAG.getConstant(ShiftAmt, DL0,
4716 getShiftAmountTy(SmallVT)));
4717 AddToWorklist(SmallShift.getNode());
4718 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4720 return DAG.getNode(ISD::AND, DL, VT,
4721 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4722 DAG.getConstant(Mask, DL, VT));
4726 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4727 // bit, which is unmodified by sra.
4728 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4729 if (N0.getOpcode() == ISD::SRA)
4730 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4733 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4734 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4735 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4736 APInt KnownZero, KnownOne;
4737 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4739 // If any of the input bits are KnownOne, then the input couldn't be all
4740 // zeros, thus the result of the srl will always be zero.
4741 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4743 // If all of the bits input the to ctlz node are known to be zero, then
4744 // the result of the ctlz is "32" and the result of the shift is one.
4745 APInt UnknownBits = ~KnownZero;
4746 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4748 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4749 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4750 // Okay, we know that only that the single bit specified by UnknownBits
4751 // could be set on input to the CTLZ node. If this bit is set, the SRL
4752 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4753 // to an SRL/XOR pair, which is likely to simplify more.
4754 unsigned ShAmt = UnknownBits.countTrailingZeros();
4755 SDValue Op = N0.getOperand(0);
4759 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4760 DAG.getConstant(ShAmt, DL,
4761 getShiftAmountTy(Op.getValueType())));
4762 AddToWorklist(Op.getNode());
4766 return DAG.getNode(ISD::XOR, DL, VT,
4767 Op, DAG.getConstant(1, DL, VT));
4771 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4772 if (N1.getOpcode() == ISD::TRUNCATE &&
4773 N1.getOperand(0).getOpcode() == ISD::AND) {
4774 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4775 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4778 // fold operands of srl based on knowledge that the low bits are not
4780 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4781 return SDValue(N, 0);
4783 if (N1C && !N1C->isOpaque())
4784 if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4787 // Attempt to convert a srl of a load into a narrower zero-extending load.
4788 if (SDValue NarrowLoad = ReduceLoadWidth(N))
4791 // Here is a common situation. We want to optimize:
4794 // %b = and i32 %a, 2
4795 // %c = srl i32 %b, 1
4796 // brcond i32 %c ...
4802 // %c = setcc eq %b, 0
4805 // However when after the source operand of SRL is optimized into AND, the SRL
4806 // itself may not be optimized further. Look for it and add the BRCOND into
4808 if (N->hasOneUse()) {
4809 SDNode *Use = *N->use_begin();
4810 if (Use->getOpcode() == ISD::BRCOND)
4812 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4813 // Also look pass the truncate.
4814 Use = *Use->use_begin();
4815 if (Use->getOpcode() == ISD::BRCOND)
4823 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4824 SDValue N0 = N->getOperand(0);
4825 EVT VT = N->getValueType(0);
4827 // fold (bswap c1) -> c2
4828 if (isConstantIntBuildVectorOrConstantInt(N0))
4829 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4830 // fold (bswap (bswap x)) -> x
4831 if (N0.getOpcode() == ISD::BSWAP)
4832 return N0->getOperand(0);
4836 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4837 SDValue N0 = N->getOperand(0);
4838 EVT VT = N->getValueType(0);
4840 // fold (ctlz c1) -> c2
4841 if (isConstantIntBuildVectorOrConstantInt(N0))
4842 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4846 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4847 SDValue N0 = N->getOperand(0);
4848 EVT VT = N->getValueType(0);
4850 // fold (ctlz_zero_undef c1) -> c2
4851 if (isConstantIntBuildVectorOrConstantInt(N0))
4852 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4856 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4857 SDValue N0 = N->getOperand(0);
4858 EVT VT = N->getValueType(0);
4860 // fold (cttz c1) -> c2
4861 if (isConstantIntBuildVectorOrConstantInt(N0))
4862 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4866 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4867 SDValue N0 = N->getOperand(0);
4868 EVT VT = N->getValueType(0);
4870 // fold (cttz_zero_undef c1) -> c2
4871 if (isConstantIntBuildVectorOrConstantInt(N0))
4872 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4876 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4877 SDValue N0 = N->getOperand(0);
4878 EVT VT = N->getValueType(0);
4880 // fold (ctpop c1) -> c2
4881 if (isConstantIntBuildVectorOrConstantInt(N0))
4882 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4887 /// \brief Generate Min/Max node
4888 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4889 SDValue True, SDValue False,
4890 ISD::CondCode CC, const TargetLowering &TLI,
4891 SelectionDAG &DAG) {
4892 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4902 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4903 if (TLI.isOperationLegal(Opcode, VT))
4904 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4913 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4914 if (TLI.isOperationLegal(Opcode, VT))
4915 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4923 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4924 SDValue N0 = N->getOperand(0);
4925 SDValue N1 = N->getOperand(1);
4926 SDValue N2 = N->getOperand(2);
4927 EVT VT = N->getValueType(0);
4928 EVT VT0 = N0.getValueType();
4930 // fold (select C, X, X) -> X
4933 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4934 // fold (select true, X, Y) -> X
4935 // fold (select false, X, Y) -> Y
4936 return !N0C->isNullValue() ? N1 : N2;
4938 // fold (select C, 1, X) -> (or C, X)
4939 if (VT == MVT::i1 && isOneConstant(N1))
4940 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4941 // fold (select C, 0, 1) -> (xor C, 1)
4942 // We can't do this reliably if integer based booleans have different contents
4943 // to floating point based booleans. This is because we can't tell whether we
4944 // have an integer-based boolean or a floating-point-based boolean unless we
4945 // can find the SETCC that produced it and inspect its operands. This is
4946 // fairly easy if C is the SETCC node, but it can potentially be
4947 // undiscoverable (or not reasonably discoverable). For example, it could be
4948 // in another basic block or it could require searching a complicated
4950 if (VT.isInteger() &&
4951 (VT0 == MVT::i1 || (VT0.isInteger() &&
4952 TLI.getBooleanContents(false, false) ==
4953 TLI.getBooleanContents(false, true) &&
4954 TLI.getBooleanContents(false, false) ==
4955 TargetLowering::ZeroOrOneBooleanContent)) &&
4956 isNullConstant(N1) && isOneConstant(N2)) {
4960 return DAG.getNode(ISD::XOR, DL, VT0,
4961 N0, DAG.getConstant(1, DL, VT0));
4964 XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4965 N0, DAG.getConstant(1, DL0, VT0));
4966 AddToWorklist(XORNode.getNode());
4968 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4969 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4971 // fold (select C, 0, X) -> (and (not C), X)
4972 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4973 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4974 AddToWorklist(NOTNode.getNode());
4975 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4977 // fold (select C, X, 1) -> (or (not C), X)
4978 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
4979 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4980 AddToWorklist(NOTNode.getNode());
4981 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4983 // fold (select C, X, 0) -> (and C, X)
4984 if (VT == MVT::i1 && isNullConstant(N2))
4985 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4986 // fold (select X, X, Y) -> (or X, Y)
4987 // fold (select X, 1, Y) -> (or X, Y)
4988 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
4989 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4990 // fold (select X, Y, X) -> (and X, Y)
4991 // fold (select X, Y, 0) -> (and X, Y)
4992 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
4993 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4995 // If we can fold this based on the true/false value, do so.
4996 if (SimplifySelectOps(N, N1, N2))
4997 return SDValue(N, 0); // Don't revisit N.
4999 if (VT0 == MVT::i1) {
5000 // The code in this block deals with the following 2 equivalences:
5001 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5002 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5003 // The target can specify its prefered form with the
5004 // shouldNormalizeToSelectSequence() callback. However we always transform
5005 // to the right anyway if we find the inner select exists in the DAG anyway
5006 // and we always transform to the left side if we know that we can further
5007 // optimize the combination of the conditions.
5008 bool normalizeToSequence
5009 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5010 // select (and Cond0, Cond1), X, Y
5011 // -> select Cond0, (select Cond1, X, Y), Y
5012 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5013 SDValue Cond0 = N0->getOperand(0);
5014 SDValue Cond1 = N0->getOperand(1);
5015 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5016 N1.getValueType(), Cond1, N1, N2);
5017 if (normalizeToSequence || !InnerSelect.use_empty())
5018 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5021 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5022 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5023 SDValue Cond0 = N0->getOperand(0);
5024 SDValue Cond1 = N0->getOperand(1);
5025 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5026 N1.getValueType(), Cond1, N1, N2);
5027 if (normalizeToSequence || !InnerSelect.use_empty())
5028 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5032 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5033 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5034 SDValue N1_0 = N1->getOperand(0);
5035 SDValue N1_1 = N1->getOperand(1);
5036 SDValue N1_2 = N1->getOperand(2);
5037 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5038 // Create the actual and node if we can generate good code for it.
5039 if (!normalizeToSequence) {
5040 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5042 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5045 // Otherwise see if we can optimize the "and" to a better pattern.
5046 if (SDValue Combined = visitANDLike(N0, N1_0, N))
5047 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5051 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5052 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5053 SDValue N2_0 = N2->getOperand(0);
5054 SDValue N2_1 = N2->getOperand(1);
5055 SDValue N2_2 = N2->getOperand(2);
5056 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5057 // Create the actual or node if we can generate good code for it.
5058 if (!normalizeToSequence) {
5059 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5061 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5064 // Otherwise see if we can optimize to a better pattern.
5065 if (SDValue Combined = visitORLike(N0, N2_0, N))
5066 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5072 // fold selects based on a setcc into other things, such as min/max/abs
5073 if (N0.getOpcode() == ISD::SETCC) {
5074 // select x, y (fcmp lt x, y) -> fminnum x, y
5075 // select x, y (fcmp gt x, y) -> fmaxnum x, y
5077 // This is OK if we don't care about what happens if either operand is a
5081 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5082 // no signed zeros as well as no nans.
5083 const TargetOptions &Options = DAG.getTarget().Options;
5084 if (Options.UnsafeFPMath &&
5085 VT.isFloatingPoint() && N0.hasOneUse() &&
5086 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5087 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5089 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5090 N0.getOperand(1), N1, N2, CC,
5095 if ((!LegalOperations &&
5096 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5097 TLI.isOperationLegal(ISD::SELECT_CC, VT))
5098 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5099 N0.getOperand(0), N0.getOperand(1),
5100 N1, N2, N0.getOperand(2));
5101 return SimplifySelect(SDLoc(N), N0, N1, N2);
5108 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5111 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5113 // Split the inputs.
5114 SDValue Lo, Hi, LL, LH, RL, RH;
5115 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5116 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5118 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5119 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5121 return std::make_pair(Lo, Hi);
5124 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5125 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5126 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5128 SDValue Cond = N->getOperand(0);
5129 SDValue LHS = N->getOperand(1);
5130 SDValue RHS = N->getOperand(2);
5131 EVT VT = N->getValueType(0);
5132 int NumElems = VT.getVectorNumElements();
5133 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5134 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5135 Cond.getOpcode() == ISD::BUILD_VECTOR);
5137 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5138 // binary ones here.
5139 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5142 // We're sure we have an even number of elements due to the
5143 // concat_vectors we have as arguments to vselect.
5144 // Skip BV elements until we find one that's not an UNDEF
5145 // After we find an UNDEF element, keep looping until we get to half the
5146 // length of the BV and see if all the non-undef nodes are the same.
5147 ConstantSDNode *BottomHalf = nullptr;
5148 for (int i = 0; i < NumElems / 2; ++i) {
5149 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5152 if (BottomHalf == nullptr)
5153 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5154 else if (Cond->getOperand(i).getNode() != BottomHalf)
5158 // Do the same for the second half of the BuildVector
5159 ConstantSDNode *TopHalf = nullptr;
5160 for (int i = NumElems / 2; i < NumElems; ++i) {
5161 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5164 if (TopHalf == nullptr)
5165 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5166 else if (Cond->getOperand(i).getNode() != TopHalf)
5170 assert(TopHalf && BottomHalf &&
5171 "One half of the selector was all UNDEFs and the other was all the "
5172 "same value. This should have been addressed before this function.");
5174 ISD::CONCAT_VECTORS, dl, VT,
5175 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5176 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5179 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5181 if (Level >= AfterLegalizeTypes)
5184 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5185 SDValue Mask = MSC->getMask();
5186 SDValue Data = MSC->getValue();
5189 // If the MSCATTER data type requires splitting and the mask is provided by a
5190 // SETCC, then split both nodes and its operands before legalization. This
5191 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5192 // and enables future optimizations (e.g. min/max pattern matching on X86).
5193 if (Mask.getOpcode() != ISD::SETCC)
5196 // Check if any splitting is required.
5197 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5198 TargetLowering::TypeSplitVector)
5200 SDValue MaskLo, MaskHi, Lo, Hi;
5201 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5204 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5206 SDValue Chain = MSC->getChain();
5208 EVT MemoryVT = MSC->getMemoryVT();
5209 unsigned Alignment = MSC->getOriginalAlignment();
5211 EVT LoMemVT, HiMemVT;
5212 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5214 SDValue DataLo, DataHi;
5215 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5217 SDValue BasePtr = MSC->getBasePtr();
5218 SDValue IndexLo, IndexHi;
5219 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5221 MachineMemOperand *MMO = DAG.getMachineFunction().
5222 getMachineMemOperand(MSC->getPointerInfo(),
5223 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5224 Alignment, MSC->getAAInfo(), MSC->getRanges());
5226 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5227 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5230 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5231 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5234 AddToWorklist(Lo.getNode());
5235 AddToWorklist(Hi.getNode());
5237 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5240 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5242 if (Level >= AfterLegalizeTypes)
5245 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5246 SDValue Mask = MST->getMask();
5247 SDValue Data = MST->getValue();
5250 // If the MSTORE data type requires splitting and the mask is provided by a
5251 // SETCC, then split both nodes and its operands before legalization. This
5252 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5253 // and enables future optimizations (e.g. min/max pattern matching on X86).
5254 if (Mask.getOpcode() == ISD::SETCC) {
5256 // Check if any splitting is required.
5257 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5258 TargetLowering::TypeSplitVector)
5261 SDValue MaskLo, MaskHi, Lo, Hi;
5262 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5265 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5267 SDValue Chain = MST->getChain();
5268 SDValue Ptr = MST->getBasePtr();
5270 EVT MemoryVT = MST->getMemoryVT();
5271 unsigned Alignment = MST->getOriginalAlignment();
5273 // if Alignment is equal to the vector size,
5274 // take the half of it for the second part
5275 unsigned SecondHalfAlignment =
5276 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5277 Alignment/2 : Alignment;
5279 EVT LoMemVT, HiMemVT;
5280 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5282 SDValue DataLo, DataHi;
5283 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5285 MachineMemOperand *MMO = DAG.getMachineFunction().
5286 getMachineMemOperand(MST->getPointerInfo(),
5287 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5288 Alignment, MST->getAAInfo(), MST->getRanges());
5290 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5291 MST->isTruncatingStore());
5293 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5294 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5295 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5297 MMO = DAG.getMachineFunction().
5298 getMachineMemOperand(MST->getPointerInfo(),
5299 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5300 SecondHalfAlignment, MST->getAAInfo(),
5303 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5304 MST->isTruncatingStore());
5306 AddToWorklist(Lo.getNode());
5307 AddToWorklist(Hi.getNode());
5309 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5314 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5316 if (Level >= AfterLegalizeTypes)
5319 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5320 SDValue Mask = MGT->getMask();
5323 // If the MGATHER result requires splitting and the mask is provided by a
5324 // SETCC, then split both nodes and its operands before legalization. This
5325 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5326 // and enables future optimizations (e.g. min/max pattern matching on X86).
5328 if (Mask.getOpcode() != ISD::SETCC)
5331 EVT VT = N->getValueType(0);
5333 // Check if any splitting is required.
5334 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5335 TargetLowering::TypeSplitVector)
5338 SDValue MaskLo, MaskHi, Lo, Hi;
5339 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5341 SDValue Src0 = MGT->getValue();
5342 SDValue Src0Lo, Src0Hi;
5343 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5346 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5348 SDValue Chain = MGT->getChain();
5349 EVT MemoryVT = MGT->getMemoryVT();
5350 unsigned Alignment = MGT->getOriginalAlignment();
5352 EVT LoMemVT, HiMemVT;
5353 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5355 SDValue BasePtr = MGT->getBasePtr();
5356 SDValue Index = MGT->getIndex();
5357 SDValue IndexLo, IndexHi;
5358 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5360 MachineMemOperand *MMO = DAG.getMachineFunction().
5361 getMachineMemOperand(MGT->getPointerInfo(),
5362 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5363 Alignment, MGT->getAAInfo(), MGT->getRanges());
5365 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5366 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5369 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5370 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5373 AddToWorklist(Lo.getNode());
5374 AddToWorklist(Hi.getNode());
5376 // Build a factor node to remember that this load is independent of the
5378 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5381 // Legalized the chain result - switch anything that used the old chain to
5383 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5385 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5387 SDValue RetOps[] = { GatherRes, Chain };
5388 return DAG.getMergeValues(RetOps, DL);
5391 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5393 if (Level >= AfterLegalizeTypes)
5396 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5397 SDValue Mask = MLD->getMask();
5400 // If the MLOAD result requires splitting and the mask is provided by a
5401 // SETCC, then split both nodes and its operands before legalization. This
5402 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5403 // and enables future optimizations (e.g. min/max pattern matching on X86).
5405 if (Mask.getOpcode() == ISD::SETCC) {
5406 EVT VT = N->getValueType(0);
5408 // Check if any splitting is required.
5409 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5410 TargetLowering::TypeSplitVector)
5413 SDValue MaskLo, MaskHi, Lo, Hi;
5414 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5416 SDValue Src0 = MLD->getSrc0();
5417 SDValue Src0Lo, Src0Hi;
5418 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5421 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5423 SDValue Chain = MLD->getChain();
5424 SDValue Ptr = MLD->getBasePtr();
5425 EVT MemoryVT = MLD->getMemoryVT();
5426 unsigned Alignment = MLD->getOriginalAlignment();
5428 // if Alignment is equal to the vector size,
5429 // take the half of it for the second part
5430 unsigned SecondHalfAlignment =
5431 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5432 Alignment/2 : Alignment;
5434 EVT LoMemVT, HiMemVT;
5435 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5437 MachineMemOperand *MMO = DAG.getMachineFunction().
5438 getMachineMemOperand(MLD->getPointerInfo(),
5439 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5440 Alignment, MLD->getAAInfo(), MLD->getRanges());
5442 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5445 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5446 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5447 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5449 MMO = DAG.getMachineFunction().
5450 getMachineMemOperand(MLD->getPointerInfo(),
5451 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5452 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5454 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5457 AddToWorklist(Lo.getNode());
5458 AddToWorklist(Hi.getNode());
5460 // Build a factor node to remember that this load is independent of the
5462 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5465 // Legalized the chain result - switch anything that used the old chain to
5467 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5469 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5471 SDValue RetOps[] = { LoadRes, Chain };
5472 return DAG.getMergeValues(RetOps, DL);
5477 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5478 SDValue N0 = N->getOperand(0);
5479 SDValue N1 = N->getOperand(1);
5480 SDValue N2 = N->getOperand(2);
5483 // Canonicalize integer abs.
5484 // vselect (setg[te] X, 0), X, -X ->
5485 // vselect (setgt X, -1), X, -X ->
5486 // vselect (setl[te] X, 0), -X, X ->
5487 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5488 if (N0.getOpcode() == ISD::SETCC) {
5489 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5490 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5492 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5494 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5495 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5496 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5497 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5498 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5499 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5500 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5503 EVT VT = LHS.getValueType();
5504 SDValue Shift = DAG.getNode(
5505 ISD::SRA, DL, VT, LHS,
5506 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5507 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5508 AddToWorklist(Shift.getNode());
5509 AddToWorklist(Add.getNode());
5510 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5514 if (SimplifySelectOps(N, N1, N2))
5515 return SDValue(N, 0); // Don't revisit N.
5517 // If the VSELECT result requires splitting and the mask is provided by a
5518 // SETCC, then split both nodes and its operands before legalization. This
5519 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5520 // and enables future optimizations (e.g. min/max pattern matching on X86).
5521 if (N0.getOpcode() == ISD::SETCC) {
5522 EVT VT = N->getValueType(0);
5524 // Check if any splitting is required.
5525 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5526 TargetLowering::TypeSplitVector)
5529 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5530 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5531 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5532 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5534 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5535 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5537 // Add the new VSELECT nodes to the work list in case they need to be split
5539 AddToWorklist(Lo.getNode());
5540 AddToWorklist(Hi.getNode());
5542 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5545 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5546 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5548 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5549 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5552 // The ConvertSelectToConcatVector function is assuming both the above
5553 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5555 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5556 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5557 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5558 if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5565 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5566 SDValue N0 = N->getOperand(0);
5567 SDValue N1 = N->getOperand(1);
5568 SDValue N2 = N->getOperand(2);
5569 SDValue N3 = N->getOperand(3);
5570 SDValue N4 = N->getOperand(4);
5571 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5573 // fold select_cc lhs, rhs, x, x, cc -> x
5577 // Determine if the condition we're dealing with is constant
5578 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5579 N0, N1, CC, SDLoc(N), false);
5580 if (SCC.getNode()) {
5581 AddToWorklist(SCC.getNode());
5583 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5584 if (!SCCC->isNullValue())
5585 return N2; // cond always true -> true val
5587 return N3; // cond always false -> false val
5588 } else if (SCC->getOpcode() == ISD::UNDEF) {
5589 // When the condition is UNDEF, just return the first operand. This is
5590 // coherent the DAG creation, no setcc node is created in this case
5592 } else if (SCC.getOpcode() == ISD::SETCC) {
5593 // Fold to a simpler select_cc
5594 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5595 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5600 // If we can fold this based on the true/false value, do so.
5601 if (SimplifySelectOps(N, N2, N3))
5602 return SDValue(N, 0); // Don't revisit N.
5604 // fold select_cc into other things, such as min/max/abs
5605 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5608 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5609 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5610 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5614 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5615 /// a build_vector of constants.
5616 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5617 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5618 /// Vector extends are not folded if operations are legal; this is to
5619 /// avoid introducing illegal build_vector dag nodes.
5620 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5621 SelectionDAG &DAG, bool LegalTypes,
5622 bool LegalOperations) {
5623 unsigned Opcode = N->getOpcode();
5624 SDValue N0 = N->getOperand(0);
5625 EVT VT = N->getValueType(0);
5627 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5628 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5629 && "Expected EXTEND dag node in input!");
5631 // fold (sext c1) -> c1
5632 // fold (zext c1) -> c1
5633 // fold (aext c1) -> c1
5634 if (isa<ConstantSDNode>(N0))
5635 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5637 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5638 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5639 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5640 EVT SVT = VT.getScalarType();
5641 if (!(VT.isVector() &&
5642 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5643 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5646 // We can fold this node into a build_vector.
5647 unsigned VTBits = SVT.getSizeInBits();
5648 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5649 SmallVector<SDValue, 8> Elts;
5650 unsigned NumElts = VT.getVectorNumElements();
5653 for (unsigned i=0; i != NumElts; ++i) {
5654 SDValue Op = N0->getOperand(i);
5655 if (Op->getOpcode() == ISD::UNDEF) {
5656 Elts.push_back(DAG.getUNDEF(SVT));
5661 // Get the constant value and if needed trunc it to the size of the type.
5662 // Nodes like build_vector might have constants wider than the scalar type.
5663 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5664 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5665 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5667 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5670 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5673 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5674 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5675 // transformation. Returns true if extension are possible and the above
5676 // mentioned transformation is profitable.
5677 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5679 SmallVectorImpl<SDNode *> &ExtendNodes,
5680 const TargetLowering &TLI) {
5681 bool HasCopyToRegUses = false;
5682 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5683 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5684 UE = N0.getNode()->use_end();
5689 if (UI.getUse().getResNo() != N0.getResNo())
5691 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5692 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5693 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5694 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5695 // Sign bits will be lost after a zext.
5698 for (unsigned i = 0; i != 2; ++i) {
5699 SDValue UseOp = User->getOperand(i);
5702 if (!isa<ConstantSDNode>(UseOp))
5707 ExtendNodes.push_back(User);
5710 // If truncates aren't free and there are users we can't
5711 // extend, it isn't worthwhile.
5714 // Remember if this value is live-out.
5715 if (User->getOpcode() == ISD::CopyToReg)
5716 HasCopyToRegUses = true;
5719 if (HasCopyToRegUses) {
5720 bool BothLiveOut = false;
5721 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5723 SDUse &Use = UI.getUse();
5724 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5730 // Both unextended and extended values are live out. There had better be
5731 // a good reason for the transformation.
5732 return ExtendNodes.size();
5737 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5738 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5739 ISD::NodeType ExtType) {
5740 // Extend SetCC uses if necessary.
5741 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5742 SDNode *SetCC = SetCCs[i];
5743 SmallVector<SDValue, 4> Ops;
5745 for (unsigned j = 0; j != 2; ++j) {
5746 SDValue SOp = SetCC->getOperand(j);
5748 Ops.push_back(ExtLoad);
5750 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5753 Ops.push_back(SetCC->getOperand(2));
5754 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5758 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5759 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5760 SDValue N0 = N->getOperand(0);
5761 EVT DstVT = N->getValueType(0);
5762 EVT SrcVT = N0.getValueType();
5764 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5765 N->getOpcode() == ISD::ZERO_EXTEND) &&
5766 "Unexpected node type (not an extend)!");
5768 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5769 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5770 // (v8i32 (sext (v8i16 (load x))))
5772 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5773 // (v4i32 (sextload (x + 16)))))
5774 // Where uses of the original load, i.e.:
5776 // are replaced with:
5778 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5779 // (v4i32 (sextload (x + 16)))))))
5781 // This combine is only applicable to illegal, but splittable, vectors.
5782 // All legal types, and illegal non-vector types, are handled elsewhere.
5783 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5785 if (N0->getOpcode() != ISD::LOAD)
5788 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5790 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5791 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5792 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5795 SmallVector<SDNode *, 4> SetCCs;
5796 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5799 ISD::LoadExtType ExtType =
5800 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5802 // Try to split the vector types to get down to legal types.
5803 EVT SplitSrcVT = SrcVT;
5804 EVT SplitDstVT = DstVT;
5805 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5806 SplitSrcVT.getVectorNumElements() > 1) {
5807 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5808 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5811 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5815 const unsigned NumSplits =
5816 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5817 const unsigned Stride = SplitSrcVT.getStoreSize();
5818 SmallVector<SDValue, 4> Loads;
5819 SmallVector<SDValue, 4> Chains;
5821 SDValue BasePtr = LN0->getBasePtr();
5822 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5823 const unsigned Offset = Idx * Stride;
5824 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5826 SDValue SplitLoad = DAG.getExtLoad(
5827 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5828 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5829 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5830 Align, LN0->getAAInfo());
5832 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5833 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5835 Loads.push_back(SplitLoad.getValue(0));
5836 Chains.push_back(SplitLoad.getValue(1));
5839 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5840 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5842 CombineTo(N, NewValue);
5844 // Replace uses of the original load (before extension)
5845 // with a truncate of the concatenated sextloaded vectors.
5847 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5848 CombineTo(N0.getNode(), Trunc, NewChain);
5849 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5850 (ISD::NodeType)N->getOpcode());
5851 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5854 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5855 SDValue N0 = N->getOperand(0);
5856 EVT VT = N->getValueType(0);
5858 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5860 return SDValue(Res, 0);
5862 // fold (sext (sext x)) -> (sext x)
5863 // fold (sext (aext x)) -> (sext x)
5864 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5865 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5868 if (N0.getOpcode() == ISD::TRUNCATE) {
5869 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5870 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5871 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
5872 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5873 if (NarrowLoad.getNode() != N0.getNode()) {
5874 CombineTo(N0.getNode(), NarrowLoad);
5875 // CombineTo deleted the truncate, if needed, but not what's under it.
5878 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5881 // See if the value being truncated is already sign extended. If so, just
5882 // eliminate the trunc/sext pair.
5883 SDValue Op = N0.getOperand(0);
5884 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5885 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5886 unsigned DestBits = VT.getScalarType().getSizeInBits();
5887 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5889 if (OpBits == DestBits) {
5890 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5891 // bits, it is already ready.
5892 if (NumSignBits > DestBits-MidBits)
5894 } else if (OpBits < DestBits) {
5895 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5896 // bits, just sext from i32.
5897 if (NumSignBits > OpBits-MidBits)
5898 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5900 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5901 // bits, just truncate to i32.
5902 if (NumSignBits > OpBits-MidBits)
5903 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5906 // fold (sext (truncate x)) -> (sextinreg x).
5907 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5908 N0.getValueType())) {
5909 if (OpBits < DestBits)
5910 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5911 else if (OpBits > DestBits)
5912 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5913 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5914 DAG.getValueType(N0.getValueType()));
5918 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5919 // Only generate vector extloads when 1) they're legal, and 2) they are
5920 // deemed desirable by the target.
5921 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5922 ((!LegalOperations && !VT.isVector() &&
5923 !cast<LoadSDNode>(N0)->isVolatile()) ||
5924 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5925 bool DoXform = true;
5926 SmallVector<SDNode*, 4> SetCCs;
5927 if (!N0.hasOneUse())
5928 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5930 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5932 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5933 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5935 LN0->getBasePtr(), N0.getValueType(),
5936 LN0->getMemOperand());
5937 CombineTo(N, ExtLoad);
5938 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5939 N0.getValueType(), ExtLoad);
5940 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5941 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5943 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5947 // fold (sext (load x)) to multiple smaller sextloads.
5948 // Only on illegal but splittable vectors.
5949 if (SDValue ExtLoad = CombineExtLoad(N))
5952 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5953 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5954 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5955 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5956 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5957 EVT MemVT = LN0->getMemoryVT();
5958 if ((!LegalOperations && !LN0->isVolatile()) ||
5959 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5960 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5962 LN0->getBasePtr(), MemVT,
5963 LN0->getMemOperand());
5964 CombineTo(N, ExtLoad);
5965 CombineTo(N0.getNode(),
5966 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5967 N0.getValueType(), ExtLoad),
5968 ExtLoad.getValue(1));
5969 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5973 // fold (sext (and/or/xor (load x), cst)) ->
5974 // (and/or/xor (sextload x), (sext cst))
5975 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5976 N0.getOpcode() == ISD::XOR) &&
5977 isa<LoadSDNode>(N0.getOperand(0)) &&
5978 N0.getOperand(1).getOpcode() == ISD::Constant &&
5979 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5980 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5981 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5982 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5983 bool DoXform = true;
5984 SmallVector<SDNode*, 4> SetCCs;
5985 if (!N0.hasOneUse())
5986 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5989 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5990 LN0->getChain(), LN0->getBasePtr(),
5992 LN0->getMemOperand());
5993 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5994 Mask = Mask.sext(VT.getSizeInBits());
5996 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5997 ExtLoad, DAG.getConstant(Mask, DL, VT));
5998 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5999 SDLoc(N0.getOperand(0)),
6000 N0.getOperand(0).getValueType(), ExtLoad);
6002 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6003 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6005 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6010 if (N0.getOpcode() == ISD::SETCC) {
6011 EVT N0VT = N0.getOperand(0).getValueType();
6012 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6013 // Only do this before legalize for now.
6014 if (VT.isVector() && !LegalOperations &&
6015 TLI.getBooleanContents(N0VT) ==
6016 TargetLowering::ZeroOrNegativeOneBooleanContent) {
6017 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6018 // of the same size as the compared operands. Only optimize sext(setcc())
6019 // if this is the case.
6020 EVT SVT = getSetCCResultType(N0VT);
6022 // We know that the # elements of the results is the same as the
6023 // # elements of the compare (and the # elements of the compare result
6024 // for that matter). Check to see that they are the same size. If so,
6025 // we know that the element size of the sext'd result matches the
6026 // element size of the compare operands.
6027 if (VT.getSizeInBits() == SVT.getSizeInBits())
6028 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6030 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6032 // If the desired elements are smaller or larger than the source
6033 // elements we can use a matching integer vector type and then
6034 // truncate/sign extend
6035 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6036 if (SVT == MatchingVectorType) {
6037 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6038 N0.getOperand(0), N0.getOperand(1),
6039 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6040 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6044 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6045 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6048 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6050 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6051 NegOne, DAG.getConstant(0, DL, VT),
6052 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6053 if (SCC.getNode()) return SCC;
6055 if (!VT.isVector()) {
6056 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6057 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
6059 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6060 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6061 N0.getOperand(0), N0.getOperand(1), CC);
6062 return DAG.getSelect(DL, VT, SetCC,
6063 NegOne, DAG.getConstant(0, DL, VT));
6068 // fold (sext x) -> (zext x) if the sign bit is known zero.
6069 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6070 DAG.SignBitIsZero(N0))
6071 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6076 // isTruncateOf - If N is a truncate of some other value, return true, record
6077 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6078 // This function computes KnownZero to avoid a duplicated call to
6079 // computeKnownBits in the caller.
6080 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6083 if (N->getOpcode() == ISD::TRUNCATE) {
6084 Op = N->getOperand(0);
6085 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6089 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6090 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6093 SDValue Op0 = N->getOperand(0);
6094 SDValue Op1 = N->getOperand(1);
6095 assert(Op0.getValueType() == Op1.getValueType());
6097 if (isNullConstant(Op0))
6099 else if (isNullConstant(Op1))
6104 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6106 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6112 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6113 SDValue N0 = N->getOperand(0);
6114 EVT VT = N->getValueType(0);
6116 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6118 return SDValue(Res, 0);
6120 // fold (zext (zext x)) -> (zext x)
6121 // fold (zext (aext x)) -> (zext x)
6122 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6123 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6126 // fold (zext (truncate x)) -> (zext x) or
6127 // (zext (truncate x)) -> (truncate x)
6128 // This is valid when the truncated bits of x are already zero.
6129 // FIXME: We should extend this to work for vectors too.
6132 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6133 APInt TruncatedBits =
6134 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6135 APInt(Op.getValueSizeInBits(), 0) :
6136 APInt::getBitsSet(Op.getValueSizeInBits(),
6137 N0.getValueSizeInBits(),
6138 std::min(Op.getValueSizeInBits(),
6139 VT.getSizeInBits()));
6140 if (TruncatedBits == (KnownZero & TruncatedBits)) {
6141 if (VT.bitsGT(Op.getValueType()))
6142 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6143 if (VT.bitsLT(Op.getValueType()))
6144 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6150 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6151 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6152 if (N0.getOpcode() == ISD::TRUNCATE) {
6153 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6154 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6155 if (NarrowLoad.getNode() != N0.getNode()) {
6156 CombineTo(N0.getNode(), NarrowLoad);
6157 // CombineTo deleted the truncate, if needed, but not what's under it.
6160 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6164 // fold (zext (truncate x)) -> (and x, mask)
6165 if (N0.getOpcode() == ISD::TRUNCATE) {
6166 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6167 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6168 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6169 SDNode *oye = N0.getNode()->getOperand(0).getNode();
6170 if (NarrowLoad.getNode() != N0.getNode()) {
6171 CombineTo(N0.getNode(), NarrowLoad);
6172 // CombineTo deleted the truncate, if needed, but not what's under it.
6175 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6178 EVT SrcVT = N0.getOperand(0).getValueType();
6179 EVT MinVT = N0.getValueType();
6181 // Try to mask before the extension to avoid having to generate a larger mask,
6182 // possibly over several sub-vectors.
6183 if (SrcVT.bitsLT(VT)) {
6184 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6185 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6186 SDValue Op = N0.getOperand(0);
6187 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6188 AddToWorklist(Op.getNode());
6189 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6193 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6194 SDValue Op = N0.getOperand(0);
6195 if (SrcVT.bitsLT(VT)) {
6196 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6197 AddToWorklist(Op.getNode());
6198 } else if (SrcVT.bitsGT(VT)) {
6199 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6200 AddToWorklist(Op.getNode());
6202 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6206 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6207 // if either of the casts is not free.
6208 if (N0.getOpcode() == ISD::AND &&
6209 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6210 N0.getOperand(1).getOpcode() == ISD::Constant &&
6211 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6212 N0.getValueType()) ||
6213 !TLI.isZExtFree(N0.getValueType(), VT))) {
6214 SDValue X = N0.getOperand(0).getOperand(0);
6215 if (X.getValueType().bitsLT(VT)) {
6216 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6217 } else if (X.getValueType().bitsGT(VT)) {
6218 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6220 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6221 Mask = Mask.zext(VT.getSizeInBits());
6223 return DAG.getNode(ISD::AND, DL, VT,
6224 X, DAG.getConstant(Mask, DL, VT));
6227 // fold (zext (load x)) -> (zext (truncate (zextload x)))
6228 // Only generate vector extloads when 1) they're legal, and 2) they are
6229 // deemed desirable by the target.
6230 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6231 ((!LegalOperations && !VT.isVector() &&
6232 !cast<LoadSDNode>(N0)->isVolatile()) ||
6233 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6234 bool DoXform = true;
6235 SmallVector<SDNode*, 4> SetCCs;
6236 if (!N0.hasOneUse())
6237 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6239 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6241 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6242 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6244 LN0->getBasePtr(), N0.getValueType(),
6245 LN0->getMemOperand());
6246 CombineTo(N, ExtLoad);
6247 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6248 N0.getValueType(), ExtLoad);
6249 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6251 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6253 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6257 // fold (zext (load x)) to multiple smaller zextloads.
6258 // Only on illegal but splittable vectors.
6259 if (SDValue ExtLoad = CombineExtLoad(N))
6262 // fold (zext (and/or/xor (load x), cst)) ->
6263 // (and/or/xor (zextload x), (zext cst))
6264 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6265 N0.getOpcode() == ISD::XOR) &&
6266 isa<LoadSDNode>(N0.getOperand(0)) &&
6267 N0.getOperand(1).getOpcode() == ISD::Constant &&
6268 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6269 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6270 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6271 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6272 bool DoXform = true;
6273 SmallVector<SDNode*, 4> SetCCs;
6274 if (!N0.hasOneUse())
6275 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6278 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6279 LN0->getChain(), LN0->getBasePtr(),
6281 LN0->getMemOperand());
6282 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6283 Mask = Mask.zext(VT.getSizeInBits());
6285 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6286 ExtLoad, DAG.getConstant(Mask, DL, VT));
6287 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6288 SDLoc(N0.getOperand(0)),
6289 N0.getOperand(0).getValueType(), ExtLoad);
6291 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6292 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6294 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6299 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6300 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6301 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6302 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6303 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6304 EVT MemVT = LN0->getMemoryVT();
6305 if ((!LegalOperations && !LN0->isVolatile()) ||
6306 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6307 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6309 LN0->getBasePtr(), MemVT,
6310 LN0->getMemOperand());
6311 CombineTo(N, ExtLoad);
6312 CombineTo(N0.getNode(),
6313 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6315 ExtLoad.getValue(1));
6316 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6320 if (N0.getOpcode() == ISD::SETCC) {
6321 if (!LegalOperations && VT.isVector() &&
6322 N0.getValueType().getVectorElementType() == MVT::i1) {
6323 EVT N0VT = N0.getOperand(0).getValueType();
6324 if (getSetCCResultType(N0VT) == N0.getValueType())
6327 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6328 // Only do this before legalize for now.
6329 EVT EltVT = VT.getVectorElementType();
6331 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6332 DAG.getConstant(1, DL, EltVT));
6333 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6334 // We know that the # elements of the results is the same as the
6335 // # elements of the compare (and the # elements of the compare result
6336 // for that matter). Check to see that they are the same size. If so,
6337 // we know that the element size of the sext'd result matches the
6338 // element size of the compare operands.
6339 return DAG.getNode(ISD::AND, DL, VT,
6340 DAG.getSetCC(DL, VT, N0.getOperand(0),
6342 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6343 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6346 // If the desired elements are smaller or larger than the source
6347 // elements we can use a matching integer vector type and then
6348 // truncate/sign extend
6349 EVT MatchingElementType =
6350 EVT::getIntegerVT(*DAG.getContext(),
6351 N0VT.getScalarType().getSizeInBits());
6352 EVT MatchingVectorType =
6353 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6354 N0VT.getVectorNumElements());
6356 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6358 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6359 return DAG.getNode(ISD::AND, DL, VT,
6360 DAG.getSExtOrTrunc(VsetCC, DL, VT),
6361 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6364 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6367 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6368 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6369 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6370 if (SCC.getNode()) return SCC;
6373 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6374 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6375 isa<ConstantSDNode>(N0.getOperand(1)) &&
6376 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6378 SDValue ShAmt = N0.getOperand(1);
6379 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6380 if (N0.getOpcode() == ISD::SHL) {
6381 SDValue InnerZExt = N0.getOperand(0);
6382 // If the original shl may be shifting out bits, do not perform this
6384 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6385 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6386 if (ShAmtVal > KnownZeroBits)
6392 // Ensure that the shift amount is wide enough for the shifted value.
6393 if (VT.getSizeInBits() >= 256)
6394 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6396 return DAG.getNode(N0.getOpcode(), DL, VT,
6397 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6404 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6405 SDValue N0 = N->getOperand(0);
6406 EVT VT = N->getValueType(0);
6408 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6410 return SDValue(Res, 0);
6412 // fold (aext (aext x)) -> (aext x)
6413 // fold (aext (zext x)) -> (zext x)
6414 // fold (aext (sext x)) -> (sext x)
6415 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6416 N0.getOpcode() == ISD::ZERO_EXTEND ||
6417 N0.getOpcode() == ISD::SIGN_EXTEND)
6418 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6420 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6421 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6422 if (N0.getOpcode() == ISD::TRUNCATE) {
6423 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6424 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6425 if (NarrowLoad.getNode() != N0.getNode()) {
6426 CombineTo(N0.getNode(), NarrowLoad);
6427 // CombineTo deleted the truncate, if needed, but not what's under it.
6430 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6434 // fold (aext (truncate x))
6435 if (N0.getOpcode() == ISD::TRUNCATE) {
6436 SDValue TruncOp = N0.getOperand(0);
6437 if (TruncOp.getValueType() == VT)
6438 return TruncOp; // x iff x size == zext size.
6439 if (TruncOp.getValueType().bitsGT(VT))
6440 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6441 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6444 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6445 // if the trunc is not free.
6446 if (N0.getOpcode() == ISD::AND &&
6447 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6448 N0.getOperand(1).getOpcode() == ISD::Constant &&
6449 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6450 N0.getValueType())) {
6451 SDValue X = N0.getOperand(0).getOperand(0);
6452 if (X.getValueType().bitsLT(VT)) {
6453 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6454 } else if (X.getValueType().bitsGT(VT)) {
6455 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6457 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6458 Mask = Mask.zext(VT.getSizeInBits());
6460 return DAG.getNode(ISD::AND, DL, VT,
6461 X, DAG.getConstant(Mask, DL, VT));
6464 // fold (aext (load x)) -> (aext (truncate (extload x)))
6465 // None of the supported targets knows how to perform load and any_ext
6466 // on vectors in one instruction. We only perform this transformation on
6468 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6469 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6470 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6471 bool DoXform = true;
6472 SmallVector<SDNode*, 4> SetCCs;
6473 if (!N0.hasOneUse())
6474 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6476 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6477 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6479 LN0->getBasePtr(), N0.getValueType(),
6480 LN0->getMemOperand());
6481 CombineTo(N, ExtLoad);
6482 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6483 N0.getValueType(), ExtLoad);
6484 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6485 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6487 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6491 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6492 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6493 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6494 if (N0.getOpcode() == ISD::LOAD &&
6495 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6497 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6498 ISD::LoadExtType ExtType = LN0->getExtensionType();
6499 EVT MemVT = LN0->getMemoryVT();
6500 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6501 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6502 VT, LN0->getChain(), LN0->getBasePtr(),
6503 MemVT, LN0->getMemOperand());
6504 CombineTo(N, ExtLoad);
6505 CombineTo(N0.getNode(),
6506 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6507 N0.getValueType(), ExtLoad),
6508 ExtLoad.getValue(1));
6509 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6513 if (N0.getOpcode() == ISD::SETCC) {
6515 // aext(setcc) -> vsetcc
6516 // aext(setcc) -> truncate(vsetcc)
6517 // aext(setcc) -> aext(vsetcc)
6518 // Only do this before legalize for now.
6519 if (VT.isVector() && !LegalOperations) {
6520 EVT N0VT = N0.getOperand(0).getValueType();
6521 // We know that the # elements of the results is the same as the
6522 // # elements of the compare (and the # elements of the compare result
6523 // for that matter). Check to see that they are the same size. If so,
6524 // we know that the element size of the sext'd result matches the
6525 // element size of the compare operands.
6526 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6527 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6529 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6530 // If the desired elements are smaller or larger than the source
6531 // elements we can use a matching integer vector type and then
6532 // truncate/any extend
6534 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6536 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6538 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6539 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6543 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6546 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6547 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6548 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6556 /// See if the specified operand can be simplified with the knowledge that only
6557 /// the bits specified by Mask are used. If so, return the simpler operand,
6558 /// otherwise return a null SDValue.
6559 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6560 switch (V.getOpcode()) {
6562 case ISD::Constant: {
6563 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6564 assert(CV && "Const value should be ConstSDNode.");
6565 const APInt &CVal = CV->getAPIntValue();
6566 APInt NewVal = CVal & Mask;
6568 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6573 // If the LHS or RHS don't contribute bits to the or, drop them.
6574 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6575 return V.getOperand(1);
6576 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6577 return V.getOperand(0);
6580 // Only look at single-use SRLs.
6581 if (!V.getNode()->hasOneUse())
6583 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6584 // See if we can recursively simplify the LHS.
6585 unsigned Amt = RHSC->getZExtValue();
6587 // Watch out for shift count overflow though.
6588 if (Amt >= Mask.getBitWidth()) break;
6589 APInt NewMask = Mask << Amt;
6590 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6591 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6592 SimplifyLHS, V.getOperand(1));
6598 /// If the result of a wider load is shifted to right of N bits and then
6599 /// truncated to a narrower type and where N is a multiple of number of bits of
6600 /// the narrower type, transform it to a narrower load from address + N / num of
6601 /// bits of new type. If the result is to be extended, also fold the extension
6602 /// to form a extending load.
6603 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6604 unsigned Opc = N->getOpcode();
6606 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6607 SDValue N0 = N->getOperand(0);
6608 EVT VT = N->getValueType(0);
6611 // This transformation isn't valid for vector loads.
6615 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6617 if (Opc == ISD::SIGN_EXTEND_INREG) {
6618 ExtType = ISD::SEXTLOAD;
6619 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6620 } else if (Opc == ISD::SRL) {
6621 // Another special-case: SRL is basically zero-extending a narrower value.
6622 ExtType = ISD::ZEXTLOAD;
6624 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6625 if (!N01) return SDValue();
6626 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6627 VT.getSizeInBits() - N01->getZExtValue());
6629 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6632 unsigned EVTBits = ExtVT.getSizeInBits();
6634 // Do not generate loads of non-round integer types since these can
6635 // be expensive (and would be wrong if the type is not byte sized).
6636 if (!ExtVT.isRound())
6640 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6641 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6642 ShAmt = N01->getZExtValue();
6643 // Is the shift amount a multiple of size of VT?
6644 if ((ShAmt & (EVTBits-1)) == 0) {
6645 N0 = N0.getOperand(0);
6646 // Is the load width a multiple of size of VT?
6647 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6651 // At this point, we must have a load or else we can't do the transform.
6652 if (!isa<LoadSDNode>(N0)) return SDValue();
6654 // Because a SRL must be assumed to *need* to zero-extend the high bits
6655 // (as opposed to anyext the high bits), we can't combine the zextload
6656 // lowering of SRL and an sextload.
6657 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6660 // If the shift amount is larger than the input type then we're not
6661 // accessing any of the loaded bytes. If the load was a zextload/extload
6662 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6663 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6668 // If the load is shifted left (and the result isn't shifted back right),
6669 // we can fold the truncate through the shift.
6670 unsigned ShLeftAmt = 0;
6671 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6672 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6673 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6674 ShLeftAmt = N01->getZExtValue();
6675 N0 = N0.getOperand(0);
6679 // If we haven't found a load, we can't narrow it. Don't transform one with
6680 // multiple uses, this would require adding a new load.
6681 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6684 // Don't change the width of a volatile load.
6685 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6686 if (LN0->isVolatile())
6689 // Verify that we are actually reducing a load width here.
6690 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6693 // For the transform to be legal, the load must produce only two values
6694 // (the value loaded and the chain). Don't transform a pre-increment
6695 // load, for example, which produces an extra value. Otherwise the
6696 // transformation is not equivalent, and the downstream logic to replace
6697 // uses gets things wrong.
6698 if (LN0->getNumValues() > 2)
6701 // If the load that we're shrinking is an extload and we're not just
6702 // discarding the extension we can't simply shrink the load. Bail.
6703 // TODO: It would be possible to merge the extensions in some cases.
6704 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6705 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6708 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6711 EVT PtrType = N0.getOperand(1).getValueType();
6713 if (PtrType == MVT::Untyped || PtrType.isExtended())
6714 // It's not possible to generate a constant of extended or untyped type.
6717 // For big endian targets, we need to adjust the offset to the pointer to
6718 // load the correct bytes.
6719 if (DAG.getDataLayout().isBigEndian()) {
6720 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6721 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6722 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6725 uint64_t PtrOff = ShAmt / 8;
6726 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6728 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6729 PtrType, LN0->getBasePtr(),
6730 DAG.getConstant(PtrOff, DL, PtrType));
6731 AddToWorklist(NewPtr.getNode());
6734 if (ExtType == ISD::NON_EXTLOAD)
6735 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6736 LN0->getPointerInfo().getWithOffset(PtrOff),
6737 LN0->isVolatile(), LN0->isNonTemporal(),
6738 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6740 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6741 LN0->getPointerInfo().getWithOffset(PtrOff),
6742 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6743 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6745 // Replace the old load's chain with the new load's chain.
6746 WorklistRemover DeadNodes(*this);
6747 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6749 // Shift the result left, if we've swallowed a left shift.
6750 SDValue Result = Load;
6751 if (ShLeftAmt != 0) {
6752 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6753 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6755 // If the shift amount is as large as the result size (but, presumably,
6756 // no larger than the source) then the useful bits of the result are
6757 // zero; we can't simply return the shortened shift, because the result
6758 // of that operation is undefined.
6760 if (ShLeftAmt >= VT.getSizeInBits())
6761 Result = DAG.getConstant(0, DL, VT);
6763 Result = DAG.getNode(ISD::SHL, DL, VT,
6764 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6767 // Return the new loaded value.
6771 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6772 SDValue N0 = N->getOperand(0);
6773 SDValue N1 = N->getOperand(1);
6774 EVT VT = N->getValueType(0);
6775 EVT EVT = cast<VTSDNode>(N1)->getVT();
6776 unsigned VTBits = VT.getScalarType().getSizeInBits();
6777 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6779 // fold (sext_in_reg c1) -> c1
6780 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6781 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6783 // If the input is already sign extended, just drop the extension.
6784 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6787 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6788 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6789 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6790 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6791 N0.getOperand(0), N1);
6793 // fold (sext_in_reg (sext x)) -> (sext x)
6794 // fold (sext_in_reg (aext x)) -> (sext x)
6795 // if x is small enough.
6796 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6797 SDValue N00 = N0.getOperand(0);
6798 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6799 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6800 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6803 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6804 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6805 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6807 // fold operands of sext_in_reg based on knowledge that the top bits are not
6809 if (SimplifyDemandedBits(SDValue(N, 0)))
6810 return SDValue(N, 0);
6812 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6813 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6814 if (SDValue NarrowLoad = ReduceLoadWidth(N))
6817 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6818 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6819 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6820 if (N0.getOpcode() == ISD::SRL) {
6821 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6822 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6823 // We can turn this into an SRA iff the input to the SRL is already sign
6825 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6826 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6827 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6828 N0.getOperand(0), N0.getOperand(1));
6832 // fold (sext_inreg (extload x)) -> (sextload x)
6833 if (ISD::isEXTLoad(N0.getNode()) &&
6834 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6835 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6836 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6837 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6838 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6839 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6841 LN0->getBasePtr(), EVT,
6842 LN0->getMemOperand());
6843 CombineTo(N, ExtLoad);
6844 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6845 AddToWorklist(ExtLoad.getNode());
6846 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6848 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6849 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6851 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6852 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6853 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6854 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6855 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6857 LN0->getBasePtr(), EVT,
6858 LN0->getMemOperand());
6859 CombineTo(N, ExtLoad);
6860 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6861 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6864 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6865 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6866 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6867 N0.getOperand(1), false);
6868 if (BSwap.getNode())
6869 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6873 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6874 // into a build_vector.
6875 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6876 SmallVector<SDValue, 8> Elts;
6877 unsigned NumElts = N0->getNumOperands();
6878 unsigned ShAmt = VTBits - EVTBits;
6880 for (unsigned i = 0; i != NumElts; ++i) {
6881 SDValue Op = N0->getOperand(i);
6882 if (Op->getOpcode() == ISD::UNDEF) {
6887 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6888 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6889 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6890 SDLoc(Op), Op.getValueType()));
6893 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6899 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6900 SDValue N0 = N->getOperand(0);
6901 EVT VT = N->getValueType(0);
6903 if (N0.getOpcode() == ISD::UNDEF)
6904 return DAG.getUNDEF(VT);
6906 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6908 return SDValue(Res, 0);
6913 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6914 SDValue N0 = N->getOperand(0);
6915 EVT VT = N->getValueType(0);
6916 bool isLE = DAG.getDataLayout().isLittleEndian();
6919 if (N0.getValueType() == N->getValueType(0))
6921 // fold (truncate c1) -> c1
6922 if (isConstantIntBuildVectorOrConstantInt(N0))
6923 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6924 // fold (truncate (truncate x)) -> (truncate x)
6925 if (N0.getOpcode() == ISD::TRUNCATE)
6926 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6927 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6928 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6929 N0.getOpcode() == ISD::SIGN_EXTEND ||
6930 N0.getOpcode() == ISD::ANY_EXTEND) {
6931 if (N0.getOperand(0).getValueType().bitsLT(VT))
6932 // if the source is smaller than the dest, we still need an extend
6933 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6935 if (N0.getOperand(0).getValueType().bitsGT(VT))
6936 // if the source is larger than the dest, than we just need the truncate
6937 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6938 // if the source and dest are the same type, we can drop both the extend
6939 // and the truncate.
6940 return N0.getOperand(0);
6943 // Fold extract-and-trunc into a narrow extract. For example:
6944 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6945 // i32 y = TRUNCATE(i64 x)
6947 // v16i8 b = BITCAST (v2i64 val)
6948 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6950 // Note: We only run this optimization after type legalization (which often
6951 // creates this pattern) and before operation legalization after which
6952 // we need to be more careful about the vector instructions that we generate.
6953 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6954 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6956 EVT VecTy = N0.getOperand(0).getValueType();
6957 EVT ExTy = N0.getValueType();
6958 EVT TrTy = N->getValueType(0);
6960 unsigned NumElem = VecTy.getVectorNumElements();
6961 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6963 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6964 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6966 SDValue EltNo = N0->getOperand(1);
6967 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6968 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6969 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
6970 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6972 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6973 NVT, N0.getOperand(0));
6976 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6978 DAG.getConstant(Index, DL, IndexTy));
6982 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6983 if (N0.getOpcode() == ISD::SELECT) {
6984 EVT SrcVT = N0.getValueType();
6985 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6986 TLI.isTruncateFree(SrcVT, VT)) {
6988 SDValue Cond = N0.getOperand(0);
6989 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6990 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6991 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6995 // Fold a series of buildvector, bitcast, and truncate if possible.
6997 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6998 // (2xi32 (buildvector x, y)).
6999 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7000 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7001 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7002 N0.getOperand(0).hasOneUse()) {
7004 SDValue BuildVect = N0.getOperand(0);
7005 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7006 EVT TruncVecEltTy = VT.getVectorElementType();
7008 // Check that the element types match.
7009 if (BuildVectEltTy == TruncVecEltTy) {
7010 // Now we only need to compute the offset of the truncated elements.
7011 unsigned BuildVecNumElts = BuildVect.getNumOperands();
7012 unsigned TruncVecNumElts = VT.getVectorNumElements();
7013 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7015 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7016 "Invalid number of elements");
7018 SmallVector<SDValue, 8> Opnds;
7019 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7020 Opnds.push_back(BuildVect.getOperand(i));
7022 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
7026 // See if we can simplify the input to this truncate through knowledge that
7027 // only the low bits are being used.
7028 // For example "trunc (or (shl x, 8), y)" // -> trunc y
7029 // Currently we only perform this optimization on scalars because vectors
7030 // may have different active low bits.
7031 if (!VT.isVector()) {
7033 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7034 VT.getSizeInBits()));
7035 if (Shorter.getNode())
7036 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7038 // fold (truncate (load x)) -> (smaller load x)
7039 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7040 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7041 if (SDValue Reduced = ReduceLoadWidth(N))
7044 // Handle the case where the load remains an extending load even
7045 // after truncation.
7046 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7047 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7048 if (!LN0->isVolatile() &&
7049 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7050 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7051 VT, LN0->getChain(), LN0->getBasePtr(),
7053 LN0->getMemOperand());
7054 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7059 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7060 // where ... are all 'undef'.
7061 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7062 SmallVector<EVT, 8> VTs;
7065 unsigned NumDefs = 0;
7067 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7068 SDValue X = N0.getOperand(i);
7069 if (X.getOpcode() != ISD::UNDEF) {
7074 // Stop if more than one members are non-undef.
7077 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7078 VT.getVectorElementType(),
7079 X.getValueType().getVectorNumElements()));
7083 return DAG.getUNDEF(VT);
7086 assert(V.getNode() && "The single defined operand is empty!");
7087 SmallVector<SDValue, 8> Opnds;
7088 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7090 Opnds.push_back(DAG.getUNDEF(VTs[i]));
7093 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7094 AddToWorklist(NV.getNode());
7095 Opnds.push_back(NV);
7097 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7101 // Simplify the operands using demanded-bits information.
7102 if (!VT.isVector() &&
7103 SimplifyDemandedBits(SDValue(N, 0)))
7104 return SDValue(N, 0);
7109 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7110 SDValue Elt = N->getOperand(i);
7111 if (Elt.getOpcode() != ISD::MERGE_VALUES)
7112 return Elt.getNode();
7113 return Elt.getOperand(Elt.getResNo()).getNode();
7116 /// build_pair (load, load) -> load
7117 /// if load locations are consecutive.
7118 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7119 assert(N->getOpcode() == ISD::BUILD_PAIR);
7121 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7122 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7123 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7124 LD1->getAddressSpace() != LD2->getAddressSpace())
7126 EVT LD1VT = LD1->getValueType(0);
7128 if (ISD::isNON_EXTLoad(LD2) &&
7130 // If both are volatile this would reduce the number of volatile loads.
7131 // If one is volatile it might be ok, but play conservative and bail out.
7132 !LD1->isVolatile() &&
7133 !LD2->isVolatile() &&
7134 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7135 unsigned Align = LD1->getAlignment();
7136 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7137 VT.getTypeForEVT(*DAG.getContext()));
7139 if (NewAlign <= Align &&
7140 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7141 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7142 LD1->getBasePtr(), LD1->getPointerInfo(),
7143 false, false, false, Align);
7149 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7150 SDValue N0 = N->getOperand(0);
7151 EVT VT = N->getValueType(0);
7153 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7154 // Only do this before legalize, since afterward the target may be depending
7155 // on the bitconvert.
7156 // First check to see if this is all constant.
7158 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7160 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7162 EVT DestEltVT = N->getValueType(0).getVectorElementType();
7163 assert(!DestEltVT.isVector() &&
7164 "Element type of vector ValueType must not be vector!");
7166 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7169 // If the input is a constant, let getNode fold it.
7170 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7171 // If we can't allow illegal operations, we need to check that this is just
7172 // a fp -> int or int -> conversion and that the resulting operation will
7174 if (!LegalOperations ||
7175 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7176 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7177 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7178 TLI.isOperationLegal(ISD::Constant, VT)))
7179 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7182 // (conv (conv x, t1), t2) -> (conv x, t2)
7183 if (N0.getOpcode() == ISD::BITCAST)
7184 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7187 // fold (conv (load x)) -> (load (conv*)x)
7188 // If the resultant load doesn't need a higher alignment than the original!
7189 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7190 // Do not change the width of a volatile load.
7191 !cast<LoadSDNode>(N0)->isVolatile() &&
7192 // Do not remove the cast if the types differ in endian layout.
7193 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7194 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7195 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7196 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7197 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7198 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7199 VT.getTypeForEVT(*DAG.getContext()));
7200 unsigned OrigAlign = LN0->getAlignment();
7202 if (Align <= OrigAlign) {
7203 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7204 LN0->getBasePtr(), LN0->getPointerInfo(),
7205 LN0->isVolatile(), LN0->isNonTemporal(),
7206 LN0->isInvariant(), OrigAlign,
7208 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7213 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7214 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7215 // This often reduces constant pool loads.
7216 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7217 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7218 N0.getNode()->hasOneUse() && VT.isInteger() &&
7219 !VT.isVector() && !N0.getValueType().isVector()) {
7220 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7222 AddToWorklist(NewConv.getNode());
7225 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7226 if (N0.getOpcode() == ISD::FNEG)
7227 return DAG.getNode(ISD::XOR, DL, VT,
7228 NewConv, DAG.getConstant(SignBit, DL, VT));
7229 assert(N0.getOpcode() == ISD::FABS);
7230 return DAG.getNode(ISD::AND, DL, VT,
7231 NewConv, DAG.getConstant(~SignBit, DL, VT));
7234 // fold (bitconvert (fcopysign cst, x)) ->
7235 // (or (and (bitconvert x), sign), (and cst, (not sign)))
7236 // Note that we don't handle (copysign x, cst) because this can always be
7237 // folded to an fneg or fabs.
7238 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7239 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7240 VT.isInteger() && !VT.isVector()) {
7241 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7242 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7243 if (isTypeLegal(IntXVT)) {
7244 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7245 IntXVT, N0.getOperand(1));
7246 AddToWorklist(X.getNode());
7248 // If X has a different width than the result/lhs, sext it or truncate it.
7249 unsigned VTWidth = VT.getSizeInBits();
7250 if (OrigXWidth < VTWidth) {
7251 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7252 AddToWorklist(X.getNode());
7253 } else if (OrigXWidth > VTWidth) {
7254 // To get the sign bit in the right place, we have to shift it right
7255 // before truncating.
7257 X = DAG.getNode(ISD::SRL, DL,
7258 X.getValueType(), X,
7259 DAG.getConstant(OrigXWidth-VTWidth, DL,
7261 AddToWorklist(X.getNode());
7262 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7263 AddToWorklist(X.getNode());
7266 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7267 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7268 X, DAG.getConstant(SignBit, SDLoc(X), VT));
7269 AddToWorklist(X.getNode());
7271 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7272 VT, N0.getOperand(0));
7273 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7274 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7275 AddToWorklist(Cst.getNode());
7277 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7281 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7282 if (N0.getOpcode() == ISD::BUILD_PAIR)
7283 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7286 // Remove double bitcasts from shuffles - this is often a legacy of
7287 // XformToShuffleWithZero being used to combine bitmaskings (of
7288 // float vectors bitcast to integer vectors) into shuffles.
7289 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7290 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7291 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7292 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7293 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7294 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7296 // If operands are a bitcast, peek through if it casts the original VT.
7297 // If operands are a constant, just bitcast back to original VT.
7298 auto PeekThroughBitcast = [&](SDValue Op) {
7299 if (Op.getOpcode() == ISD::BITCAST &&
7300 Op.getOperand(0).getValueType() == VT)
7301 return SDValue(Op.getOperand(0));
7302 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7303 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7304 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7308 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7309 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7314 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7315 SmallVector<int, 8> NewMask;
7316 for (int M : SVN->getMask())
7317 for (int i = 0; i != MaskScale; ++i)
7318 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7320 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7322 std::swap(SV0, SV1);
7323 ShuffleVectorSDNode::commuteMask(NewMask);
7324 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7328 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7334 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7335 EVT VT = N->getValueType(0);
7336 return CombineConsecutiveLoads(N, VT);
7339 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7340 /// operands. DstEltVT indicates the destination element value type.
7341 SDValue DAGCombiner::
7342 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7343 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7345 // If this is already the right type, we're done.
7346 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7348 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7349 unsigned DstBitSize = DstEltVT.getSizeInBits();
7351 // If this is a conversion of N elements of one type to N elements of another
7352 // type, convert each element. This handles FP<->INT cases.
7353 if (SrcBitSize == DstBitSize) {
7354 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7355 BV->getValueType(0).getVectorNumElements());
7357 // Due to the FP element handling below calling this routine recursively,
7358 // we can end up with a scalar-to-vector node here.
7359 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7360 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7361 DAG.getNode(ISD::BITCAST, SDLoc(BV),
7362 DstEltVT, BV->getOperand(0)));
7364 SmallVector<SDValue, 8> Ops;
7365 for (SDValue Op : BV->op_values()) {
7366 // If the vector element type is not legal, the BUILD_VECTOR operands
7367 // are promoted and implicitly truncated. Make that explicit here.
7368 if (Op.getValueType() != SrcEltVT)
7369 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7370 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7372 AddToWorklist(Ops.back().getNode());
7374 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7377 // Otherwise, we're growing or shrinking the elements. To avoid having to
7378 // handle annoying details of growing/shrinking FP values, we convert them to
7380 if (SrcEltVT.isFloatingPoint()) {
7381 // Convert the input float vector to a int vector where the elements are the
7383 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7384 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7388 // Now we know the input is an integer vector. If the output is a FP type,
7389 // convert to integer first, then to FP of the right size.
7390 if (DstEltVT.isFloatingPoint()) {
7391 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7392 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7394 // Next, convert to FP elements of the same size.
7395 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7400 // Okay, we know the src/dst types are both integers of differing types.
7401 // Handling growing first.
7402 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7403 if (SrcBitSize < DstBitSize) {
7404 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7406 SmallVector<SDValue, 8> Ops;
7407 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7408 i += NumInputsPerOutput) {
7409 bool isLE = DAG.getDataLayout().isLittleEndian();
7410 APInt NewBits = APInt(DstBitSize, 0);
7411 bool EltIsUndef = true;
7412 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7413 // Shift the previously computed bits over.
7414 NewBits <<= SrcBitSize;
7415 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7416 if (Op.getOpcode() == ISD::UNDEF) continue;
7419 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7420 zextOrTrunc(SrcBitSize).zext(DstBitSize);
7424 Ops.push_back(DAG.getUNDEF(DstEltVT));
7426 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7429 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7430 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7433 // Finally, this must be the case where we are shrinking elements: each input
7434 // turns into multiple outputs.
7435 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7436 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7437 NumOutputsPerInput*BV->getNumOperands());
7438 SmallVector<SDValue, 8> Ops;
7440 for (const SDValue &Op : BV->op_values()) {
7441 if (Op.getOpcode() == ISD::UNDEF) {
7442 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7446 APInt OpVal = cast<ConstantSDNode>(Op)->
7447 getAPIntValue().zextOrTrunc(SrcBitSize);
7449 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7450 APInt ThisVal = OpVal.trunc(DstBitSize);
7451 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7452 OpVal = OpVal.lshr(DstBitSize);
7455 // For big endian targets, swap the order of the pieces of each element.
7456 if (DAG.getDataLayout().isBigEndian())
7457 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7460 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7463 /// Try to perform FMA combining on a given FADD node.
7464 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7465 SDValue N0 = N->getOperand(0);
7466 SDValue N1 = N->getOperand(1);
7467 EVT VT = N->getValueType(0);
7470 const TargetOptions &Options = DAG.getTarget().Options;
7471 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7472 Options.UnsafeFPMath);
7474 // Floating-point multiply-add with intermediate rounding.
7475 bool HasFMAD = (LegalOperations &&
7476 TLI.isOperationLegal(ISD::FMAD, VT));
7478 // Floating-point multiply-add without intermediate rounding.
7479 bool HasFMA = ((!LegalOperations ||
7480 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7481 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7484 // No valid opcode, do not combine.
7485 if (!HasFMAD && !HasFMA)
7488 // Always prefer FMAD to FMA for precision.
7489 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7490 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7491 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7493 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7494 // prefer to fold the multiply with fewer uses.
7495 if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7496 N1.getOpcode() == ISD::FMUL) {
7497 if (N0.getNode()->use_size() > N1.getNode()->use_size())
7501 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7502 if (N0.getOpcode() == ISD::FMUL &&
7503 (Aggressive || N0->hasOneUse())) {
7504 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7505 N0.getOperand(0), N0.getOperand(1), N1);
7508 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7509 // Note: Commutes FADD operands.
7510 if (N1.getOpcode() == ISD::FMUL &&
7511 (Aggressive || N1->hasOneUse())) {
7512 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7513 N1.getOperand(0), N1.getOperand(1), N0);
7516 // Look through FP_EXTEND nodes to do more combining.
7517 if (UnsafeFPMath && LookThroughFPExt) {
7518 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7519 if (N0.getOpcode() == ISD::FP_EXTEND) {
7520 SDValue N00 = N0.getOperand(0);
7521 if (N00.getOpcode() == ISD::FMUL)
7522 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7523 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7525 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7526 N00.getOperand(1)), N1);
7529 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7530 // Note: Commutes FADD operands.
7531 if (N1.getOpcode() == ISD::FP_EXTEND) {
7532 SDValue N10 = N1.getOperand(0);
7533 if (N10.getOpcode() == ISD::FMUL)
7534 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7535 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7537 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7538 N10.getOperand(1)), N0);
7542 // More folding opportunities when target permits.
7543 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7544 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7545 if (N0.getOpcode() == PreferredFusedOpcode &&
7546 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7547 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7548 N0.getOperand(0), N0.getOperand(1),
7549 DAG.getNode(PreferredFusedOpcode, SL, VT,
7550 N0.getOperand(2).getOperand(0),
7551 N0.getOperand(2).getOperand(1),
7555 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7556 if (N1->getOpcode() == PreferredFusedOpcode &&
7557 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7558 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7559 N1.getOperand(0), N1.getOperand(1),
7560 DAG.getNode(PreferredFusedOpcode, SL, VT,
7561 N1.getOperand(2).getOperand(0),
7562 N1.getOperand(2).getOperand(1),
7566 if (UnsafeFPMath && LookThroughFPExt) {
7567 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7568 // -> (fma x, y, (fma (fpext u), (fpext v), z))
7569 auto FoldFAddFMAFPExtFMul = [&] (
7570 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7571 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7572 DAG.getNode(PreferredFusedOpcode, SL, VT,
7573 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7574 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7577 if (N0.getOpcode() == PreferredFusedOpcode) {
7578 SDValue N02 = N0.getOperand(2);
7579 if (N02.getOpcode() == ISD::FP_EXTEND) {
7580 SDValue N020 = N02.getOperand(0);
7581 if (N020.getOpcode() == ISD::FMUL)
7582 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7583 N020.getOperand(0), N020.getOperand(1),
7588 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7589 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7590 // FIXME: This turns two single-precision and one double-precision
7591 // operation into two double-precision operations, which might not be
7592 // interesting for all targets, especially GPUs.
7593 auto FoldFAddFPExtFMAFMul = [&] (
7594 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7595 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7596 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7597 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7598 DAG.getNode(PreferredFusedOpcode, SL, VT,
7599 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7600 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7603 if (N0.getOpcode() == ISD::FP_EXTEND) {
7604 SDValue N00 = N0.getOperand(0);
7605 if (N00.getOpcode() == PreferredFusedOpcode) {
7606 SDValue N002 = N00.getOperand(2);
7607 if (N002.getOpcode() == ISD::FMUL)
7608 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7609 N002.getOperand(0), N002.getOperand(1),
7614 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7615 // -> (fma y, z, (fma (fpext u), (fpext v), x))
7616 if (N1.getOpcode() == PreferredFusedOpcode) {
7617 SDValue N12 = N1.getOperand(2);
7618 if (N12.getOpcode() == ISD::FP_EXTEND) {
7619 SDValue N120 = N12.getOperand(0);
7620 if (N120.getOpcode() == ISD::FMUL)
7621 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7622 N120.getOperand(0), N120.getOperand(1),
7627 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7628 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7629 // FIXME: This turns two single-precision and one double-precision
7630 // operation into two double-precision operations, which might not be
7631 // interesting for all targets, especially GPUs.
7632 if (N1.getOpcode() == ISD::FP_EXTEND) {
7633 SDValue N10 = N1.getOperand(0);
7634 if (N10.getOpcode() == PreferredFusedOpcode) {
7635 SDValue N102 = N10.getOperand(2);
7636 if (N102.getOpcode() == ISD::FMUL)
7637 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7638 N102.getOperand(0), N102.getOperand(1),
7648 /// Try to perform FMA combining on a given FSUB node.
7649 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7650 SDValue N0 = N->getOperand(0);
7651 SDValue N1 = N->getOperand(1);
7652 EVT VT = N->getValueType(0);
7655 const TargetOptions &Options = DAG.getTarget().Options;
7656 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7657 Options.UnsafeFPMath);
7659 // Floating-point multiply-add with intermediate rounding.
7660 bool HasFMAD = (LegalOperations &&
7661 TLI.isOperationLegal(ISD::FMAD, VT));
7663 // Floating-point multiply-add without intermediate rounding.
7664 bool HasFMA = ((!LegalOperations ||
7665 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7666 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7669 // No valid opcode, do not combine.
7670 if (!HasFMAD && !HasFMA)
7673 // Always prefer FMAD to FMA for precision.
7674 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7675 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7676 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7678 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7679 if (N0.getOpcode() == ISD::FMUL &&
7680 (Aggressive || N0->hasOneUse())) {
7681 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7682 N0.getOperand(0), N0.getOperand(1),
7683 DAG.getNode(ISD::FNEG, SL, VT, N1));
7686 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7687 // Note: Commutes FSUB operands.
7688 if (N1.getOpcode() == ISD::FMUL &&
7689 (Aggressive || N1->hasOneUse()))
7690 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7691 DAG.getNode(ISD::FNEG, SL, VT,
7693 N1.getOperand(1), N0);
7695 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7696 if (N0.getOpcode() == ISD::FNEG &&
7697 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7698 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7699 SDValue N00 = N0.getOperand(0).getOperand(0);
7700 SDValue N01 = N0.getOperand(0).getOperand(1);
7701 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7702 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7703 DAG.getNode(ISD::FNEG, SL, VT, N1));
7706 // Look through FP_EXTEND nodes to do more combining.
7707 if (UnsafeFPMath && LookThroughFPExt) {
7708 // fold (fsub (fpext (fmul x, y)), z)
7709 // -> (fma (fpext x), (fpext y), (fneg z))
7710 if (N0.getOpcode() == ISD::FP_EXTEND) {
7711 SDValue N00 = N0.getOperand(0);
7712 if (N00.getOpcode() == ISD::FMUL)
7713 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7714 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7716 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7718 DAG.getNode(ISD::FNEG, SL, VT, N1));
7721 // fold (fsub x, (fpext (fmul y, z)))
7722 // -> (fma (fneg (fpext y)), (fpext z), x)
7723 // Note: Commutes FSUB operands.
7724 if (N1.getOpcode() == ISD::FP_EXTEND) {
7725 SDValue N10 = N1.getOperand(0);
7726 if (N10.getOpcode() == ISD::FMUL)
7727 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7728 DAG.getNode(ISD::FNEG, SL, VT,
7729 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7730 N10.getOperand(0))),
7731 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7736 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7737 // -> (fneg (fma (fpext x), (fpext y), z))
7738 // Note: This could be removed with appropriate canonicalization of the
7739 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7740 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7741 // from implementing the canonicalization in visitFSUB.
7742 if (N0.getOpcode() == ISD::FP_EXTEND) {
7743 SDValue N00 = N0.getOperand(0);
7744 if (N00.getOpcode() == ISD::FNEG) {
7745 SDValue N000 = N00.getOperand(0);
7746 if (N000.getOpcode() == ISD::FMUL) {
7747 return DAG.getNode(ISD::FNEG, SL, VT,
7748 DAG.getNode(PreferredFusedOpcode, SL, VT,
7749 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7750 N000.getOperand(0)),
7751 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7752 N000.getOperand(1)),
7758 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7759 // -> (fneg (fma (fpext x)), (fpext y), z)
7760 // Note: This could be removed with appropriate canonicalization of the
7761 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7762 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7763 // from implementing the canonicalization in visitFSUB.
7764 if (N0.getOpcode() == ISD::FNEG) {
7765 SDValue N00 = N0.getOperand(0);
7766 if (N00.getOpcode() == ISD::FP_EXTEND) {
7767 SDValue N000 = N00.getOperand(0);
7768 if (N000.getOpcode() == ISD::FMUL) {
7769 return DAG.getNode(ISD::FNEG, SL, VT,
7770 DAG.getNode(PreferredFusedOpcode, SL, VT,
7771 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7772 N000.getOperand(0)),
7773 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7774 N000.getOperand(1)),
7782 // More folding opportunities when target permits.
7783 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7784 // fold (fsub (fma x, y, (fmul u, v)), z)
7785 // -> (fma x, y (fma u, v, (fneg z)))
7786 if (N0.getOpcode() == PreferredFusedOpcode &&
7787 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7788 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7789 N0.getOperand(0), N0.getOperand(1),
7790 DAG.getNode(PreferredFusedOpcode, SL, VT,
7791 N0.getOperand(2).getOperand(0),
7792 N0.getOperand(2).getOperand(1),
7793 DAG.getNode(ISD::FNEG, SL, VT,
7797 // fold (fsub x, (fma y, z, (fmul u, v)))
7798 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7799 if (N1.getOpcode() == PreferredFusedOpcode &&
7800 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7801 SDValue N20 = N1.getOperand(2).getOperand(0);
7802 SDValue N21 = N1.getOperand(2).getOperand(1);
7803 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7804 DAG.getNode(ISD::FNEG, SL, VT,
7807 DAG.getNode(PreferredFusedOpcode, SL, VT,
7808 DAG.getNode(ISD::FNEG, SL, VT, N20),
7813 if (UnsafeFPMath && LookThroughFPExt) {
7814 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7815 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7816 if (N0.getOpcode() == PreferredFusedOpcode) {
7817 SDValue N02 = N0.getOperand(2);
7818 if (N02.getOpcode() == ISD::FP_EXTEND) {
7819 SDValue N020 = N02.getOperand(0);
7820 if (N020.getOpcode() == ISD::FMUL)
7821 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7822 N0.getOperand(0), N0.getOperand(1),
7823 DAG.getNode(PreferredFusedOpcode, SL, VT,
7824 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7825 N020.getOperand(0)),
7826 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7827 N020.getOperand(1)),
7828 DAG.getNode(ISD::FNEG, SL, VT,
7833 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7834 // -> (fma (fpext x), (fpext y),
7835 // (fma (fpext u), (fpext v), (fneg z)))
7836 // FIXME: This turns two single-precision and one double-precision
7837 // operation into two double-precision operations, which might not be
7838 // interesting for all targets, especially GPUs.
7839 if (N0.getOpcode() == ISD::FP_EXTEND) {
7840 SDValue N00 = N0.getOperand(0);
7841 if (N00.getOpcode() == PreferredFusedOpcode) {
7842 SDValue N002 = N00.getOperand(2);
7843 if (N002.getOpcode() == ISD::FMUL)
7844 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7845 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7847 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7849 DAG.getNode(PreferredFusedOpcode, SL, VT,
7850 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7851 N002.getOperand(0)),
7852 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7853 N002.getOperand(1)),
7854 DAG.getNode(ISD::FNEG, SL, VT,
7859 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7860 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7861 if (N1.getOpcode() == PreferredFusedOpcode &&
7862 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7863 SDValue N120 = N1.getOperand(2).getOperand(0);
7864 if (N120.getOpcode() == ISD::FMUL) {
7865 SDValue N1200 = N120.getOperand(0);
7866 SDValue N1201 = N120.getOperand(1);
7867 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7868 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7870 DAG.getNode(PreferredFusedOpcode, SL, VT,
7871 DAG.getNode(ISD::FNEG, SL, VT,
7872 DAG.getNode(ISD::FP_EXTEND, SL,
7874 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7880 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7881 // -> (fma (fneg (fpext y)), (fpext z),
7882 // (fma (fneg (fpext u)), (fpext v), x))
7883 // FIXME: This turns two single-precision and one double-precision
7884 // operation into two double-precision operations, which might not be
7885 // interesting for all targets, especially GPUs.
7886 if (N1.getOpcode() == ISD::FP_EXTEND &&
7887 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7888 SDValue N100 = N1.getOperand(0).getOperand(0);
7889 SDValue N101 = N1.getOperand(0).getOperand(1);
7890 SDValue N102 = N1.getOperand(0).getOperand(2);
7891 if (N102.getOpcode() == ISD::FMUL) {
7892 SDValue N1020 = N102.getOperand(0);
7893 SDValue N1021 = N102.getOperand(1);
7894 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7895 DAG.getNode(ISD::FNEG, SL, VT,
7896 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7898 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7899 DAG.getNode(PreferredFusedOpcode, SL, VT,
7900 DAG.getNode(ISD::FNEG, SL, VT,
7901 DAG.getNode(ISD::FP_EXTEND, SL,
7903 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7914 SDValue DAGCombiner::visitFADD(SDNode *N) {
7915 SDValue N0 = N->getOperand(0);
7916 SDValue N1 = N->getOperand(1);
7917 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7918 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7919 EVT VT = N->getValueType(0);
7921 const TargetOptions &Options = DAG.getTarget().Options;
7925 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7928 // fold (fadd c1, c2) -> c1 + c2
7930 return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7932 // canonicalize constant to RHS
7933 if (N0CFP && !N1CFP)
7934 return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7936 // fold (fadd A, (fneg B)) -> (fsub A, B)
7937 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7938 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7939 return DAG.getNode(ISD::FSUB, DL, VT, N0,
7940 GetNegatedExpression(N1, DAG, LegalOperations));
7942 // fold (fadd (fneg A), B) -> (fsub B, A)
7943 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7944 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7945 return DAG.getNode(ISD::FSUB, DL, VT, N1,
7946 GetNegatedExpression(N0, DAG, LegalOperations));
7948 // If 'unsafe math' is enabled, fold lots of things.
7949 if (Options.UnsafeFPMath) {
7950 // No FP constant should be created after legalization as Instruction
7951 // Selection pass has a hard time dealing with FP constants.
7952 bool AllowNewConst = (Level < AfterLegalizeDAG);
7954 // fold (fadd A, 0) -> A
7955 if (N1CFP && N1CFP->isZero())
7958 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7959 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7960 isa<ConstantFPSDNode>(N0.getOperand(1)))
7961 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7962 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7964 // If allowed, fold (fadd (fneg x), x) -> 0.0
7965 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7966 return DAG.getConstantFP(0.0, DL, VT);
7968 // If allowed, fold (fadd x, (fneg x)) -> 0.0
7969 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7970 return DAG.getConstantFP(0.0, DL, VT);
7972 // We can fold chains of FADD's of the same value into multiplications.
7973 // This transform is not safe in general because we are reducing the number
7974 // of rounding steps.
7975 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7976 if (N0.getOpcode() == ISD::FMUL) {
7977 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7978 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7980 // (fadd (fmul x, c), x) -> (fmul x, c+1)
7981 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7982 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7983 DAG.getConstantFP(1.0, DL, VT));
7984 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7987 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7988 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7989 N1.getOperand(0) == N1.getOperand(1) &&
7990 N0.getOperand(0) == N1.getOperand(0)) {
7991 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7992 DAG.getConstantFP(2.0, DL, VT));
7993 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
7997 if (N1.getOpcode() == ISD::FMUL) {
7998 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7999 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
8001 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8002 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8003 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
8004 DAG.getConstantFP(1.0, DL, VT));
8005 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
8008 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8009 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8010 N0.getOperand(0) == N0.getOperand(1) &&
8011 N1.getOperand(0) == N0.getOperand(0)) {
8012 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
8013 DAG.getConstantFP(2.0, DL, VT));
8014 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
8018 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8019 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
8020 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8021 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
8022 (N0.getOperand(0) == N1)) {
8023 return DAG.getNode(ISD::FMUL, DL, VT,
8024 N1, DAG.getConstantFP(3.0, DL, VT));
8028 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8029 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
8030 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8031 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8032 N1.getOperand(0) == N0) {
8033 return DAG.getNode(ISD::FMUL, DL, VT,
8034 N0, DAG.getConstantFP(3.0, DL, VT));
8038 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8039 if (AllowNewConst &&
8040 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8041 N0.getOperand(0) == N0.getOperand(1) &&
8042 N1.getOperand(0) == N1.getOperand(1) &&
8043 N0.getOperand(0) == N1.getOperand(0)) {
8044 return DAG.getNode(ISD::FMUL, DL, VT,
8045 N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
8048 } // enable-unsafe-fp-math
8050 // FADD -> FMA combines:
8051 if (SDValue Fused = visitFADDForFMACombine(N)) {
8052 AddToWorklist(Fused.getNode());
8059 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8060 SDValue N0 = N->getOperand(0);
8061 SDValue N1 = N->getOperand(1);
8062 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8063 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8064 EVT VT = N->getValueType(0);
8066 const TargetOptions &Options = DAG.getTarget().Options;
8070 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8073 // fold (fsub c1, c2) -> c1-c2
8075 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
8077 // fold (fsub A, (fneg B)) -> (fadd A, B)
8078 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8079 return DAG.getNode(ISD::FADD, dl, VT, N0,
8080 GetNegatedExpression(N1, DAG, LegalOperations));
8082 // If 'unsafe math' is enabled, fold lots of things.
8083 if (Options.UnsafeFPMath) {
8085 if (N1CFP && N1CFP->isZero())
8088 // (fsub 0, B) -> -B
8089 if (N0CFP && N0CFP->isZero()) {
8090 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8091 return GetNegatedExpression(N1, DAG, LegalOperations);
8092 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8093 return DAG.getNode(ISD::FNEG, dl, VT, N1);
8096 // (fsub x, x) -> 0.0
8098 return DAG.getConstantFP(0.0f, dl, VT);
8100 // (fsub x, (fadd x, y)) -> (fneg y)
8101 // (fsub x, (fadd y, x)) -> (fneg y)
8102 if (N1.getOpcode() == ISD::FADD) {
8103 SDValue N10 = N1->getOperand(0);
8104 SDValue N11 = N1->getOperand(1);
8106 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8107 return GetNegatedExpression(N11, DAG, LegalOperations);
8109 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8110 return GetNegatedExpression(N10, DAG, LegalOperations);
8114 // FSUB -> FMA combines:
8115 if (SDValue Fused = visitFSUBForFMACombine(N)) {
8116 AddToWorklist(Fused.getNode());
8123 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8124 SDValue N0 = N->getOperand(0);
8125 SDValue N1 = N->getOperand(1);
8126 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8127 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8128 EVT VT = N->getValueType(0);
8130 const TargetOptions &Options = DAG.getTarget().Options;
8133 if (VT.isVector()) {
8134 // This just handles C1 * C2 for vectors. Other vector folds are below.
8135 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8139 // fold (fmul c1, c2) -> c1*c2
8141 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
8143 // canonicalize constant to RHS
8144 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8145 !isConstantFPBuildVectorOrConstantFP(N1))
8146 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
8148 // fold (fmul A, 1.0) -> A
8149 if (N1CFP && N1CFP->isExactlyValue(1.0))
8152 if (Options.UnsafeFPMath) {
8153 // fold (fmul A, 0) -> 0
8154 if (N1CFP && N1CFP->isZero())
8157 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8158 if (N0.getOpcode() == ISD::FMUL) {
8159 // Fold scalars or any vector constants (not just splats).
8160 // This fold is done in general by InstCombine, but extra fmul insts
8161 // may have been generated during lowering.
8162 SDValue N00 = N0.getOperand(0);
8163 SDValue N01 = N0.getOperand(1);
8164 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8165 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8166 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8168 // Check 1: Make sure that the first operand of the inner multiply is NOT
8169 // a constant. Otherwise, we may induce infinite looping.
8170 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8171 // Check 2: Make sure that the second operand of the inner multiply and
8172 // the second operand of the outer multiply are constants.
8173 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8174 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8175 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8176 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
8181 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8182 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8183 // during an early run of DAGCombiner can prevent folding with fmuls
8184 // inserted during lowering.
8185 if (N0.getOpcode() == ISD::FADD &&
8186 (N0.getOperand(0) == N0.getOperand(1)) &&
8188 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8189 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8190 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
8194 // fold (fmul X, 2.0) -> (fadd X, X)
8195 if (N1CFP && N1CFP->isExactlyValue(+2.0))
8196 return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
8198 // fold (fmul X, -1.0) -> (fneg X)
8199 if (N1CFP && N1CFP->isExactlyValue(-1.0))
8200 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8201 return DAG.getNode(ISD::FNEG, DL, VT, N0);
8203 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8204 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8205 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8206 // Both can be negated for free, check to see if at least one is cheaper
8208 if (LHSNeg == 2 || RHSNeg == 2)
8209 return DAG.getNode(ISD::FMUL, DL, VT,
8210 GetNegatedExpression(N0, DAG, LegalOperations),
8211 GetNegatedExpression(N1, DAG, LegalOperations));
8218 SDValue DAGCombiner::visitFMA(SDNode *N) {
8219 SDValue N0 = N->getOperand(0);
8220 SDValue N1 = N->getOperand(1);
8221 SDValue N2 = N->getOperand(2);
8222 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8223 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8224 EVT VT = N->getValueType(0);
8226 const TargetOptions &Options = DAG.getTarget().Options;
8228 // Constant fold FMA.
8229 if (isa<ConstantFPSDNode>(N0) &&
8230 isa<ConstantFPSDNode>(N1) &&
8231 isa<ConstantFPSDNode>(N2)) {
8232 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8235 if (Options.UnsafeFPMath) {
8236 if (N0CFP && N0CFP->isZero())
8238 if (N1CFP && N1CFP->isZero())
8241 if (N0CFP && N0CFP->isExactlyValue(1.0))
8242 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8243 if (N1CFP && N1CFP->isExactlyValue(1.0))
8244 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8246 // Canonicalize (fma c, x, y) -> (fma x, c, y)
8247 if (N0CFP && !N1CFP)
8248 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8250 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8251 if (Options.UnsafeFPMath && N1CFP &&
8252 N2.getOpcode() == ISD::FMUL &&
8253 N0 == N2.getOperand(0) &&
8254 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8255 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8256 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8260 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8261 if (Options.UnsafeFPMath &&
8262 N0.getOpcode() == ISD::FMUL && N1CFP &&
8263 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8264 return DAG.getNode(ISD::FMA, dl, VT,
8266 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8270 // (fma x, 1, y) -> (fadd x, y)
8271 // (fma x, -1, y) -> (fadd (fneg x), y)
8273 if (N1CFP->isExactlyValue(1.0))
8274 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8276 if (N1CFP->isExactlyValue(-1.0) &&
8277 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8278 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8279 AddToWorklist(RHSNeg.getNode());
8280 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8284 // (fma x, c, x) -> (fmul x, (c+1))
8285 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8286 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8287 DAG.getNode(ISD::FADD, dl, VT,
8288 N1, DAG.getConstantFP(1.0, dl, VT)));
8290 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8291 if (Options.UnsafeFPMath && N1CFP &&
8292 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8293 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8294 DAG.getNode(ISD::FADD, dl, VT,
8295 N1, DAG.getConstantFP(-1.0, dl, VT)));
8301 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8303 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8304 // Notice that this is not always beneficial. One reason is different target
8305 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8306 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8307 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8308 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8309 if (!DAG.getTarget().Options.UnsafeFPMath)
8312 // Skip if current node is a reciprocal.
8313 SDValue N0 = N->getOperand(0);
8314 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8315 if (N0CFP && N0CFP->isExactlyValue(1.0))
8318 // Exit early if the target does not want this transform or if there can't
8319 // possibly be enough uses of the divisor to make the transform worthwhile.
8320 SDValue N1 = N->getOperand(1);
8321 unsigned MinUses = TLI.combineRepeatedFPDivisors();
8322 if (!MinUses || N1->use_size() < MinUses)
8325 // Find all FDIV users of the same divisor.
8326 // Use a set because duplicates may be present in the user list.
8327 SetVector<SDNode *> Users;
8328 for (auto *U : N1->uses())
8329 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8332 // Now that we have the actual number of divisor uses, make sure it meets
8333 // the minimum threshold specified by the target.
8334 if (Users.size() < MinUses)
8337 EVT VT = N->getValueType(0);
8339 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8340 // FIXME: This optimization requires some level of fast-math, so the
8341 // created reciprocal node should at least have the 'allowReciprocal'
8342 // fast-math-flag set.
8343 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8345 // Dividend / Divisor -> Dividend * Reciprocal
8346 for (auto *U : Users) {
8347 SDValue Dividend = U->getOperand(0);
8348 if (Dividend != FPOne) {
8349 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8351 CombineTo(U, NewNode);
8352 } else if (U != Reciprocal.getNode()) {
8353 // In the absence of fast-math-flags, this user node is always the
8354 // same node as Reciprocal, but with FMF they may be different nodes.
8355 CombineTo(U, Reciprocal);
8358 return SDValue(N, 0); // N was replaced.
8361 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8362 SDValue N0 = N->getOperand(0);
8363 SDValue N1 = N->getOperand(1);
8364 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8365 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8366 EVT VT = N->getValueType(0);
8368 const TargetOptions &Options = DAG.getTarget().Options;
8372 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8375 // fold (fdiv c1, c2) -> c1/c2
8377 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8379 if (Options.UnsafeFPMath) {
8380 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8382 // Compute the reciprocal 1.0 / c2.
8383 APFloat N1APF = N1CFP->getValueAPF();
8384 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8385 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8386 // Only do the transform if the reciprocal is a legal fp immediate that
8387 // isn't too nasty (eg NaN, denormal, ...).
8388 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8389 (!LegalOperations ||
8390 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8391 // backend)... we should handle this gracefully after Legalize.
8392 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8393 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8394 TLI.isFPImmLegal(Recip, VT)))
8395 return DAG.getNode(ISD::FMUL, DL, VT, N0,
8396 DAG.getConstantFP(Recip, DL, VT));
8399 // If this FDIV is part of a reciprocal square root, it may be folded
8400 // into a target-specific square root estimate instruction.
8401 if (N1.getOpcode() == ISD::FSQRT) {
8402 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8403 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8405 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8406 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8407 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8408 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8409 AddToWorklist(RV.getNode());
8410 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8412 } else if (N1.getOpcode() == ISD::FP_ROUND &&
8413 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8414 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8415 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8416 AddToWorklist(RV.getNode());
8417 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8419 } else if (N1.getOpcode() == ISD::FMUL) {
8420 // Look through an FMUL. Even though this won't remove the FDIV directly,
8421 // it's still worthwhile to get rid of the FSQRT if possible.
8424 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8425 SqrtOp = N1.getOperand(0);
8426 OtherOp = N1.getOperand(1);
8427 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8428 SqrtOp = N1.getOperand(1);
8429 OtherOp = N1.getOperand(0);
8431 if (SqrtOp.getNode()) {
8432 // We found a FSQRT, so try to make this fold:
8433 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8434 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8435 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8436 AddToWorklist(RV.getNode());
8437 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8442 // Fold into a reciprocal estimate and multiply instead of a real divide.
8443 if (SDValue RV = BuildReciprocalEstimate(N1)) {
8444 AddToWorklist(RV.getNode());
8445 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8449 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8450 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8451 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8452 // Both can be negated for free, check to see if at least one is cheaper
8454 if (LHSNeg == 2 || RHSNeg == 2)
8455 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8456 GetNegatedExpression(N0, DAG, LegalOperations),
8457 GetNegatedExpression(N1, DAG, LegalOperations));
8461 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8462 return CombineRepeatedDivisors;
8467 SDValue DAGCombiner::visitFREM(SDNode *N) {
8468 SDValue N0 = N->getOperand(0);
8469 SDValue N1 = N->getOperand(1);
8470 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8471 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8472 EVT VT = N->getValueType(0);
8474 // fold (frem c1, c2) -> fmod(c1,c2)
8476 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8481 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8482 if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8485 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8486 SDValue RV = BuildRsqrtEstimate(N->getOperand(0));
8490 EVT VT = RV.getValueType();
8492 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8493 AddToWorklist(RV.getNode());
8495 // Unfortunately, RV is now NaN if the input was exactly 0.
8496 // Select out this case and force the answer to 0.
8497 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8498 EVT CCVT = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8499 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8500 AddToWorklist(ZeroCmp.getNode());
8501 AddToWorklist(RV.getNode());
8503 return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8507 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8508 SDValue N0 = N->getOperand(0);
8509 SDValue N1 = N->getOperand(1);
8510 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8511 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8512 EVT VT = N->getValueType(0);
8514 if (N0CFP && N1CFP) // Constant fold
8515 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8518 const APFloat& V = N1CFP->getValueAPF();
8519 // copysign(x, c1) -> fabs(x) iff ispos(c1)
8520 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8521 if (!V.isNegative()) {
8522 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8523 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8525 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8526 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8527 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8531 // copysign(fabs(x), y) -> copysign(x, y)
8532 // copysign(fneg(x), y) -> copysign(x, y)
8533 // copysign(copysign(x,z), y) -> copysign(x, y)
8534 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8535 N0.getOpcode() == ISD::FCOPYSIGN)
8536 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8537 N0.getOperand(0), N1);
8539 // copysign(x, abs(y)) -> abs(x)
8540 if (N1.getOpcode() == ISD::FABS)
8541 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8543 // copysign(x, copysign(y,z)) -> copysign(x, z)
8544 if (N1.getOpcode() == ISD::FCOPYSIGN)
8545 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8546 N0, N1.getOperand(1));
8548 // copysign(x, fp_extend(y)) -> copysign(x, y)
8549 // copysign(x, fp_round(y)) -> copysign(x, y)
8550 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8551 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8552 N0, N1.getOperand(0));
8557 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8558 SDValue N0 = N->getOperand(0);
8559 EVT VT = N->getValueType(0);
8560 EVT OpVT = N0.getValueType();
8562 // fold (sint_to_fp c1) -> c1fp
8563 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8564 // ...but only if the target supports immediate floating-point values
8565 (!LegalOperations ||
8566 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8567 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8569 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8570 // but UINT_TO_FP is legal on this target, try to convert.
8571 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8572 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8573 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8574 if (DAG.SignBitIsZero(N0))
8575 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8578 // The next optimizations are desirable only if SELECT_CC can be lowered.
8579 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8580 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8581 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8583 (!LegalOperations ||
8584 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8587 { N0.getOperand(0), N0.getOperand(1),
8588 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8590 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8593 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8594 // (select_cc x, y, 1.0, 0.0,, cc)
8595 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8596 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8597 (!LegalOperations ||
8598 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8601 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8602 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8603 N0.getOperand(0).getOperand(2) };
8604 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8611 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8612 SDValue N0 = N->getOperand(0);
8613 EVT VT = N->getValueType(0);
8614 EVT OpVT = N0.getValueType();
8616 // fold (uint_to_fp c1) -> c1fp
8617 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8618 // ...but only if the target supports immediate floating-point values
8619 (!LegalOperations ||
8620 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8621 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8623 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8624 // but SINT_TO_FP is legal on this target, try to convert.
8625 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8626 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8627 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8628 if (DAG.SignBitIsZero(N0))
8629 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8632 // The next optimizations are desirable only if SELECT_CC can be lowered.
8633 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8634 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8636 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8637 (!LegalOperations ||
8638 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8641 { N0.getOperand(0), N0.getOperand(1),
8642 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8644 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8651 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8652 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8653 SDValue N0 = N->getOperand(0);
8654 EVT VT = N->getValueType(0);
8656 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8659 SDValue Src = N0.getOperand(0);
8660 EVT SrcVT = Src.getValueType();
8661 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8662 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8664 // We can safely assume the conversion won't overflow the output range,
8665 // because (for example) (uint8_t)18293.f is undefined behavior.
8667 // Since we can assume the conversion won't overflow, our decision as to
8668 // whether the input will fit in the float should depend on the minimum
8669 // of the input range and output range.
8671 // This means this is also safe for a signed input and unsigned output, since
8672 // a negative input would lead to undefined behavior.
8673 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8674 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8675 unsigned ActualSize = std::min(InputSize, OutputSize);
8676 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8678 // We can only fold away the float conversion if the input range can be
8679 // represented exactly in the float range.
8680 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8681 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8682 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8684 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8686 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8687 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8690 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8695 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8696 SDValue N0 = N->getOperand(0);
8697 EVT VT = N->getValueType(0);
8699 // fold (fp_to_sint c1fp) -> c1
8700 if (isConstantFPBuildVectorOrConstantFP(N0))
8701 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8703 return FoldIntToFPToInt(N, DAG);
8706 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8707 SDValue N0 = N->getOperand(0);
8708 EVT VT = N->getValueType(0);
8710 // fold (fp_to_uint c1fp) -> c1
8711 if (isConstantFPBuildVectorOrConstantFP(N0))
8712 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8714 return FoldIntToFPToInt(N, DAG);
8717 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8718 SDValue N0 = N->getOperand(0);
8719 SDValue N1 = N->getOperand(1);
8720 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8721 EVT VT = N->getValueType(0);
8723 // fold (fp_round c1fp) -> c1fp
8725 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8727 // fold (fp_round (fp_extend x)) -> x
8728 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8729 return N0.getOperand(0);
8731 // fold (fp_round (fp_round x)) -> (fp_round x)
8732 if (N0.getOpcode() == ISD::FP_ROUND) {
8733 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8734 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8735 // If the first fp_round isn't a value preserving truncation, it might
8736 // introduce a tie in the second fp_round, that wouldn't occur in the
8737 // single-step fp_round we want to fold to.
8738 // In other words, double rounding isn't the same as rounding.
8739 // Also, this is a value preserving truncation iff both fp_round's are.
8740 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8742 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8743 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8747 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8748 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8749 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8750 N0.getOperand(0), N1);
8751 AddToWorklist(Tmp.getNode());
8752 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8753 Tmp, N0.getOperand(1));
8759 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8760 SDValue N0 = N->getOperand(0);
8761 EVT VT = N->getValueType(0);
8762 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8763 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8765 // fold (fp_round_inreg c1fp) -> c1fp
8766 if (N0CFP && isTypeLegal(EVT)) {
8768 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8769 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8775 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8776 SDValue N0 = N->getOperand(0);
8777 EVT VT = N->getValueType(0);
8779 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8780 if (N->hasOneUse() &&
8781 N->use_begin()->getOpcode() == ISD::FP_ROUND)
8784 // fold (fp_extend c1fp) -> c1fp
8785 if (isConstantFPBuildVectorOrConstantFP(N0))
8786 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8788 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8789 if (N0.getOpcode() == ISD::FP16_TO_FP &&
8790 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8791 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8793 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8795 if (N0.getOpcode() == ISD::FP_ROUND
8796 && N0.getNode()->getConstantOperandVal(1) == 1) {
8797 SDValue In = N0.getOperand(0);
8798 if (In.getValueType() == VT) return In;
8799 if (VT.bitsLT(In.getValueType()))
8800 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8801 In, N0.getOperand(1));
8802 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8805 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8806 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8807 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8808 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8809 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8811 LN0->getBasePtr(), N0.getValueType(),
8812 LN0->getMemOperand());
8813 CombineTo(N, ExtLoad);
8814 CombineTo(N0.getNode(),
8815 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8816 N0.getValueType(), ExtLoad,
8817 DAG.getIntPtrConstant(1, SDLoc(N0))),
8818 ExtLoad.getValue(1));
8819 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8825 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8826 SDValue N0 = N->getOperand(0);
8827 EVT VT = N->getValueType(0);
8829 // fold (fceil c1) -> fceil(c1)
8830 if (isConstantFPBuildVectorOrConstantFP(N0))
8831 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8836 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8837 SDValue N0 = N->getOperand(0);
8838 EVT VT = N->getValueType(0);
8840 // fold (ftrunc c1) -> ftrunc(c1)
8841 if (isConstantFPBuildVectorOrConstantFP(N0))
8842 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8847 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8848 SDValue N0 = N->getOperand(0);
8849 EVT VT = N->getValueType(0);
8851 // fold (ffloor c1) -> ffloor(c1)
8852 if (isConstantFPBuildVectorOrConstantFP(N0))
8853 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8858 // FIXME: FNEG and FABS have a lot in common; refactor.
8859 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8860 SDValue N0 = N->getOperand(0);
8861 EVT VT = N->getValueType(0);
8863 // Constant fold FNEG.
8864 if (isConstantFPBuildVectorOrConstantFP(N0))
8865 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8867 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8868 &DAG.getTarget().Options))
8869 return GetNegatedExpression(N0, DAG, LegalOperations);
8871 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8872 // constant pool values.
8873 if (!TLI.isFNegFree(VT) &&
8874 N0.getOpcode() == ISD::BITCAST &&
8875 N0.getNode()->hasOneUse()) {
8876 SDValue Int = N0.getOperand(0);
8877 EVT IntVT = Int.getValueType();
8878 if (IntVT.isInteger() && !IntVT.isVector()) {
8880 if (N0.getValueType().isVector()) {
8881 // For a vector, get a mask such as 0x80... per scalar element
8883 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8884 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8886 // For a scalar, just generate 0x80...
8887 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8890 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8891 DAG.getConstant(SignMask, DL0, IntVT));
8892 AddToWorklist(Int.getNode());
8893 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8897 // (fneg (fmul c, x)) -> (fmul -c, x)
8898 if (N0.getOpcode() == ISD::FMUL &&
8899 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
8900 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8902 APFloat CVal = CFP1->getValueAPF();
8904 if (Level >= AfterLegalizeDAG &&
8905 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8906 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8908 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8909 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8916 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8917 SDValue N0 = N->getOperand(0);
8918 SDValue N1 = N->getOperand(1);
8919 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8920 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8922 if (N0CFP && N1CFP) {
8923 const APFloat &C0 = N0CFP->getValueAPF();
8924 const APFloat &C1 = N1CFP->getValueAPF();
8925 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8929 EVT VT = N->getValueType(0);
8930 // Canonicalize to constant on RHS.
8931 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8937 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8938 SDValue N0 = N->getOperand(0);
8939 SDValue N1 = N->getOperand(1);
8940 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8941 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8943 if (N0CFP && N1CFP) {
8944 const APFloat &C0 = N0CFP->getValueAPF();
8945 const APFloat &C1 = N1CFP->getValueAPF();
8946 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8950 EVT VT = N->getValueType(0);
8951 // Canonicalize to constant on RHS.
8952 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8958 SDValue DAGCombiner::visitFABS(SDNode *N) {
8959 SDValue N0 = N->getOperand(0);
8960 EVT VT = N->getValueType(0);
8962 // fold (fabs c1) -> fabs(c1)
8963 if (isConstantFPBuildVectorOrConstantFP(N0))
8964 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8966 // fold (fabs (fabs x)) -> (fabs x)
8967 if (N0.getOpcode() == ISD::FABS)
8968 return N->getOperand(0);
8970 // fold (fabs (fneg x)) -> (fabs x)
8971 // fold (fabs (fcopysign x, y)) -> (fabs x)
8972 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8973 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8975 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8976 // constant pool values.
8977 if (!TLI.isFAbsFree(VT) &&
8978 N0.getOpcode() == ISD::BITCAST &&
8979 N0.getNode()->hasOneUse()) {
8980 SDValue Int = N0.getOperand(0);
8981 EVT IntVT = Int.getValueType();
8982 if (IntVT.isInteger() && !IntVT.isVector()) {
8984 if (N0.getValueType().isVector()) {
8985 // For a vector, get a mask such as 0x7f... per scalar element
8987 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8988 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8990 // For a scalar, just generate 0x7f...
8991 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8994 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8995 DAG.getConstant(SignMask, DL, IntVT));
8996 AddToWorklist(Int.getNode());
8997 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
9004 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9005 SDValue Chain = N->getOperand(0);
9006 SDValue N1 = N->getOperand(1);
9007 SDValue N2 = N->getOperand(2);
9009 // If N is a constant we could fold this into a fallthrough or unconditional
9010 // branch. However that doesn't happen very often in normal code, because
9011 // Instcombine/SimplifyCFG should have handled the available opportunities.
9012 // If we did this folding here, it would be necessary to update the
9013 // MachineBasicBlock CFG, which is awkward.
9015 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9017 if (N1.getOpcode() == ISD::SETCC &&
9018 TLI.isOperationLegalOrCustom(ISD::BR_CC,
9019 N1.getOperand(0).getValueType())) {
9020 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9021 Chain, N1.getOperand(2),
9022 N1.getOperand(0), N1.getOperand(1), N2);
9025 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9026 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9027 (N1.getOperand(0).hasOneUse() &&
9028 N1.getOperand(0).getOpcode() == ISD::SRL))) {
9029 SDNode *Trunc = nullptr;
9030 if (N1.getOpcode() == ISD::TRUNCATE) {
9031 // Look pass the truncate.
9032 Trunc = N1.getNode();
9033 N1 = N1.getOperand(0);
9036 // Match this pattern so that we can generate simpler code:
9039 // %b = and i32 %a, 2
9040 // %c = srl i32 %b, 1
9041 // brcond i32 %c ...
9046 // %b = and i32 %a, 2
9047 // %c = setcc eq %b, 0
9050 // This applies only when the AND constant value has one bit set and the
9051 // SRL constant is equal to the log2 of the AND constant. The back-end is
9052 // smart enough to convert the result into a TEST/JMP sequence.
9053 SDValue Op0 = N1.getOperand(0);
9054 SDValue Op1 = N1.getOperand(1);
9056 if (Op0.getOpcode() == ISD::AND &&
9057 Op1.getOpcode() == ISD::Constant) {
9058 SDValue AndOp1 = Op0.getOperand(1);
9060 if (AndOp1.getOpcode() == ISD::Constant) {
9061 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9063 if (AndConst.isPowerOf2() &&
9064 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9068 getSetCCResultType(Op0.getValueType()),
9069 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9072 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9073 MVT::Other, Chain, SetCC, N2);
9074 // Don't add the new BRCond into the worklist or else SimplifySelectCC
9075 // will convert it back to (X & C1) >> C2.
9076 CombineTo(N, NewBRCond, false);
9077 // Truncate is dead.
9079 deleteAndRecombine(Trunc);
9080 // Replace the uses of SRL with SETCC
9081 WorklistRemover DeadNodes(*this);
9082 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9083 deleteAndRecombine(N1.getNode());
9084 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9090 // Restore N1 if the above transformation doesn't match.
9091 N1 = N->getOperand(1);
9094 // Transform br(xor(x, y)) -> br(x != y)
9095 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9096 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9097 SDNode *TheXor = N1.getNode();
9098 SDValue Op0 = TheXor->getOperand(0);
9099 SDValue Op1 = TheXor->getOperand(1);
9100 if (Op0.getOpcode() == Op1.getOpcode()) {
9101 // Avoid missing important xor optimizations.
9102 if (SDValue Tmp = visitXOR(TheXor)) {
9103 if (Tmp.getNode() != TheXor) {
9104 DEBUG(dbgs() << "\nReplacing.8 ";
9106 dbgs() << "\nWith: ";
9107 Tmp.getNode()->dump(&DAG);
9109 WorklistRemover DeadNodes(*this);
9110 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9111 deleteAndRecombine(TheXor);
9112 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9113 MVT::Other, Chain, Tmp, N2);
9116 // visitXOR has changed XOR's operands or replaced the XOR completely,
9118 return SDValue(N, 0);
9122 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9124 if (isOneConstant(Op0) && Op0.hasOneUse() &&
9125 Op0.getOpcode() == ISD::XOR) {
9126 TheXor = Op0.getNode();
9130 EVT SetCCVT = N1.getValueType();
9132 SetCCVT = getSetCCResultType(SetCCVT);
9133 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9136 Equal ? ISD::SETEQ : ISD::SETNE);
9137 // Replace the uses of XOR with SETCC
9138 WorklistRemover DeadNodes(*this);
9139 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9140 deleteAndRecombine(N1.getNode());
9141 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9142 MVT::Other, Chain, SetCC, N2);
9149 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9151 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9152 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9153 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9155 // If N is a constant we could fold this into a fallthrough or unconditional
9156 // branch. However that doesn't happen very often in normal code, because
9157 // Instcombine/SimplifyCFG should have handled the available opportunities.
9158 // If we did this folding here, it would be necessary to update the
9159 // MachineBasicBlock CFG, which is awkward.
9161 // Use SimplifySetCC to simplify SETCC's.
9162 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9163 CondLHS, CondRHS, CC->get(), SDLoc(N),
9165 if (Simp.getNode()) AddToWorklist(Simp.getNode());
9167 // fold to a simpler setcc
9168 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9169 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9170 N->getOperand(0), Simp.getOperand(2),
9171 Simp.getOperand(0), Simp.getOperand(1),
9177 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9178 /// and that N may be folded in the load / store addressing mode.
9179 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9181 const TargetLowering &TLI) {
9185 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
9186 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9188 VT = LD->getMemoryVT();
9189 AS = LD->getAddressSpace();
9190 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
9191 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9193 VT = ST->getMemoryVT();
9194 AS = ST->getAddressSpace();
9198 TargetLowering::AddrMode AM;
9199 if (N->getOpcode() == ISD::ADD) {
9200 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9203 AM.BaseOffs = Offset->getSExtValue();
9207 } else if (N->getOpcode() == ISD::SUB) {
9208 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9211 AM.BaseOffs = -Offset->getSExtValue();
9218 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9219 VT.getTypeForEVT(*DAG.getContext()), AS);
9222 /// Try turning a load/store into a pre-indexed load/store when the base
9223 /// pointer is an add or subtract and it has other uses besides the load/store.
9224 /// After the transformation, the new indexed load/store has effectively folded
9225 /// the add/subtract in and all of its other uses are redirected to the
9227 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9228 if (Level < AfterLegalizeDAG)
9234 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9235 if (LD->isIndexed())
9237 VT = LD->getMemoryVT();
9238 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9239 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9241 Ptr = LD->getBasePtr();
9242 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9243 if (ST->isIndexed())
9245 VT = ST->getMemoryVT();
9246 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9247 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9249 Ptr = ST->getBasePtr();
9255 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9256 // out. There is no reason to make this a preinc/predec.
9257 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9258 Ptr.getNode()->hasOneUse())
9261 // Ask the target to do addressing mode selection.
9264 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9265 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9268 // Backends without true r+i pre-indexed forms may need to pass a
9269 // constant base with a variable offset so that constant coercion
9270 // will work with the patterns in canonical form.
9271 bool Swapped = false;
9272 if (isa<ConstantSDNode>(BasePtr)) {
9273 std::swap(BasePtr, Offset);
9277 // Don't create a indexed load / store with zero offset.
9278 if (isNullConstant(Offset))
9281 // Try turning it into a pre-indexed load / store except when:
9282 // 1) The new base ptr is a frame index.
9283 // 2) If N is a store and the new base ptr is either the same as or is a
9284 // predecessor of the value being stored.
9285 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9286 // that would create a cycle.
9287 // 4) All uses are load / store ops that use it as old base ptr.
9289 // Check #1. Preinc'ing a frame index would require copying the stack pointer
9290 // (plus the implicit offset) to a register to preinc anyway.
9291 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9296 SDValue Val = cast<StoreSDNode>(N)->getValue();
9297 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9301 // If the offset is a constant, there may be other adds of constants that
9302 // can be folded with this one. We should do this to avoid having to keep
9303 // a copy of the original base pointer.
9304 SmallVector<SDNode *, 16> OtherUses;
9305 if (isa<ConstantSDNode>(Offset))
9306 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9307 UE = BasePtr.getNode()->use_end();
9309 SDUse &Use = UI.getUse();
9310 // Skip the use that is Ptr and uses of other results from BasePtr's
9311 // node (important for nodes that return multiple results).
9312 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9315 if (Use.getUser()->isPredecessorOf(N))
9318 if (Use.getUser()->getOpcode() != ISD::ADD &&
9319 Use.getUser()->getOpcode() != ISD::SUB) {
9324 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9325 if (!isa<ConstantSDNode>(Op1)) {
9330 // FIXME: In some cases, we can be smarter about this.
9331 if (Op1.getValueType() != Offset.getValueType()) {
9336 OtherUses.push_back(Use.getUser());
9340 std::swap(BasePtr, Offset);
9342 // Now check for #3 and #4.
9343 bool RealUse = false;
9345 // Caches for hasPredecessorHelper
9346 SmallPtrSet<const SDNode *, 32> Visited;
9347 SmallVector<const SDNode *, 16> Worklist;
9349 for (SDNode *Use : Ptr.getNode()->uses()) {
9352 if (N->hasPredecessorHelper(Use, Visited, Worklist))
9355 // If Ptr may be folded in addressing mode of other use, then it's
9356 // not profitable to do this transformation.
9357 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9366 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9367 BasePtr, Offset, AM);
9369 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9370 BasePtr, Offset, AM);
9373 DEBUG(dbgs() << "\nReplacing.4 ";
9375 dbgs() << "\nWith: ";
9376 Result.getNode()->dump(&DAG);
9378 WorklistRemover DeadNodes(*this);
9380 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9381 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9383 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9386 // Finally, since the node is now dead, remove it from the graph.
9387 deleteAndRecombine(N);
9390 std::swap(BasePtr, Offset);
9392 // Replace other uses of BasePtr that can be updated to use Ptr
9393 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9394 unsigned OffsetIdx = 1;
9395 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9397 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9398 BasePtr.getNode() && "Expected BasePtr operand");
9400 // We need to replace ptr0 in the following expression:
9401 // x0 * offset0 + y0 * ptr0 = t0
9403 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9405 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9406 // indexed load/store and the expresion that needs to be re-written.
9408 // Therefore, we have:
9409 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9411 ConstantSDNode *CN =
9412 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9414 APInt Offset0 = CN->getAPIntValue();
9415 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9417 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9418 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9419 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9420 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9422 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9424 APInt CNV = Offset0;
9425 if (X0 < 0) CNV = -CNV;
9426 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9427 else CNV = CNV - Offset1;
9429 SDLoc DL(OtherUses[i]);
9431 // We can now generate the new expression.
9432 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9433 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9435 SDValue NewUse = DAG.getNode(Opcode,
9437 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9438 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9439 deleteAndRecombine(OtherUses[i]);
9442 // Replace the uses of Ptr with uses of the updated base value.
9443 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9444 deleteAndRecombine(Ptr.getNode());
9449 /// Try to combine a load/store with a add/sub of the base pointer node into a
9450 /// post-indexed load/store. The transformation folded the add/subtract into the
9451 /// new indexed load/store effectively and all of its uses are redirected to the
9453 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9454 if (Level < AfterLegalizeDAG)
9460 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9461 if (LD->isIndexed())
9463 VT = LD->getMemoryVT();
9464 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9465 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9467 Ptr = LD->getBasePtr();
9468 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9469 if (ST->isIndexed())
9471 VT = ST->getMemoryVT();
9472 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9473 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9475 Ptr = ST->getBasePtr();
9481 if (Ptr.getNode()->hasOneUse())
9484 for (SDNode *Op : Ptr.getNode()->uses()) {
9486 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9491 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9492 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9493 // Don't create a indexed load / store with zero offset.
9494 if (isNullConstant(Offset))
9497 // Try turning it into a post-indexed load / store except when
9498 // 1) All uses are load / store ops that use it as base ptr (and
9499 // it may be folded as addressing mmode).
9500 // 2) Op must be independent of N, i.e. Op is neither a predecessor
9501 // nor a successor of N. Otherwise, if Op is folded that would
9504 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9508 bool TryNext = false;
9509 for (SDNode *Use : BasePtr.getNode()->uses()) {
9510 if (Use == Ptr.getNode())
9513 // If all the uses are load / store addresses, then don't do the
9515 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9516 bool RealUse = false;
9517 for (SDNode *UseUse : Use->uses()) {
9518 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9533 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9534 SDValue Result = isLoad
9535 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9536 BasePtr, Offset, AM)
9537 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9538 BasePtr, Offset, AM);
9541 DEBUG(dbgs() << "\nReplacing.5 ";
9543 dbgs() << "\nWith: ";
9544 Result.getNode()->dump(&DAG);
9546 WorklistRemover DeadNodes(*this);
9548 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9549 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9551 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9554 // Finally, since the node is now dead, remove it from the graph.
9555 deleteAndRecombine(N);
9557 // Replace the uses of Use with uses of the updated base value.
9558 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9559 Result.getValue(isLoad ? 1 : 0));
9560 deleteAndRecombine(Op);
9569 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9570 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9571 ISD::MemIndexedMode AM = LD->getAddressingMode();
9572 assert(AM != ISD::UNINDEXED);
9573 SDValue BP = LD->getOperand(1);
9574 SDValue Inc = LD->getOperand(2);
9576 // Some backends use TargetConstants for load offsets, but don't expect
9577 // TargetConstants in general ADD nodes. We can convert these constants into
9578 // regular Constants (if the constant is not opaque).
9579 assert((Inc.getOpcode() != ISD::TargetConstant ||
9580 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9581 "Cannot split out indexing using opaque target constants");
9582 if (Inc.getOpcode() == ISD::TargetConstant) {
9583 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9584 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9585 ConstInc->getValueType(0));
9589 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9590 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9593 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9594 LoadSDNode *LD = cast<LoadSDNode>(N);
9595 SDValue Chain = LD->getChain();
9596 SDValue Ptr = LD->getBasePtr();
9598 // If load is not volatile and there are no uses of the loaded value (and
9599 // the updated indexed value in case of indexed loads), change uses of the
9600 // chain value into uses of the chain input (i.e. delete the dead load).
9601 if (!LD->isVolatile()) {
9602 if (N->getValueType(1) == MVT::Other) {
9604 if (!N->hasAnyUseOfValue(0)) {
9605 // It's not safe to use the two value CombineTo variant here. e.g.
9606 // v1, chain2 = load chain1, loc
9607 // v2, chain3 = load chain2, loc
9609 // Now we replace use of chain2 with chain1. This makes the second load
9610 // isomorphic to the one we are deleting, and thus makes this load live.
9611 DEBUG(dbgs() << "\nReplacing.6 ";
9613 dbgs() << "\nWith chain: ";
9614 Chain.getNode()->dump(&DAG);
9616 WorklistRemover DeadNodes(*this);
9617 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9620 deleteAndRecombine(N);
9622 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9626 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9628 // If this load has an opaque TargetConstant offset, then we cannot split
9629 // the indexing into an add/sub directly (that TargetConstant may not be
9630 // valid for a different type of node, and we cannot convert an opaque
9631 // target constant into a regular constant).
9632 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9633 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9635 if (!N->hasAnyUseOfValue(0) &&
9636 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9637 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9639 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9640 Index = SplitIndexingFromLoad(LD);
9641 // Try to fold the base pointer arithmetic into subsequent loads and
9643 AddUsersToWorklist(N);
9645 Index = DAG.getUNDEF(N->getValueType(1));
9646 DEBUG(dbgs() << "\nReplacing.7 ";
9648 dbgs() << "\nWith: ";
9649 Undef.getNode()->dump(&DAG);
9650 dbgs() << " and 2 other values\n");
9651 WorklistRemover DeadNodes(*this);
9652 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9653 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9654 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9655 deleteAndRecombine(N);
9656 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9661 // If this load is directly stored, replace the load value with the stored
9663 // TODO: Handle store large -> read small portion.
9664 // TODO: Handle TRUNCSTORE/LOADEXT
9665 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9666 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9667 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9668 if (PrevST->getBasePtr() == Ptr &&
9669 PrevST->getValue().getValueType() == N->getValueType(0))
9670 return CombineTo(N, Chain.getOperand(1), Chain);
9674 // Try to infer better alignment information than the load already has.
9675 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9676 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9677 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9679 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9680 LD->getValueType(0),
9681 Chain, Ptr, LD->getPointerInfo(),
9683 LD->isVolatile(), LD->isNonTemporal(),
9684 LD->isInvariant(), Align, LD->getAAInfo());
9685 if (NewLoad.getNode() != N)
9686 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9691 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9692 : DAG.getSubtarget().useAA();
9694 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9695 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9698 if (UseAA && LD->isUnindexed()) {
9699 // Walk up chain skipping non-aliasing memory nodes.
9700 SDValue BetterChain = FindBetterChain(N, Chain);
9702 // If there is a better chain.
9703 if (Chain != BetterChain) {
9706 // Replace the chain to void dependency.
9707 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9708 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9709 BetterChain, Ptr, LD->getMemOperand());
9711 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9712 LD->getValueType(0),
9713 BetterChain, Ptr, LD->getMemoryVT(),
9714 LD->getMemOperand());
9717 // Create token factor to keep old chain connected.
9718 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9719 MVT::Other, Chain, ReplLoad.getValue(1));
9721 // Make sure the new and old chains are cleaned up.
9722 AddToWorklist(Token.getNode());
9724 // Replace uses with load result and token factor. Don't add users
9726 return CombineTo(N, ReplLoad.getValue(0), Token, false);
9730 // Try transforming N to an indexed load.
9731 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9732 return SDValue(N, 0);
9734 // Try to slice up N to more direct loads if the slices are mapped to
9735 // different register banks or pairing can take place.
9737 return SDValue(N, 0);
9743 /// \brief Helper structure used to slice a load in smaller loads.
9744 /// Basically a slice is obtained from the following sequence:
9745 /// Origin = load Ty1, Base
9746 /// Shift = srl Ty1 Origin, CstTy Amount
9747 /// Inst = trunc Shift to Ty2
9749 /// Then, it will be rewriten into:
9750 /// Slice = load SliceTy, Base + SliceOffset
9751 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9753 /// SliceTy is deduced from the number of bits that are actually used to
9755 struct LoadedSlice {
9756 /// \brief Helper structure used to compute the cost of a slice.
9758 /// Are we optimizing for code size.
9763 unsigned CrossRegisterBanksCopies;
9767 Cost(bool ForCodeSize = false)
9768 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9769 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9771 /// \brief Get the cost of one isolated slice.
9772 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9773 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9774 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9775 EVT TruncType = LS.Inst->getValueType(0);
9776 EVT LoadedType = LS.getLoadedType();
9777 if (TruncType != LoadedType &&
9778 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9782 /// \brief Account for slicing gain in the current cost.
9783 /// Slicing provide a few gains like removing a shift or a
9784 /// truncate. This method allows to grow the cost of the original
9785 /// load with the gain from this slice.
9786 void addSliceGain(const LoadedSlice &LS) {
9787 // Each slice saves a truncate.
9788 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9789 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
9790 LS.Inst->getValueType(0)))
9792 // If there is a shift amount, this slice gets rid of it.
9795 // If this slice can merge a cross register bank copy, account for it.
9796 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9797 ++CrossRegisterBanksCopies;
9800 Cost &operator+=(const Cost &RHS) {
9802 Truncates += RHS.Truncates;
9803 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9809 bool operator==(const Cost &RHS) const {
9810 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9811 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9812 ZExts == RHS.ZExts && Shift == RHS.Shift;
9815 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9817 bool operator<(const Cost &RHS) const {
9818 // Assume cross register banks copies are as expensive as loads.
9819 // FIXME: Do we want some more target hooks?
9820 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9821 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9822 // Unless we are optimizing for code size, consider the
9823 // expensive operation first.
9824 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9825 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9826 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9827 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9830 bool operator>(const Cost &RHS) const { return RHS < *this; }
9832 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9834 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9836 // The last instruction that represent the slice. This should be a
9837 // truncate instruction.
9839 // The original load instruction.
9841 // The right shift amount in bits from the original load.
9843 // The DAG from which Origin came from.
9844 // This is used to get some contextual information about legal types, etc.
9847 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9848 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9849 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9851 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9852 /// \return Result is \p BitWidth and has used bits set to 1 and
9853 /// not used bits set to 0.
9854 APInt getUsedBits() const {
9855 // Reproduce the trunc(lshr) sequence:
9856 // - Start from the truncated value.
9857 // - Zero extend to the desired bit width.
9859 assert(Origin && "No original load to compare against.");
9860 unsigned BitWidth = Origin->getValueSizeInBits(0);
9861 assert(Inst && "This slice is not bound to an instruction");
9862 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9863 "Extracted slice is bigger than the whole type!");
9864 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9865 UsedBits.setAllBits();
9866 UsedBits = UsedBits.zext(BitWidth);
9871 /// \brief Get the size of the slice to be loaded in bytes.
9872 unsigned getLoadedSize() const {
9873 unsigned SliceSize = getUsedBits().countPopulation();
9874 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9875 return SliceSize / 8;
9878 /// \brief Get the type that will be loaded for this slice.
9879 /// Note: This may not be the final type for the slice.
9880 EVT getLoadedType() const {
9881 assert(DAG && "Missing context");
9882 LLVMContext &Ctxt = *DAG->getContext();
9883 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9886 /// \brief Get the alignment of the load used for this slice.
9887 unsigned getAlignment() const {
9888 unsigned Alignment = Origin->getAlignment();
9889 unsigned Offset = getOffsetFromBase();
9891 Alignment = MinAlign(Alignment, Alignment + Offset);
9895 /// \brief Check if this slice can be rewritten with legal operations.
9896 bool isLegal() const {
9897 // An invalid slice is not legal.
9898 if (!Origin || !Inst || !DAG)
9901 // Offsets are for indexed load only, we do not handle that.
9902 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9905 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9907 // Check that the type is legal.
9908 EVT SliceType = getLoadedType();
9909 if (!TLI.isTypeLegal(SliceType))
9912 // Check that the load is legal for this type.
9913 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9916 // Check that the offset can be computed.
9917 // 1. Check its type.
9918 EVT PtrType = Origin->getBasePtr().getValueType();
9919 if (PtrType == MVT::Untyped || PtrType.isExtended())
9922 // 2. Check that it fits in the immediate.
9923 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9926 // 3. Check that the computation is legal.
9927 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9930 // Check that the zext is legal if it needs one.
9931 EVT TruncateType = Inst->getValueType(0);
9932 if (TruncateType != SliceType &&
9933 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9939 /// \brief Get the offset in bytes of this slice in the original chunk of
9941 /// \pre DAG != nullptr.
9942 uint64_t getOffsetFromBase() const {
9943 assert(DAG && "Missing context.");
9944 bool IsBigEndian = DAG->getDataLayout().isBigEndian();
9945 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9946 uint64_t Offset = Shift / 8;
9947 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9948 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9949 "The size of the original loaded type is not a multiple of a"
9951 // If Offset is bigger than TySizeInBytes, it means we are loading all
9952 // zeros. This should have been optimized before in the process.
9953 assert(TySizeInBytes > Offset &&
9954 "Invalid shift amount for given loaded size");
9956 Offset = TySizeInBytes - Offset - getLoadedSize();
9960 /// \brief Generate the sequence of instructions to load the slice
9961 /// represented by this object and redirect the uses of this slice to
9962 /// this new sequence of instructions.
9963 /// \pre this->Inst && this->Origin are valid Instructions and this
9964 /// object passed the legal check: LoadedSlice::isLegal returned true.
9965 /// \return The last instruction of the sequence used to load the slice.
9966 SDValue loadSlice() const {
9967 assert(Inst && Origin && "Unable to replace a non-existing slice.");
9968 const SDValue &OldBaseAddr = Origin->getBasePtr();
9969 SDValue BaseAddr = OldBaseAddr;
9970 // Get the offset in that chunk of bytes w.r.t. the endianess.
9971 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9972 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9974 // BaseAddr = BaseAddr + Offset.
9975 EVT ArithType = BaseAddr.getValueType();
9977 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9978 DAG->getConstant(Offset, DL, ArithType));
9981 // Create the type of the loaded slice according to its size.
9982 EVT SliceType = getLoadedType();
9984 // Create the load for the slice.
9985 SDValue LastInst = DAG->getLoad(
9986 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9987 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9988 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9989 // If the final type is not the same as the loaded type, this means that
9990 // we have to pad with zero. Create a zero extend for that.
9991 EVT FinalType = Inst->getValueType(0);
9992 if (SliceType != FinalType)
9994 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9998 /// \brief Check if this slice can be merged with an expensive cross register
9999 /// bank copy. E.g.,
10001 /// f = bitcast i32 i to float
10002 bool canMergeExpensiveCrossRegisterBankCopy() const {
10003 if (!Inst || !Inst->hasOneUse())
10005 SDNode *Use = *Inst->use_begin();
10006 if (Use->getOpcode() != ISD::BITCAST)
10008 assert(DAG && "Missing context");
10009 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10010 EVT ResVT = Use->getValueType(0);
10011 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10012 const TargetRegisterClass *ArgRC =
10013 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10014 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10017 // At this point, we know that we perform a cross-register-bank copy.
10018 // Check if it is expensive.
10019 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10020 // Assume bitcasts are cheap, unless both register classes do not
10021 // explicitly share a common sub class.
10022 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10025 // Check if it will be merged with the load.
10026 // 1. Check the alignment constraint.
10027 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10028 ResVT.getTypeForEVT(*DAG->getContext()));
10030 if (RequiredAlignment > getAlignment())
10033 // 2. Check that the load is a legal operation for that type.
10034 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10037 // 3. Check that we do not have a zext in the way.
10038 if (Inst->getValueType(0) != getLoadedType())
10046 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10047 /// \p UsedBits looks like 0..0 1..1 0..0.
10048 static bool areUsedBitsDense(const APInt &UsedBits) {
10049 // If all the bits are one, this is dense!
10050 if (UsedBits.isAllOnesValue())
10053 // Get rid of the unused bits on the right.
10054 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10055 // Get rid of the unused bits on the left.
10056 if (NarrowedUsedBits.countLeadingZeros())
10057 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10058 // Check that the chunk of bits is completely used.
10059 return NarrowedUsedBits.isAllOnesValue();
10062 /// \brief Check whether or not \p First and \p Second are next to each other
10063 /// in memory. This means that there is no hole between the bits loaded
10064 /// by \p First and the bits loaded by \p Second.
10065 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10066 const LoadedSlice &Second) {
10067 assert(First.Origin == Second.Origin && First.Origin &&
10068 "Unable to match different memory origins.");
10069 APInt UsedBits = First.getUsedBits();
10070 assert((UsedBits & Second.getUsedBits()) == 0 &&
10071 "Slices are not supposed to overlap.");
10072 UsedBits |= Second.getUsedBits();
10073 return areUsedBitsDense(UsedBits);
10076 /// \brief Adjust the \p GlobalLSCost according to the target
10077 /// paring capabilities and the layout of the slices.
10078 /// \pre \p GlobalLSCost should account for at least as many loads as
10079 /// there is in the slices in \p LoadedSlices.
10080 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10081 LoadedSlice::Cost &GlobalLSCost) {
10082 unsigned NumberOfSlices = LoadedSlices.size();
10083 // If there is less than 2 elements, no pairing is possible.
10084 if (NumberOfSlices < 2)
10087 // Sort the slices so that elements that are likely to be next to each
10088 // other in memory are next to each other in the list.
10089 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10090 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10091 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10092 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10094 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10095 // First (resp. Second) is the first (resp. Second) potentially candidate
10096 // to be placed in a paired load.
10097 const LoadedSlice *First = nullptr;
10098 const LoadedSlice *Second = nullptr;
10099 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10100 // Set the beginning of the pair.
10103 Second = &LoadedSlices[CurrSlice];
10105 // If First is NULL, it means we start a new pair.
10106 // Get to the next slice.
10110 EVT LoadedType = First->getLoadedType();
10112 // If the types of the slices are different, we cannot pair them.
10113 if (LoadedType != Second->getLoadedType())
10116 // Check if the target supplies paired loads for this type.
10117 unsigned RequiredAlignment = 0;
10118 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10119 // move to the next pair, this type is hopeless.
10123 // Check if we meet the alignment requirement.
10124 if (RequiredAlignment > First->getAlignment())
10127 // Check that both loads are next to each other in memory.
10128 if (!areSlicesNextToEachOther(*First, *Second))
10131 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10132 --GlobalLSCost.Loads;
10133 // Move to the next pair.
10138 /// \brief Check the profitability of all involved LoadedSlice.
10139 /// Currently, it is considered profitable if there is exactly two
10140 /// involved slices (1) which are (2) next to each other in memory, and
10141 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10143 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10144 /// the elements themselves.
10146 /// FIXME: When the cost model will be mature enough, we can relax
10147 /// constraints (1) and (2).
10148 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10149 const APInt &UsedBits, bool ForCodeSize) {
10150 unsigned NumberOfSlices = LoadedSlices.size();
10151 if (StressLoadSlicing)
10152 return NumberOfSlices > 1;
10155 if (NumberOfSlices != 2)
10159 if (!areUsedBitsDense(UsedBits))
10163 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10164 // The original code has one big load.
10165 OrigCost.Loads = 1;
10166 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10167 const LoadedSlice &LS = LoadedSlices[CurrSlice];
10168 // Accumulate the cost of all the slices.
10169 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10170 GlobalSlicingCost += SliceCost;
10172 // Account as cost in the original configuration the gain obtained
10173 // with the current slices.
10174 OrigCost.addSliceGain(LS);
10177 // If the target supports paired load, adjust the cost accordingly.
10178 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10179 return OrigCost > GlobalSlicingCost;
10182 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10183 /// operations, split it in the various pieces being extracted.
10185 /// This sort of thing is introduced by SROA.
10186 /// This slicing takes care not to insert overlapping loads.
10187 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10188 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10189 if (Level < AfterLegalizeDAG)
10192 LoadSDNode *LD = cast<LoadSDNode>(N);
10193 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10194 !LD->getValueType(0).isInteger())
10197 // Keep track of already used bits to detect overlapping values.
10198 // In that case, we will just abort the transformation.
10199 APInt UsedBits(LD->getValueSizeInBits(0), 0);
10201 SmallVector<LoadedSlice, 4> LoadedSlices;
10203 // Check if this load is used as several smaller chunks of bits.
10204 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10205 // of computation for each trunc.
10206 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10207 UI != UIEnd; ++UI) {
10208 // Skip the uses of the chain.
10209 if (UI.getUse().getResNo() != 0)
10212 SDNode *User = *UI;
10213 unsigned Shift = 0;
10215 // Check if this is a trunc(lshr).
10216 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10217 isa<ConstantSDNode>(User->getOperand(1))) {
10218 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10219 User = *User->use_begin();
10222 // At this point, User is a Truncate, iff we encountered, trunc or
10224 if (User->getOpcode() != ISD::TRUNCATE)
10227 // The width of the type must be a power of 2 and greater than 8-bits.
10228 // Otherwise the load cannot be represented in LLVM IR.
10229 // Moreover, if we shifted with a non-8-bits multiple, the slice
10230 // will be across several bytes. We do not support that.
10231 unsigned Width = User->getValueSizeInBits(0);
10232 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10235 // Build the slice for this chain of computations.
10236 LoadedSlice LS(User, LD, Shift, &DAG);
10237 APInt CurrentUsedBits = LS.getUsedBits();
10239 // Check if this slice overlaps with another.
10240 if ((CurrentUsedBits & UsedBits) != 0)
10242 // Update the bits used globally.
10243 UsedBits |= CurrentUsedBits;
10245 // Check if the new slice would be legal.
10249 // Record the slice.
10250 LoadedSlices.push_back(LS);
10253 // Abort slicing if it does not seem to be profitable.
10254 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10259 // Rewrite each chain to use an independent load.
10260 // By construction, each chain can be represented by a unique load.
10262 // Prepare the argument for the new token factor for all the slices.
10263 SmallVector<SDValue, 8> ArgChains;
10264 for (SmallVectorImpl<LoadedSlice>::const_iterator
10265 LSIt = LoadedSlices.begin(),
10266 LSItEnd = LoadedSlices.end();
10267 LSIt != LSItEnd; ++LSIt) {
10268 SDValue SliceInst = LSIt->loadSlice();
10269 CombineTo(LSIt->Inst, SliceInst, true);
10270 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10271 SliceInst = SliceInst.getOperand(0);
10272 assert(SliceInst->getOpcode() == ISD::LOAD &&
10273 "It takes more than a zext to get to the loaded slice!!");
10274 ArgChains.push_back(SliceInst.getValue(1));
10277 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10279 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10283 /// Check to see if V is (and load (ptr), imm), where the load is having
10284 /// specific bytes cleared out. If so, return the byte size being masked out
10285 /// and the shift amount.
10286 static std::pair<unsigned, unsigned>
10287 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10288 std::pair<unsigned, unsigned> Result(0, 0);
10290 // Check for the structure we're looking for.
10291 if (V->getOpcode() != ISD::AND ||
10292 !isa<ConstantSDNode>(V->getOperand(1)) ||
10293 !ISD::isNormalLoad(V->getOperand(0).getNode()))
10296 // Check the chain and pointer.
10297 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10298 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
10300 // The store should be chained directly to the load or be an operand of a
10302 if (LD == Chain.getNode())
10304 else if (Chain->getOpcode() != ISD::TokenFactor)
10305 return Result; // Fail.
10308 for (const SDValue &ChainOp : Chain->op_values())
10309 if (ChainOp.getNode() == LD) {
10313 if (!isOk) return Result;
10316 // This only handles simple types.
10317 if (V.getValueType() != MVT::i16 &&
10318 V.getValueType() != MVT::i32 &&
10319 V.getValueType() != MVT::i64)
10322 // Check the constant mask. Invert it so that the bits being masked out are
10323 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
10324 // follow the sign bit for uniformity.
10325 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10326 unsigned NotMaskLZ = countLeadingZeros(NotMask);
10327 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
10328 unsigned NotMaskTZ = countTrailingZeros(NotMask);
10329 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
10330 if (NotMaskLZ == 64) return Result; // All zero mask.
10332 // See if we have a continuous run of bits. If so, we have 0*1+0*
10333 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10336 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10337 if (V.getValueType() != MVT::i64 && NotMaskLZ)
10338 NotMaskLZ -= 64-V.getValueSizeInBits();
10340 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10341 switch (MaskedBytes) {
10345 default: return Result; // All one mask, or 5-byte mask.
10348 // Verify that the first bit starts at a multiple of mask so that the access
10349 // is aligned the same as the access width.
10350 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10352 Result.first = MaskedBytes;
10353 Result.second = NotMaskTZ/8;
10358 /// Check to see if IVal is something that provides a value as specified by
10359 /// MaskInfo. If so, replace the specified store with a narrower store of
10360 /// truncated IVal.
10362 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10363 SDValue IVal, StoreSDNode *St,
10365 unsigned NumBytes = MaskInfo.first;
10366 unsigned ByteShift = MaskInfo.second;
10367 SelectionDAG &DAG = DC->getDAG();
10369 // Check to see if IVal is all zeros in the part being masked in by the 'or'
10370 // that uses this. If not, this is not a replacement.
10371 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10372 ByteShift*8, (ByteShift+NumBytes)*8);
10373 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10375 // Check that it is legal on the target to do this. It is legal if the new
10376 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10378 MVT VT = MVT::getIntegerVT(NumBytes*8);
10379 if (!DC->isTypeLegal(VT))
10382 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
10383 // shifted by ByteShift and truncated down to NumBytes.
10386 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10387 DAG.getConstant(ByteShift*8, DL,
10388 DC->getShiftAmountTy(IVal.getValueType())));
10391 // Figure out the offset for the store and the alignment of the access.
10393 unsigned NewAlign = St->getAlignment();
10395 if (DAG.getDataLayout().isLittleEndian())
10396 StOffset = ByteShift;
10398 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10400 SDValue Ptr = St->getBasePtr();
10403 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10404 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10405 NewAlign = MinAlign(NewAlign, StOffset);
10408 // Truncate down to the new size.
10409 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10412 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10413 St->getPointerInfo().getWithOffset(StOffset),
10414 false, false, NewAlign).getNode();
10418 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10419 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10420 /// narrowing the load and store if it would end up being a win for performance
10422 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10423 StoreSDNode *ST = cast<StoreSDNode>(N);
10424 if (ST->isVolatile())
10427 SDValue Chain = ST->getChain();
10428 SDValue Value = ST->getValue();
10429 SDValue Ptr = ST->getBasePtr();
10430 EVT VT = Value.getValueType();
10432 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10435 unsigned Opc = Value.getOpcode();
10437 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10438 // is a byte mask indicating a consecutive number of bytes, check to see if
10439 // Y is known to provide just those bytes. If so, we try to replace the
10440 // load + replace + store sequence with a single (narrower) store, which makes
10442 if (Opc == ISD::OR) {
10443 std::pair<unsigned, unsigned> MaskedLoad;
10444 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10445 if (MaskedLoad.first)
10446 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10447 Value.getOperand(1), ST,this))
10448 return SDValue(NewST, 0);
10450 // Or is commutative, so try swapping X and Y.
10451 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10452 if (MaskedLoad.first)
10453 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10454 Value.getOperand(0), ST,this))
10455 return SDValue(NewST, 0);
10458 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10459 Value.getOperand(1).getOpcode() != ISD::Constant)
10462 SDValue N0 = Value.getOperand(0);
10463 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10464 Chain == SDValue(N0.getNode(), 1)) {
10465 LoadSDNode *LD = cast<LoadSDNode>(N0);
10466 if (LD->getBasePtr() != Ptr ||
10467 LD->getPointerInfo().getAddrSpace() !=
10468 ST->getPointerInfo().getAddrSpace())
10471 // Find the type to narrow it the load / op / store to.
10472 SDValue N1 = Value.getOperand(1);
10473 unsigned BitWidth = N1.getValueSizeInBits();
10474 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10475 if (Opc == ISD::AND)
10476 Imm ^= APInt::getAllOnesValue(BitWidth);
10477 if (Imm == 0 || Imm.isAllOnesValue())
10479 unsigned ShAmt = Imm.countTrailingZeros();
10480 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10481 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10482 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10483 // The narrowing should be profitable, the load/store operation should be
10484 // legal (or custom) and the store size should be equal to the NewVT width.
10485 while (NewBW < BitWidth &&
10486 (NewVT.getStoreSizeInBits() != NewBW ||
10487 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10488 !TLI.isNarrowingProfitable(VT, NewVT))) {
10489 NewBW = NextPowerOf2(NewBW);
10490 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10492 if (NewBW >= BitWidth)
10495 // If the lsb changed does not start at the type bitwidth boundary,
10496 // start at the previous one.
10498 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10499 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10500 std::min(BitWidth, ShAmt + NewBW));
10501 if ((Imm & Mask) == Imm) {
10502 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10503 if (Opc == ISD::AND)
10504 NewImm ^= APInt::getAllOnesValue(NewBW);
10505 uint64_t PtrOff = ShAmt / 8;
10506 // For big endian targets, we need to adjust the offset to the pointer to
10507 // load the correct bytes.
10508 if (DAG.getDataLayout().isBigEndian())
10509 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10511 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10512 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10513 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10516 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10517 Ptr.getValueType(), Ptr,
10518 DAG.getConstant(PtrOff, SDLoc(LD),
10519 Ptr.getValueType()));
10520 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10521 LD->getChain(), NewPtr,
10522 LD->getPointerInfo().getWithOffset(PtrOff),
10523 LD->isVolatile(), LD->isNonTemporal(),
10524 LD->isInvariant(), NewAlign,
10526 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10527 DAG.getConstant(NewImm, SDLoc(Value),
10529 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10531 ST->getPointerInfo().getWithOffset(PtrOff),
10532 false, false, NewAlign);
10534 AddToWorklist(NewPtr.getNode());
10535 AddToWorklist(NewLD.getNode());
10536 AddToWorklist(NewVal.getNode());
10537 WorklistRemover DeadNodes(*this);
10538 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10547 /// For a given floating point load / store pair, if the load value isn't used
10548 /// by any other operations, then consider transforming the pair to integer
10549 /// load / store operations if the target deems the transformation profitable.
10550 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10551 StoreSDNode *ST = cast<StoreSDNode>(N);
10552 SDValue Chain = ST->getChain();
10553 SDValue Value = ST->getValue();
10554 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10555 Value.hasOneUse() &&
10556 Chain == SDValue(Value.getNode(), 1)) {
10557 LoadSDNode *LD = cast<LoadSDNode>(Value);
10558 EVT VT = LD->getMemoryVT();
10559 if (!VT.isFloatingPoint() ||
10560 VT != ST->getMemoryVT() ||
10561 LD->isNonTemporal() ||
10562 ST->isNonTemporal() ||
10563 LD->getPointerInfo().getAddrSpace() != 0 ||
10564 ST->getPointerInfo().getAddrSpace() != 0)
10567 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10568 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10569 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10570 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10571 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10574 unsigned LDAlign = LD->getAlignment();
10575 unsigned STAlign = ST->getAlignment();
10576 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10577 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10578 if (LDAlign < ABIAlign || STAlign < ABIAlign)
10581 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10582 LD->getChain(), LD->getBasePtr(),
10583 LD->getPointerInfo(),
10584 false, false, false, LDAlign);
10586 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10587 NewLD, ST->getBasePtr(),
10588 ST->getPointerInfo(),
10589 false, false, STAlign);
10591 AddToWorklist(NewLD.getNode());
10592 AddToWorklist(NewST.getNode());
10593 WorklistRemover DeadNodes(*this);
10594 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10603 /// Helper struct to parse and store a memory address as base + index + offset.
10604 /// We ignore sign extensions when it is safe to do so.
10605 /// The following two expressions are not equivalent. To differentiate we need
10606 /// to store whether there was a sign extension involved in the index
10608 /// (load (i64 add (i64 copyfromreg %c)
10609 /// (i64 signextend (add (i8 load %index)
10613 /// (load (i64 add (i64 copyfromreg %c)
10614 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
10616 struct BaseIndexOffset {
10620 bool IsIndexSignExt;
10622 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10624 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10625 bool IsIndexSignExt) :
10626 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10628 bool equalBaseIndex(const BaseIndexOffset &Other) {
10629 return Other.Base == Base && Other.Index == Index &&
10630 Other.IsIndexSignExt == IsIndexSignExt;
10633 /// Parses tree in Ptr for base, index, offset addresses.
10634 static BaseIndexOffset match(SDValue Ptr) {
10635 bool IsIndexSignExt = false;
10637 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10638 // instruction, then it could be just the BASE or everything else we don't
10639 // know how to handle. Just use Ptr as BASE and give up.
10640 if (Ptr->getOpcode() != ISD::ADD)
10641 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10643 // We know that we have at least an ADD instruction. Try to pattern match
10644 // the simple case of BASE + OFFSET.
10645 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10646 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10647 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10651 // Inside a loop the current BASE pointer is calculated using an ADD and a
10652 // MUL instruction. In this case Ptr is the actual BASE pointer.
10653 // (i64 add (i64 %array_ptr)
10654 // (i64 mul (i64 %induction_var)
10655 // (i64 %element_size)))
10656 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10657 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10659 // Look at Base + Index + Offset cases.
10660 SDValue Base = Ptr->getOperand(0);
10661 SDValue IndexOffset = Ptr->getOperand(1);
10663 // Skip signextends.
10664 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10665 IndexOffset = IndexOffset->getOperand(0);
10666 IsIndexSignExt = true;
10669 // Either the case of Base + Index (no offset) or something else.
10670 if (IndexOffset->getOpcode() != ISD::ADD)
10671 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10673 // Now we have the case of Base + Index + offset.
10674 SDValue Index = IndexOffset->getOperand(0);
10675 SDValue Offset = IndexOffset->getOperand(1);
10677 if (!isa<ConstantSDNode>(Offset))
10678 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10680 // Ignore signextends.
10681 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10682 Index = Index->getOperand(0);
10683 IsIndexSignExt = true;
10684 } else IsIndexSignExt = false;
10686 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10687 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10692 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10694 ArrayRef<MemOpLink> Stores,
10696 SmallVector<SDValue, 8> BuildVector;
10698 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I)
10699 BuildVector.push_back(cast<StoreSDNode>(Stores[I].MemNode)->getValue());
10701 return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10704 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10705 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10706 unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10707 // Make sure we have something to merge.
10711 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10712 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10713 unsigned LatestNodeUsed = 0;
10715 for (unsigned i=0; i < NumElem; ++i) {
10716 // Find a chain for the new wide-store operand. Notice that some
10717 // of the store nodes that we found may not be selected for inclusion
10718 // in the wide store. The chain we use needs to be the chain of the
10719 // latest store node which is *used* and replaced by the wide store.
10720 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10721 LatestNodeUsed = i;
10724 // The latest Node in the DAG.
10725 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10726 SDLoc DL(StoreNodes[0].MemNode);
10730 // Find a legal type for the vector store.
10731 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10732 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10733 if (IsConstantSrc) {
10734 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Ty);
10736 SmallVector<SDValue, 8> Ops;
10737 for (unsigned i = 0; i < NumElem ; ++i) {
10738 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10739 SDValue Val = St->getValue();
10740 // All of the operands of a BUILD_VECTOR must have the same type.
10741 if (Val.getValueType() != MemVT)
10743 Ops.push_back(Val);
10746 // Build the extracted vector elements back into a vector.
10747 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10750 // We should always use a vector store when merging extracted vector
10751 // elements, so this path implies a store of constants.
10752 assert(IsConstantSrc && "Merged vector elements should use vector store");
10754 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
10755 APInt StoreInt(SizeInBits, 0);
10757 // Construct a single integer constant which is made of the smaller
10758 // constant inputs.
10759 bool IsLE = DAG.getDataLayout().isLittleEndian();
10760 for (unsigned i = 0; i < NumElem ; ++i) {
10761 unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10762 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10763 SDValue Val = St->getValue();
10764 StoreInt <<= ElementSizeBytes * 8;
10765 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10766 StoreInt |= C->getAPIntValue().zext(SizeInBits);
10767 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10768 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
10770 llvm_unreachable("Invalid constant element type");
10774 // Create the new Load and Store operations.
10775 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
10776 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10779 SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10780 FirstInChain->getBasePtr(),
10781 FirstInChain->getPointerInfo(),
10783 FirstInChain->getAlignment());
10785 // Replace the last store with the new store
10786 CombineTo(LatestOp, NewStore);
10787 // Erase all other stores.
10788 for (unsigned i = 0; i < NumElem ; ++i) {
10789 if (StoreNodes[i].MemNode == LatestOp)
10791 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10792 // ReplaceAllUsesWith will replace all uses that existed when it was
10793 // called, but graph optimizations may cause new ones to appear. For
10794 // example, the case in pr14333 looks like
10796 // St's chain -> St -> another store -> X
10798 // And the only difference from St to the other store is the chain.
10799 // When we change it's chain to be St's chain they become identical,
10800 // get CSEed and the net result is that X is now a use of St.
10801 // Since we know that St is redundant, just iterate.
10802 while (!St->use_empty())
10803 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10804 deleteAndRecombine(St);
10810 void DAGCombiner::getStoreMergeAndAliasCandidates(
10811 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
10812 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
10813 // This holds the base pointer, index, and the offset in bytes from the base
10815 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10817 // We must have a base and an offset.
10818 if (!BasePtr.Base.getNode())
10821 // Do not handle stores to undef base pointers.
10822 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10825 // Walk up the chain and look for nodes with offsets from the same
10826 // base pointer. Stop when reaching an instruction with a different kind
10827 // or instruction which has a different base pointer.
10828 EVT MemVT = St->getMemoryVT();
10830 StoreSDNode *Index = St;
10832 // If the chain has more than one use, then we can't reorder the mem ops.
10833 if (Index != St && !SDValue(Index, 0)->hasOneUse())
10836 // Find the base pointer and offset for this memory node.
10837 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10839 // Check that the base pointer is the same as the original one.
10840 if (!Ptr.equalBaseIndex(BasePtr))
10843 // The memory operands must not be volatile.
10844 if (Index->isVolatile() || Index->isIndexed())
10848 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10849 if (St->isTruncatingStore())
10852 // The stored memory type must be the same.
10853 if (Index->getMemoryVT() != MemVT)
10856 // We found a potential memory operand to merge.
10857 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10859 // Find the next memory operand in the chain. If the next operand in the
10860 // chain is a store then move up and continue the scan with the next
10861 // memory operand. If the next operand is a load save it and use alias
10862 // information to check if it interferes with anything.
10863 SDNode *NextInChain = Index->getChain().getNode();
10865 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10866 // We found a store node. Use it for the next iteration.
10869 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10870 if (Ldn->isVolatile()) {
10875 // Save the load node for later. Continue the scan.
10876 AliasLoadNodes.push_back(Ldn);
10877 NextInChain = Ldn->getChain().getNode();
10887 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10888 if (OptLevel == CodeGenOpt::None)
10891 EVT MemVT = St->getMemoryVT();
10892 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10893 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10894 Attribute::NoImplicitFloat);
10896 // This function cannot currently deal with non-byte-sized memory sizes.
10897 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10900 // Don't merge vectors into wider inputs.
10901 if (MemVT.isVector() || !MemVT.isSimple())
10904 // Perform an early exit check. Do not bother looking at stored values that
10905 // are not constants, loads, or extracted vector elements.
10906 SDValue StoredVal = St->getValue();
10907 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10908 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10909 isa<ConstantFPSDNode>(StoredVal);
10910 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10912 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10915 // Only look at ends of store sequences.
10916 SDValue Chain = SDValue(St, 0);
10917 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10920 // Save the LoadSDNodes that we find in the chain.
10921 // We need to make sure that these nodes do not interfere with
10922 // any of the store nodes.
10923 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10925 // Save the StoreSDNodes that we find in the chain.
10926 SmallVector<MemOpLink, 8> StoreNodes;
10928 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
10930 // Check if there is anything to merge.
10931 if (StoreNodes.size() < 2)
10934 // Sort the memory operands according to their distance from the base pointer.
10935 std::sort(StoreNodes.begin(), StoreNodes.end(),
10936 [](MemOpLink LHS, MemOpLink RHS) {
10937 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10938 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10939 LHS.SequenceNum > RHS.SequenceNum);
10942 // Scan the memory operations on the chain and find the first non-consecutive
10943 // store memory address.
10944 unsigned LastConsecutiveStore = 0;
10945 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10946 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10948 // Check that the addresses are consecutive starting from the second
10949 // element in the list of stores.
10951 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10952 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10956 bool Alias = false;
10957 // Check if this store interferes with any of the loads that we found.
10958 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10959 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10963 // We found a load that alias with this store. Stop the sequence.
10967 // Mark this node as useful.
10968 LastConsecutiveStore = i;
10971 // The node with the lowest store address.
10972 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10973 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
10974 unsigned FirstStoreAlign = FirstInChain->getAlignment();
10975 LLVMContext &Context = *DAG.getContext();
10976 const DataLayout &DL = DAG.getDataLayout();
10978 // Store the constants into memory as one consecutive store.
10979 if (IsConstantSrc) {
10980 unsigned LastLegalType = 0;
10981 unsigned LastLegalVectorType = 0;
10982 bool NonZero = false;
10983 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10984 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10985 SDValue StoredVal = St->getValue();
10987 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10988 NonZero |= !C->isNullValue();
10989 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10990 NonZero |= !C->getConstantFPValue()->isNullValue();
10996 // Find a legal type for the constant store.
10997 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
10998 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
10999 if (TLI.isTypeLegal(StoreTy) &&
11000 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11001 FirstStoreAlign)) {
11002 LastLegalType = i+1;
11003 // Or check whether a truncstore is legal.
11004 } else if (TLI.getTypeAction(Context, StoreTy) ==
11005 TargetLowering::TypePromoteInteger) {
11006 EVT LegalizedStoredValueTy =
11007 TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11008 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11009 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11010 FirstStoreAS, FirstStoreAlign)) {
11011 LastLegalType = i + 1;
11015 // Find a legal type for the vector store.
11016 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11017 if (TLI.isTypeLegal(Ty) &&
11018 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11019 FirstStoreAlign)) {
11020 LastLegalVectorType = i + 1;
11025 // We only use vectors if the constant is known to be zero or the target
11026 // allows it and the function is not marked with the noimplicitfloat
11029 LastLegalVectorType = 0;
11030 } else if (NonZero && !TLI.storeOfVectorConstantIsCheap(MemVT,
11031 LastLegalVectorType,
11033 LastLegalVectorType = 0;
11036 // Check if we found a legal integer type to store.
11037 if (LastLegalType == 0 && LastLegalVectorType == 0)
11040 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11041 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11043 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11047 // When extracting multiple vector elements, try to store them
11048 // in one vector store rather than a sequence of scalar stores.
11049 if (IsExtractVecEltSrc) {
11050 unsigned NumElem = 0;
11051 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11052 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11053 SDValue StoredVal = St->getValue();
11054 // This restriction could be loosened.
11055 // Bail out if any stored values are not elements extracted from a vector.
11056 // It should be possible to handle mixed sources, but load sources need
11057 // more careful handling (see the block of code below that handles
11058 // consecutive loads).
11059 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11062 // Find a legal type for the vector store.
11063 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11064 if (TLI.isTypeLegal(Ty) &&
11065 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11070 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11074 // Below we handle the case of multiple consecutive stores that
11075 // come from multiple consecutive loads. We merge them into a single
11076 // wide load and a single wide store.
11078 // Look for load nodes which are used by the stored values.
11079 SmallVector<MemOpLink, 8> LoadNodes;
11081 // Find acceptable loads. Loads need to have the same chain (token factor),
11082 // must not be zext, volatile, indexed, and they must be consecutive.
11083 BaseIndexOffset LdBasePtr;
11084 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11085 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11086 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11089 // Loads must only have one use.
11090 if (!Ld->hasNUsesOfValue(1, 0))
11093 // The memory operands must not be volatile.
11094 if (Ld->isVolatile() || Ld->isIndexed())
11097 // We do not accept ext loads.
11098 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11101 // The stored memory type must be the same.
11102 if (Ld->getMemoryVT() != MemVT)
11105 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11106 // If this is not the first ptr that we check.
11107 if (LdBasePtr.Base.getNode()) {
11108 // The base ptr must be the same.
11109 if (!LdPtr.equalBaseIndex(LdBasePtr))
11112 // Check that all other base pointers are the same as this one.
11116 // We found a potential memory operand to merge.
11117 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11120 if (LoadNodes.size() < 2)
11123 // If we have load/store pair instructions and we only have two values,
11125 unsigned RequiredAlignment;
11126 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11127 St->getAlignment() >= RequiredAlignment)
11130 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11131 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11132 unsigned FirstLoadAlign = FirstLoad->getAlignment();
11134 // Scan the memory operations on the chain and find the first non-consecutive
11135 // load memory address. These variables hold the index in the store node
11137 unsigned LastConsecutiveLoad = 0;
11138 // This variable refers to the size and not index in the array.
11139 unsigned LastLegalVectorType = 0;
11140 unsigned LastLegalIntegerType = 0;
11141 StartAddress = LoadNodes[0].OffsetFromBase;
11142 SDValue FirstChain = FirstLoad->getChain();
11143 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11144 // All loads much share the same chain.
11145 if (LoadNodes[i].MemNode->getChain() != FirstChain)
11148 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11149 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11151 LastConsecutiveLoad = i;
11153 // Find a legal type for the vector store.
11154 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11155 if (TLI.isTypeLegal(StoreTy) &&
11156 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11157 FirstStoreAlign) &&
11158 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11160 LastLegalVectorType = i + 1;
11163 // Find a legal type for the integer store.
11164 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11165 StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11166 if (TLI.isTypeLegal(StoreTy) &&
11167 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11168 FirstStoreAlign) &&
11169 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11171 LastLegalIntegerType = i + 1;
11172 // Or check whether a truncstore and extload is legal.
11173 else if (TLI.getTypeAction(Context, StoreTy) ==
11174 TargetLowering::TypePromoteInteger) {
11175 EVT LegalizedStoredValueTy =
11176 TLI.getTypeToTransformTo(Context, StoreTy);
11177 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11178 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11179 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11180 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11181 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11182 FirstStoreAS, FirstStoreAlign) &&
11183 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11184 FirstLoadAS, FirstLoadAlign))
11185 LastLegalIntegerType = i+1;
11189 // Only use vector types if the vector type is larger than the integer type.
11190 // If they are the same, use integers.
11191 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11192 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11194 // We add +1 here because the LastXXX variables refer to location while
11195 // the NumElem refers to array/index size.
11196 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11197 NumElem = std::min(LastLegalType, NumElem);
11202 // The latest Node in the DAG.
11203 unsigned LatestNodeUsed = 0;
11204 for (unsigned i=1; i<NumElem; ++i) {
11205 // Find a chain for the new wide-store operand. Notice that some
11206 // of the store nodes that we found may not be selected for inclusion
11207 // in the wide store. The chain we use needs to be the chain of the
11208 // latest store node which is *used* and replaced by the wide store.
11209 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11210 LatestNodeUsed = i;
11213 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11215 // Find if it is better to use vectors or integers to load and store
11219 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11221 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11222 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11225 SDLoc LoadDL(LoadNodes[0].MemNode);
11226 SDLoc StoreDL(StoreNodes[0].MemNode);
11228 SDValue NewLoad = DAG.getLoad(
11229 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11230 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11232 SDValue NewStore = DAG.getStore(
11233 LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11234 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11236 // Replace one of the loads with the new load.
11237 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11238 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11239 SDValue(NewLoad.getNode(), 1));
11241 // Remove the rest of the load chains.
11242 for (unsigned i = 1; i < NumElem ; ++i) {
11243 // Replace all chain users of the old load nodes with the chain of the new
11245 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11246 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11249 // Replace the last store with the new store.
11250 CombineTo(LatestOp, NewStore);
11251 // Erase all other stores.
11252 for (unsigned i = 0; i < NumElem ; ++i) {
11253 // Remove all Store nodes.
11254 if (StoreNodes[i].MemNode == LatestOp)
11256 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11257 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11258 deleteAndRecombine(St);
11264 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11265 StoreSDNode *ST = cast<StoreSDNode>(N);
11266 SDValue Chain = ST->getChain();
11267 SDValue Value = ST->getValue();
11268 SDValue Ptr = ST->getBasePtr();
11270 // If this is a store of a bit convert, store the input value if the
11271 // resultant store does not need a higher alignment than the original.
11272 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11273 ST->isUnindexed()) {
11274 unsigned OrigAlign = ST->getAlignment();
11275 EVT SVT = Value.getOperand(0).getValueType();
11276 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11277 SVT.getTypeForEVT(*DAG.getContext()));
11278 if (Align <= OrigAlign &&
11279 ((!LegalOperations && !ST->isVolatile()) ||
11280 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11281 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11282 Ptr, ST->getPointerInfo(), ST->isVolatile(),
11283 ST->isNonTemporal(), OrigAlign,
11287 // Turn 'store undef, Ptr' -> nothing.
11288 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11291 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11292 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11293 // NOTE: If the original store is volatile, this transform must not increase
11294 // the number of stores. For example, on x86-32 an f64 can be stored in one
11295 // processor operation but an i64 (which is not legal) requires two. So the
11296 // transform should not be done in this case.
11297 if (Value.getOpcode() != ISD::TargetConstantFP) {
11299 switch (CFP->getSimpleValueType(0).SimpleTy) {
11300 default: llvm_unreachable("Unknown FP type");
11301 case MVT::f16: // We don't do this for these yet.
11307 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11308 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11310 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11311 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11313 return DAG.getStore(Chain, SDLoc(N), Tmp,
11314 Ptr, ST->getMemOperand());
11318 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11319 !ST->isVolatile()) ||
11320 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11322 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11323 getZExtValue(), SDLoc(CFP), MVT::i64);
11324 return DAG.getStore(Chain, SDLoc(N), Tmp,
11325 Ptr, ST->getMemOperand());
11328 if (!ST->isVolatile() &&
11329 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11330 // Many FP stores are not made apparent until after legalize, e.g. for
11331 // argument passing. Since this is so common, custom legalize the
11332 // 64-bit integer store into two 32-bit stores.
11333 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11334 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11335 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11336 if (DAG.getDataLayout().isBigEndian())
11339 unsigned Alignment = ST->getAlignment();
11340 bool isVolatile = ST->isVolatile();
11341 bool isNonTemporal = ST->isNonTemporal();
11342 AAMDNodes AAInfo = ST->getAAInfo();
11346 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11347 Ptr, ST->getPointerInfo(),
11348 isVolatile, isNonTemporal,
11349 ST->getAlignment(), AAInfo);
11350 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11351 DAG.getConstant(4, DL, Ptr.getValueType()));
11352 Alignment = MinAlign(Alignment, 4U);
11353 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11354 Ptr, ST->getPointerInfo().getWithOffset(4),
11355 isVolatile, isNonTemporal,
11356 Alignment, AAInfo);
11357 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11366 // Try to infer better alignment information than the store already has.
11367 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11368 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11369 if (Align > ST->getAlignment()) {
11371 DAG.getTruncStore(Chain, SDLoc(N), Value,
11372 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11373 ST->isVolatile(), ST->isNonTemporal(), Align,
11375 if (NewStore.getNode() != N)
11376 return CombineTo(ST, NewStore, true);
11381 // Try transforming a pair floating point load / store ops to integer
11382 // load / store ops.
11383 if (SDValue NewST = TransformFPLoadStorePair(N))
11386 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11387 : DAG.getSubtarget().useAA();
11389 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11390 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11393 if (UseAA && ST->isUnindexed()) {
11394 // Walk up chain skipping non-aliasing memory nodes.
11395 SDValue BetterChain = FindBetterChain(N, Chain);
11397 // If there is a better chain.
11398 if (Chain != BetterChain) {
11401 // Replace the chain to avoid dependency.
11402 if (ST->isTruncatingStore()) {
11403 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11404 ST->getMemoryVT(), ST->getMemOperand());
11406 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11407 ST->getMemOperand());
11410 // Create token to keep both nodes around.
11411 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11412 MVT::Other, Chain, ReplStore);
11414 // Make sure the new and old chains are cleaned up.
11415 AddToWorklist(Token.getNode());
11417 // Don't add users to work list.
11418 return CombineTo(N, Token, false);
11422 // Try transforming N to an indexed store.
11423 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11424 return SDValue(N, 0);
11426 // FIXME: is there such a thing as a truncating indexed store?
11427 if (ST->isTruncatingStore() && ST->isUnindexed() &&
11428 Value.getValueType().isInteger()) {
11429 // See if we can simplify the input to this truncstore with knowledge that
11430 // only the low bits are being used. For example:
11431 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
11433 GetDemandedBits(Value,
11434 APInt::getLowBitsSet(
11435 Value.getValueType().getScalarType().getSizeInBits(),
11436 ST->getMemoryVT().getScalarType().getSizeInBits()));
11437 AddToWorklist(Value.getNode());
11438 if (Shorter.getNode())
11439 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11440 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11442 // Otherwise, see if we can simplify the operation with
11443 // SimplifyDemandedBits, which only works if the value has a single use.
11444 if (SimplifyDemandedBits(Value,
11445 APInt::getLowBitsSet(
11446 Value.getValueType().getScalarType().getSizeInBits(),
11447 ST->getMemoryVT().getScalarType().getSizeInBits())))
11448 return SDValue(N, 0);
11451 // If this is a load followed by a store to the same location, then the store
11453 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11454 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11455 ST->isUnindexed() && !ST->isVolatile() &&
11456 // There can't be any side effects between the load and store, such as
11457 // a call or store.
11458 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11459 // The store is dead, remove it.
11464 // If this is a store followed by a store with the same value to the same
11465 // location, then the store is dead/noop.
11466 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11467 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11468 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11469 ST1->isUnindexed() && !ST1->isVolatile()) {
11470 // The store is dead, remove it.
11475 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11476 // truncating store. We can do this even if this is already a truncstore.
11477 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11478 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11479 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11480 ST->getMemoryVT())) {
11481 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11482 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11485 // Only perform this optimization before the types are legal, because we
11486 // don't want to perform this optimization on every DAGCombine invocation.
11488 bool EverChanged = false;
11491 // There can be multiple store sequences on the same chain.
11492 // Keep trying to merge store sequences until we are unable to do so
11493 // or until we merge the last store on the chain.
11494 bool Changed = MergeConsecutiveStores(ST);
11495 EverChanged |= Changed;
11496 if (!Changed) break;
11497 } while (ST->getOpcode() != ISD::DELETED_NODE);
11500 return SDValue(N, 0);
11503 return ReduceLoadOpStoreWidth(N);
11506 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11507 SDValue InVec = N->getOperand(0);
11508 SDValue InVal = N->getOperand(1);
11509 SDValue EltNo = N->getOperand(2);
11512 // If the inserted element is an UNDEF, just use the input vector.
11513 if (InVal.getOpcode() == ISD::UNDEF)
11516 EVT VT = InVec.getValueType();
11518 // If we can't generate a legal BUILD_VECTOR, exit
11519 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11522 // Check that we know which element is being inserted
11523 if (!isa<ConstantSDNode>(EltNo))
11525 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11527 // Canonicalize insert_vector_elt dag nodes.
11529 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11530 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11532 // Do this only if the child insert_vector node has one use; also
11533 // do this only if indices are both constants and Idx1 < Idx0.
11534 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11535 && isa<ConstantSDNode>(InVec.getOperand(2))) {
11536 unsigned OtherElt =
11537 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11538 if (Elt < OtherElt) {
11540 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11541 InVec.getOperand(0), InVal, EltNo);
11542 AddToWorklist(NewOp.getNode());
11543 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11544 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11548 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11549 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
11550 // vector elements.
11551 SmallVector<SDValue, 8> Ops;
11552 // Do not combine these two vectors if the output vector will not replace
11553 // the input vector.
11554 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11555 Ops.append(InVec.getNode()->op_begin(),
11556 InVec.getNode()->op_end());
11557 } else if (InVec.getOpcode() == ISD::UNDEF) {
11558 unsigned NElts = VT.getVectorNumElements();
11559 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11564 // Insert the element
11565 if (Elt < Ops.size()) {
11566 // All the operands of BUILD_VECTOR must have the same type;
11567 // we enforce that here.
11568 EVT OpVT = Ops[0].getValueType();
11569 if (InVal.getValueType() != OpVT)
11570 InVal = OpVT.bitsGT(InVal.getValueType()) ?
11571 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11572 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11576 // Return the new vector
11577 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11580 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11581 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11582 EVT ResultVT = EVE->getValueType(0);
11583 EVT VecEltVT = InVecVT.getVectorElementType();
11584 unsigned Align = OriginalLoad->getAlignment();
11585 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
11586 VecEltVT.getTypeForEVT(*DAG.getContext()));
11588 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11593 SDValue NewPtr = OriginalLoad->getBasePtr();
11595 EVT PtrType = NewPtr.getValueType();
11596 MachinePointerInfo MPI;
11598 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11599 int Elt = ConstEltNo->getZExtValue();
11600 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11601 Offset = DAG.getConstant(PtrOff, DL, PtrType);
11602 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11604 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11605 Offset = DAG.getNode(
11606 ISD::MUL, DL, PtrType, Offset,
11607 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11608 MPI = OriginalLoad->getPointerInfo();
11610 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11612 // The replacement we need to do here is a little tricky: we need to
11613 // replace an extractelement of a load with a load.
11614 // Use ReplaceAllUsesOfValuesWith to do the replacement.
11615 // Note that this replacement assumes that the extractvalue is the only
11616 // use of the load; that's okay because we don't want to perform this
11617 // transformation in other cases anyway.
11620 if (ResultVT.bitsGT(VecEltVT)) {
11621 // If the result type of vextract is wider than the load, then issue an
11622 // extending load instead.
11623 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11627 Load = DAG.getExtLoad(
11628 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11629 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11630 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11631 Chain = Load.getValue(1);
11633 Load = DAG.getLoad(
11634 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11635 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11636 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11637 Chain = Load.getValue(1);
11638 if (ResultVT.bitsLT(VecEltVT))
11639 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11641 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11643 WorklistRemover DeadNodes(*this);
11644 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11645 SDValue To[] = { Load, Chain };
11646 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11647 // Since we're explicitly calling ReplaceAllUses, add the new node to the
11648 // worklist explicitly as well.
11649 AddToWorklist(Load.getNode());
11650 AddUsersToWorklist(Load.getNode()); // Add users too
11651 // Make sure to revisit this node to clean it up; it will usually be dead.
11652 AddToWorklist(EVE);
11654 return SDValue(EVE, 0);
11657 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11658 // (vextract (scalar_to_vector val, 0) -> val
11659 SDValue InVec = N->getOperand(0);
11660 EVT VT = InVec.getValueType();
11661 EVT NVT = N->getValueType(0);
11663 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11664 // Check if the result type doesn't match the inserted element type. A
11665 // SCALAR_TO_VECTOR may truncate the inserted element and the
11666 // EXTRACT_VECTOR_ELT may widen the extracted vector.
11667 SDValue InOp = InVec.getOperand(0);
11668 if (InOp.getValueType() != NVT) {
11669 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11670 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11675 SDValue EltNo = N->getOperand(1);
11676 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11678 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11679 // We only perform this optimization before the op legalization phase because
11680 // we may introduce new vector instructions which are not backed by TD
11681 // patterns. For example on AVX, extracting elements from a wide vector
11682 // without using extract_subvector. However, if we can find an underlying
11683 // scalar value, then we can always use that.
11684 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11686 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11687 int NumElem = VT.getVectorNumElements();
11688 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11689 // Find the new index to extract from.
11690 int OrigElt = SVOp->getMaskElt(Elt);
11692 // Extracting an undef index is undef.
11694 return DAG.getUNDEF(NVT);
11696 // Select the right vector half to extract from.
11698 if (OrigElt < NumElem) {
11699 SVInVec = InVec->getOperand(0);
11701 SVInVec = InVec->getOperand(1);
11702 OrigElt -= NumElem;
11705 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11706 SDValue InOp = SVInVec.getOperand(OrigElt);
11707 if (InOp.getValueType() != NVT) {
11708 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11709 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11715 // FIXME: We should handle recursing on other vector shuffles and
11716 // scalar_to_vector here as well.
11718 if (!LegalOperations) {
11719 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
11720 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11721 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11725 bool BCNumEltsChanged = false;
11726 EVT ExtVT = VT.getVectorElementType();
11729 // If the result of load has to be truncated, then it's not necessarily
11731 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11734 if (InVec.getOpcode() == ISD::BITCAST) {
11735 // Don't duplicate a load with other uses.
11736 if (!InVec.hasOneUse())
11739 EVT BCVT = InVec.getOperand(0).getValueType();
11740 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11742 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11743 BCNumEltsChanged = true;
11744 InVec = InVec.getOperand(0);
11745 ExtVT = BCVT.getVectorElementType();
11748 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11749 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11750 ISD::isNormalLoad(InVec.getNode()) &&
11751 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11752 SDValue Index = N->getOperand(1);
11753 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11754 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11758 // Perform only after legalization to ensure build_vector / vector_shuffle
11759 // optimizations have already been done.
11760 if (!LegalOperations) return SDValue();
11762 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11763 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11764 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11767 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11769 LoadSDNode *LN0 = nullptr;
11770 const ShuffleVectorSDNode *SVN = nullptr;
11771 if (ISD::isNormalLoad(InVec.getNode())) {
11772 LN0 = cast<LoadSDNode>(InVec);
11773 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11774 InVec.getOperand(0).getValueType() == ExtVT &&
11775 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11776 // Don't duplicate a load with other uses.
11777 if (!InVec.hasOneUse())
11780 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11781 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11782 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11784 // (load $addr+1*size)
11786 // Don't duplicate a load with other uses.
11787 if (!InVec.hasOneUse())
11790 // If the bit convert changed the number of elements, it is unsafe
11791 // to examine the mask.
11792 if (BCNumEltsChanged)
11795 // Select the input vector, guarding against out of range extract vector.
11796 unsigned NumElems = VT.getVectorNumElements();
11797 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11798 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11800 if (InVec.getOpcode() == ISD::BITCAST) {
11801 // Don't duplicate a load with other uses.
11802 if (!InVec.hasOneUse())
11805 InVec = InVec.getOperand(0);
11807 if (ISD::isNormalLoad(InVec.getNode())) {
11808 LN0 = cast<LoadSDNode>(InVec);
11809 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11810 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11814 // Make sure we found a non-volatile load and the extractelement is
11816 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11819 // If Idx was -1 above, Elt is going to be -1, so just return undef.
11821 return DAG.getUNDEF(LVT);
11823 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11829 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11830 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11831 // We perform this optimization post type-legalization because
11832 // the type-legalizer often scalarizes integer-promoted vectors.
11833 // Performing this optimization before may create bit-casts which
11834 // will be type-legalized to complex code sequences.
11835 // We perform this optimization only before the operation legalizer because we
11836 // may introduce illegal operations.
11837 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11840 unsigned NumInScalars = N->getNumOperands();
11842 EVT VT = N->getValueType(0);
11844 // Check to see if this is a BUILD_VECTOR of a bunch of values
11845 // which come from any_extend or zero_extend nodes. If so, we can create
11846 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11847 // optimizations. We do not handle sign-extend because we can't fill the sign
11849 EVT SourceType = MVT::Other;
11850 bool AllAnyExt = true;
11852 for (unsigned i = 0; i != NumInScalars; ++i) {
11853 SDValue In = N->getOperand(i);
11854 // Ignore undef inputs.
11855 if (In.getOpcode() == ISD::UNDEF) continue;
11857 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
11858 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11860 // Abort if the element is not an extension.
11861 if (!ZeroExt && !AnyExt) {
11862 SourceType = MVT::Other;
11866 // The input is a ZeroExt or AnyExt. Check the original type.
11867 EVT InTy = In.getOperand(0).getValueType();
11869 // Check that all of the widened source types are the same.
11870 if (SourceType == MVT::Other)
11873 else if (InTy != SourceType) {
11874 // Multiple income types. Abort.
11875 SourceType = MVT::Other;
11879 // Check if all of the extends are ANY_EXTENDs.
11880 AllAnyExt &= AnyExt;
11883 // In order to have valid types, all of the inputs must be extended from the
11884 // same source type and all of the inputs must be any or zero extend.
11885 // Scalar sizes must be a power of two.
11886 EVT OutScalarTy = VT.getScalarType();
11887 bool ValidTypes = SourceType != MVT::Other &&
11888 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11889 isPowerOf2_32(SourceType.getSizeInBits());
11891 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11892 // turn into a single shuffle instruction.
11896 bool isLE = DAG.getDataLayout().isLittleEndian();
11897 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11898 assert(ElemRatio > 1 && "Invalid element size ratio");
11899 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11900 DAG.getConstant(0, SDLoc(N), SourceType);
11902 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11903 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11905 // Populate the new build_vector
11906 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11907 SDValue Cast = N->getOperand(i);
11908 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11909 Cast.getOpcode() == ISD::ZERO_EXTEND ||
11910 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11912 if (Cast.getOpcode() == ISD::UNDEF)
11913 In = DAG.getUNDEF(SourceType);
11915 In = Cast->getOperand(0);
11916 unsigned Index = isLE ? (i * ElemRatio) :
11917 (i * ElemRatio + (ElemRatio - 1));
11919 assert(Index < Ops.size() && "Invalid index");
11923 // The type of the new BUILD_VECTOR node.
11924 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11925 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11926 "Invalid vector size");
11927 // Check if the new vector type is legal.
11928 if (!isTypeLegal(VecVT)) return SDValue();
11930 // Make the new BUILD_VECTOR.
11931 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11933 // The new BUILD_VECTOR node has the potential to be further optimized.
11934 AddToWorklist(BV.getNode());
11935 // Bitcast to the desired type.
11936 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11939 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11940 EVT VT = N->getValueType(0);
11942 unsigned NumInScalars = N->getNumOperands();
11945 EVT SrcVT = MVT::Other;
11946 unsigned Opcode = ISD::DELETED_NODE;
11947 unsigned NumDefs = 0;
11949 for (unsigned i = 0; i != NumInScalars; ++i) {
11950 SDValue In = N->getOperand(i);
11951 unsigned Opc = In.getOpcode();
11953 if (Opc == ISD::UNDEF)
11956 // If all scalar values are floats and converted from integers.
11957 if (Opcode == ISD::DELETED_NODE &&
11958 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11965 EVT InVT = In.getOperand(0).getValueType();
11967 // If all scalar values are typed differently, bail out. It's chosen to
11968 // simplify BUILD_VECTOR of integer types.
11969 if (SrcVT == MVT::Other)
11976 // If the vector has just one element defined, it's not worth to fold it into
11977 // a vectorized one.
11981 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11982 && "Should only handle conversion from integer to float.");
11983 assert(SrcVT != MVT::Other && "Cannot determine source type!");
11985 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11987 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11990 // Just because the floating-point vector type is legal does not necessarily
11991 // mean that the corresponding integer vector type is.
11992 if (!isTypeLegal(NVT))
11995 SmallVector<SDValue, 8> Opnds;
11996 for (unsigned i = 0; i != NumInScalars; ++i) {
11997 SDValue In = N->getOperand(i);
11999 if (In.getOpcode() == ISD::UNDEF)
12000 Opnds.push_back(DAG.getUNDEF(SrcVT));
12002 Opnds.push_back(In.getOperand(0));
12004 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
12005 AddToWorklist(BV.getNode());
12007 return DAG.getNode(Opcode, dl, VT, BV);
12010 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12011 unsigned NumInScalars = N->getNumOperands();
12013 EVT VT = N->getValueType(0);
12015 // A vector built entirely of undefs is undef.
12016 if (ISD::allOperandsUndef(N))
12017 return DAG.getUNDEF(VT);
12019 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12022 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12025 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12026 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12027 // at most two distinct vectors, turn this into a shuffle node.
12029 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12030 if (!isTypeLegal(VT))
12033 // May only combine to shuffle after legalize if shuffle is legal.
12034 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12037 SDValue VecIn1, VecIn2;
12038 bool UsesZeroVector = false;
12039 for (unsigned i = 0; i != NumInScalars; ++i) {
12040 SDValue Op = N->getOperand(i);
12041 // Ignore undef inputs.
12042 if (Op.getOpcode() == ISD::UNDEF) continue;
12044 // See if we can combine this build_vector into a blend with a zero vector.
12045 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12046 UsesZeroVector = true;
12050 // If this input is something other than a EXTRACT_VECTOR_ELT with a
12051 // constant index, bail out.
12052 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12053 !isa<ConstantSDNode>(Op.getOperand(1))) {
12054 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12058 // We allow up to two distinct input vectors.
12059 SDValue ExtractedFromVec = Op.getOperand(0);
12060 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12063 if (!VecIn1.getNode()) {
12064 VecIn1 = ExtractedFromVec;
12065 } else if (!VecIn2.getNode() && !UsesZeroVector) {
12066 VecIn2 = ExtractedFromVec;
12068 // Too many inputs.
12069 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12074 // If everything is good, we can make a shuffle operation.
12075 if (VecIn1.getNode()) {
12076 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12077 SmallVector<int, 8> Mask;
12078 for (unsigned i = 0; i != NumInScalars; ++i) {
12079 unsigned Opcode = N->getOperand(i).getOpcode();
12080 if (Opcode == ISD::UNDEF) {
12081 Mask.push_back(-1);
12085 // Operands can also be zero.
12086 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12087 assert(UsesZeroVector &&
12088 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12089 "Unexpected node found!");
12090 Mask.push_back(NumInScalars+i);
12094 // If extracting from the first vector, just use the index directly.
12095 SDValue Extract = N->getOperand(i);
12096 SDValue ExtVal = Extract.getOperand(1);
12097 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12098 if (Extract.getOperand(0) == VecIn1) {
12099 Mask.push_back(ExtIndex);
12103 // Otherwise, use InIdx + InputVecSize
12104 Mask.push_back(InNumElements + ExtIndex);
12107 // Avoid introducing illegal shuffles with zero.
12108 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12111 // We can't generate a shuffle node with mismatched input and output types.
12112 // Attempt to transform a single input vector to the correct type.
12113 if ((VT != VecIn1.getValueType())) {
12114 // If the input vector type has a different base type to the output
12115 // vector type, bail out.
12116 EVT VTElemType = VT.getVectorElementType();
12117 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12118 (VecIn2.getNode() &&
12119 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12122 // If the input vector is too small, widen it.
12123 // We only support widening of vectors which are half the size of the
12124 // output registers. For example XMM->YMM widening on X86 with AVX.
12125 EVT VecInT = VecIn1.getValueType();
12126 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12127 // If we only have one small input, widen it by adding undef values.
12128 if (!VecIn2.getNode())
12129 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12130 DAG.getUNDEF(VecIn1.getValueType()));
12131 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12132 // If we have two small inputs of the same type, try to concat them.
12133 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12134 VecIn2 = SDValue(nullptr, 0);
12137 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12138 // If the input vector is too large, try to split it.
12139 // We don't support having two input vectors that are too large.
12140 // If the zero vector was used, we can not split the vector,
12141 // since we'd need 3 inputs.
12142 if (UsesZeroVector || VecIn2.getNode())
12145 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12148 // Try to replace VecIn1 with two extract_subvectors
12149 // No need to update the masks, they should still be correct.
12150 VecIn2 = DAG.getNode(
12151 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12152 DAG.getConstant(VT.getVectorNumElements(), dl,
12153 TLI.getVectorIdxTy(DAG.getDataLayout())));
12154 VecIn1 = DAG.getNode(
12155 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12156 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12161 if (UsesZeroVector)
12162 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12163 DAG.getConstantFP(0.0, dl, VT);
12165 // If VecIn2 is unused then change it to undef.
12166 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12168 // Check that we were able to transform all incoming values to the same
12170 if (VecIn2.getValueType() != VecIn1.getValueType() ||
12171 VecIn1.getValueType() != VT)
12174 // Return the new VECTOR_SHUFFLE node.
12178 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12184 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12185 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12186 EVT OpVT = N->getOperand(0).getValueType();
12188 // If the operands are legal vectors, leave them alone.
12189 if (TLI.isTypeLegal(OpVT))
12193 EVT VT = N->getValueType(0);
12194 SmallVector<SDValue, 8> Ops;
12196 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12197 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12199 // Keep track of what we encounter.
12200 bool AnyInteger = false;
12201 bool AnyFP = false;
12202 for (const SDValue &Op : N->ops()) {
12203 if (ISD::BITCAST == Op.getOpcode() &&
12204 !Op.getOperand(0).getValueType().isVector())
12205 Ops.push_back(Op.getOperand(0));
12206 else if (ISD::UNDEF == Op.getOpcode())
12207 Ops.push_back(ScalarUndef);
12211 // Note whether we encounter an integer or floating point scalar.
12212 // If it's neither, bail out, it could be something weird like x86mmx.
12213 EVT LastOpVT = Ops.back().getValueType();
12214 if (LastOpVT.isFloatingPoint())
12216 else if (LastOpVT.isInteger())
12222 // If any of the operands is a floating point scalar bitcast to a vector,
12223 // use floating point types throughout, and bitcast everything.
12224 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12226 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12227 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12229 for (SDValue &Op : Ops) {
12230 if (Op.getValueType() == SVT)
12232 if (Op.getOpcode() == ISD::UNDEF)
12235 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12240 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12241 VT.getSizeInBits() / SVT.getSizeInBits());
12242 return DAG.getNode(ISD::BITCAST, DL, VT,
12243 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12246 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12247 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12248 // most two distinct vectors the same size as the result, attempt to turn this
12249 // into a legal shuffle.
12250 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12251 EVT VT = N->getValueType(0);
12252 EVT OpVT = N->getOperand(0).getValueType();
12253 int NumElts = VT.getVectorNumElements();
12254 int NumOpElts = OpVT.getVectorNumElements();
12256 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12257 SmallVector<int, 8> Mask;
12259 for (SDValue Op : N->ops()) {
12260 // Peek through any bitcast.
12261 while (Op.getOpcode() == ISD::BITCAST)
12262 Op = Op.getOperand(0);
12264 // UNDEF nodes convert to UNDEF shuffle mask values.
12265 if (Op.getOpcode() == ISD::UNDEF) {
12266 Mask.append((unsigned)NumOpElts, -1);
12270 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12273 // What vector are we extracting the subvector from and at what index?
12274 SDValue ExtVec = Op.getOperand(0);
12276 // We want the EVT of the original extraction to correctly scale the
12277 // extraction index.
12278 EVT ExtVT = ExtVec.getValueType();
12280 // Peek through any bitcast.
12281 while (ExtVec.getOpcode() == ISD::BITCAST)
12282 ExtVec = ExtVec.getOperand(0);
12284 // UNDEF nodes convert to UNDEF shuffle mask values.
12285 if (ExtVec.getOpcode() == ISD::UNDEF) {
12286 Mask.append((unsigned)NumOpElts, -1);
12290 if (!isa<ConstantSDNode>(Op.getOperand(1)))
12292 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12294 // Ensure that we are extracting a subvector from a vector the same
12295 // size as the result.
12296 if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12299 // Scale the subvector index to account for any bitcast.
12300 int NumExtElts = ExtVT.getVectorNumElements();
12301 if (0 == (NumExtElts % NumElts))
12302 ExtIdx /= (NumExtElts / NumElts);
12303 else if (0 == (NumElts % NumExtElts))
12304 ExtIdx *= (NumElts / NumExtElts);
12308 // At most we can reference 2 inputs in the final shuffle.
12309 if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) {
12311 for (int i = 0; i != NumOpElts; ++i)
12312 Mask.push_back(i + ExtIdx);
12313 } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) {
12315 for (int i = 0; i != NumOpElts; ++i)
12316 Mask.push_back(i + ExtIdx + NumElts);
12322 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
12325 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
12326 DAG.getBitcast(VT, SV1), Mask);
12329 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12330 // If we only have one input vector, we don't need to do any concatenation.
12331 if (N->getNumOperands() == 1)
12332 return N->getOperand(0);
12334 // Check if all of the operands are undefs.
12335 EVT VT = N->getValueType(0);
12336 if (ISD::allOperandsUndef(N))
12337 return DAG.getUNDEF(VT);
12339 // Optimize concat_vectors where all but the first of the vectors are undef.
12340 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12341 return Op.getOpcode() == ISD::UNDEF;
12343 SDValue In = N->getOperand(0);
12344 assert(In.getValueType().isVector() && "Must concat vectors");
12346 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12347 if (In->getOpcode() == ISD::BITCAST &&
12348 !In->getOperand(0)->getValueType(0).isVector()) {
12349 SDValue Scalar = In->getOperand(0);
12351 // If the bitcast type isn't legal, it might be a trunc of a legal type;
12352 // look through the trunc so we can still do the transform:
12353 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12354 if (Scalar->getOpcode() == ISD::TRUNCATE &&
12355 !TLI.isTypeLegal(Scalar.getValueType()) &&
12356 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12357 Scalar = Scalar->getOperand(0);
12359 EVT SclTy = Scalar->getValueType(0);
12361 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12364 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12365 VT.getSizeInBits() / SclTy.getSizeInBits());
12366 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12369 SDLoc dl = SDLoc(N);
12370 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12371 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12375 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12376 // We have already tested above for an UNDEF only concatenation.
12377 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12378 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12379 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12380 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12382 bool AllBuildVectorsOrUndefs =
12383 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12384 if (AllBuildVectorsOrUndefs) {
12385 SmallVector<SDValue, 8> Opnds;
12386 EVT SVT = VT.getScalarType();
12389 if (!SVT.isFloatingPoint()) {
12390 // If BUILD_VECTOR are from built from integer, they may have different
12391 // operand types. Get the smallest type and truncate all operands to it.
12392 bool FoundMinVT = false;
12393 for (const SDValue &Op : N->ops())
12394 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12395 EVT OpSVT = Op.getOperand(0)->getValueType(0);
12396 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12399 assert(FoundMinVT && "Concat vector type mismatch");
12402 for (const SDValue &Op : N->ops()) {
12403 EVT OpVT = Op.getValueType();
12404 unsigned NumElts = OpVT.getVectorNumElements();
12406 if (ISD::UNDEF == Op.getOpcode())
12407 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12409 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12410 if (SVT.isFloatingPoint()) {
12411 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12412 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12414 for (unsigned i = 0; i != NumElts; ++i)
12416 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12421 assert(VT.getVectorNumElements() == Opnds.size() &&
12422 "Concat vector type mismatch");
12423 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12426 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12427 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12430 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
12431 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
12432 if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
12435 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12436 // nodes often generate nop CONCAT_VECTOR nodes.
12437 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12438 // place the incoming vectors at the exact same location.
12439 SDValue SingleSource = SDValue();
12440 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12442 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12443 SDValue Op = N->getOperand(i);
12445 if (Op.getOpcode() == ISD::UNDEF)
12448 // Check if this is the identity extract:
12449 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12452 // Find the single incoming vector for the extract_subvector.
12453 if (SingleSource.getNode()) {
12454 if (Op.getOperand(0) != SingleSource)
12457 SingleSource = Op.getOperand(0);
12459 // Check the source type is the same as the type of the result.
12460 // If not, this concat may extend the vector, so we can not
12461 // optimize it away.
12462 if (SingleSource.getValueType() != N->getValueType(0))
12466 unsigned IdentityIndex = i * PartNumElem;
12467 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12468 // The extract index must be constant.
12472 // Check that we are reading from the identity index.
12473 if (CS->getZExtValue() != IdentityIndex)
12477 if (SingleSource.getNode())
12478 return SingleSource;
12483 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12484 EVT NVT = N->getValueType(0);
12485 SDValue V = N->getOperand(0);
12487 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12489 // (extract_subvec (concat V1, V2, ...), i)
12492 // Only operand 0 is checked as 'concat' assumes all inputs of the same
12494 if (V->getOperand(0).getValueType() != NVT)
12496 unsigned Idx = N->getConstantOperandVal(1);
12497 unsigned NumElems = NVT.getVectorNumElements();
12498 assert((Idx % NumElems) == 0 &&
12499 "IDX in concat is not a multiple of the result vector length.");
12500 return V->getOperand(Idx / NumElems);
12504 if (V->getOpcode() == ISD::BITCAST)
12505 V = V.getOperand(0);
12507 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12509 // Handle only simple case where vector being inserted and vector
12510 // being extracted are of same type, and are half size of larger vectors.
12511 EVT BigVT = V->getOperand(0).getValueType();
12512 EVT SmallVT = V->getOperand(1).getValueType();
12513 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12516 // Only handle cases where both indexes are constants with the same type.
12517 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12518 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12520 if (InsIdx && ExtIdx &&
12521 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12522 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12524 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12526 // indices are equal or bit offsets are equal => V1
12527 // otherwise => (extract_subvec V1, ExtIdx)
12528 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12529 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12530 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12531 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12532 DAG.getNode(ISD::BITCAST, dl,
12533 N->getOperand(0).getValueType(),
12534 V->getOperand(0)), N->getOperand(1));
12541 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12542 SDValue V, SelectionDAG &DAG) {
12544 EVT VT = V.getValueType();
12546 switch (V.getOpcode()) {
12550 case ISD::CONCAT_VECTORS: {
12551 EVT OpVT = V->getOperand(0).getValueType();
12552 int OpSize = OpVT.getVectorNumElements();
12553 SmallBitVector OpUsedElements(OpSize, false);
12554 bool FoundSimplification = false;
12555 SmallVector<SDValue, 4> NewOps;
12556 NewOps.reserve(V->getNumOperands());
12557 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12558 SDValue Op = V->getOperand(i);
12559 bool OpUsed = false;
12560 for (int j = 0; j < OpSize; ++j)
12561 if (UsedElements[i * OpSize + j]) {
12562 OpUsedElements[j] = true;
12566 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12567 : DAG.getUNDEF(OpVT));
12568 FoundSimplification |= Op == NewOps.back();
12569 OpUsedElements.reset();
12571 if (FoundSimplification)
12572 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12576 case ISD::INSERT_SUBVECTOR: {
12577 SDValue BaseV = V->getOperand(0);
12578 SDValue SubV = V->getOperand(1);
12579 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12583 int SubSize = SubV.getValueType().getVectorNumElements();
12584 int Idx = IdxN->getZExtValue();
12585 bool SubVectorUsed = false;
12586 SmallBitVector SubUsedElements(SubSize, false);
12587 for (int i = 0; i < SubSize; ++i)
12588 if (UsedElements[i + Idx]) {
12589 SubVectorUsed = true;
12590 SubUsedElements[i] = true;
12591 UsedElements[i + Idx] = false;
12594 // Now recurse on both the base and sub vectors.
12595 SDValue SimplifiedSubV =
12597 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12598 : DAG.getUNDEF(SubV.getValueType());
12599 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12600 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12601 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12602 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12608 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12609 SDValue N1, SelectionDAG &DAG) {
12610 EVT VT = SVN->getValueType(0);
12611 int NumElts = VT.getVectorNumElements();
12612 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12613 for (int M : SVN->getMask())
12614 if (M >= 0 && M < NumElts)
12615 N0UsedElements[M] = true;
12616 else if (M >= NumElts)
12617 N1UsedElements[M - NumElts] = true;
12619 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12620 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12621 if (S0 == N0 && S1 == N1)
12624 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12627 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12628 // or turn a shuffle of a single concat into simpler shuffle then concat.
12629 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12630 EVT VT = N->getValueType(0);
12631 unsigned NumElts = VT.getVectorNumElements();
12633 SDValue N0 = N->getOperand(0);
12634 SDValue N1 = N->getOperand(1);
12635 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12637 SmallVector<SDValue, 4> Ops;
12638 EVT ConcatVT = N0.getOperand(0).getValueType();
12639 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12640 unsigned NumConcats = NumElts / NumElemsPerConcat;
12642 // Special case: shuffle(concat(A,B)) can be more efficiently represented
12643 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12644 // half vector elements.
12645 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12646 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12647 SVN->getMask().end(), [](int i) { return i == -1; })) {
12648 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12649 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12650 N1 = DAG.getUNDEF(ConcatVT);
12651 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12654 // Look at every vector that's inserted. We're looking for exact
12655 // subvector-sized copies from a concatenated vector
12656 for (unsigned I = 0; I != NumConcats; ++I) {
12657 // Make sure we're dealing with a copy.
12658 unsigned Begin = I * NumElemsPerConcat;
12659 bool AllUndef = true, NoUndef = true;
12660 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12661 if (SVN->getMaskElt(J) >= 0)
12668 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12671 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12672 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12675 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12676 if (FirstElt < N0.getNumOperands())
12677 Ops.push_back(N0.getOperand(FirstElt));
12679 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12681 } else if (AllUndef) {
12682 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12683 } else { // Mixed with general masks and undefs, can't do optimization.
12688 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12691 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12692 EVT VT = N->getValueType(0);
12693 unsigned NumElts = VT.getVectorNumElements();
12695 SDValue N0 = N->getOperand(0);
12696 SDValue N1 = N->getOperand(1);
12698 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12700 // Canonicalize shuffle undef, undef -> undef
12701 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12702 return DAG.getUNDEF(VT);
12704 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12706 // Canonicalize shuffle v, v -> v, undef
12708 SmallVector<int, 8> NewMask;
12709 for (unsigned i = 0; i != NumElts; ++i) {
12710 int Idx = SVN->getMaskElt(i);
12711 if (Idx >= (int)NumElts) Idx -= NumElts;
12712 NewMask.push_back(Idx);
12714 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12718 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
12719 if (N0.getOpcode() == ISD::UNDEF) {
12720 SmallVector<int, 8> NewMask;
12721 for (unsigned i = 0; i != NumElts; ++i) {
12722 int Idx = SVN->getMaskElt(i);
12724 if (Idx >= (int)NumElts)
12727 Idx = -1; // remove reference to lhs
12729 NewMask.push_back(Idx);
12731 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12735 // Remove references to rhs if it is undef
12736 if (N1.getOpcode() == ISD::UNDEF) {
12737 bool Changed = false;
12738 SmallVector<int, 8> NewMask;
12739 for (unsigned i = 0; i != NumElts; ++i) {
12740 int Idx = SVN->getMaskElt(i);
12741 if (Idx >= (int)NumElts) {
12745 NewMask.push_back(Idx);
12748 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12751 // If it is a splat, check if the argument vector is another splat or a
12753 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12754 SDNode *V = N0.getNode();
12756 // If this is a bit convert that changes the element type of the vector but
12757 // not the number of vector elements, look through it. Be careful not to
12758 // look though conversions that change things like v4f32 to v2f64.
12759 if (V->getOpcode() == ISD::BITCAST) {
12760 SDValue ConvInput = V->getOperand(0);
12761 if (ConvInput.getValueType().isVector() &&
12762 ConvInput.getValueType().getVectorNumElements() == NumElts)
12763 V = ConvInput.getNode();
12766 if (V->getOpcode() == ISD::BUILD_VECTOR) {
12767 assert(V->getNumOperands() == NumElts &&
12768 "BUILD_VECTOR has wrong number of operands");
12770 bool AllSame = true;
12771 for (unsigned i = 0; i != NumElts; ++i) {
12772 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12773 Base = V->getOperand(i);
12777 // Splat of <u, u, u, u>, return <u, u, u, u>
12778 if (!Base.getNode())
12780 for (unsigned i = 0; i != NumElts; ++i) {
12781 if (V->getOperand(i) != Base) {
12786 // Splat of <x, x, x, x>, return <x, x, x, x>
12790 // Canonicalize any other splat as a build_vector.
12791 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12792 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12793 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12794 V->getValueType(0), Ops);
12796 // We may have jumped through bitcasts, so the type of the
12797 // BUILD_VECTOR may not match the type of the shuffle.
12798 if (V->getValueType(0) != VT)
12799 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12804 // There are various patterns used to build up a vector from smaller vectors,
12805 // subvectors, or elements. Scan chains of these and replace unused insertions
12806 // or components with undef.
12807 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12810 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12811 Level < AfterLegalizeVectorOps &&
12812 (N1.getOpcode() == ISD::UNDEF ||
12813 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12814 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12815 SDValue V = partitionShuffleOfConcats(N, DAG);
12821 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12822 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12823 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12824 SmallVector<SDValue, 8> Ops;
12825 for (int M : SVN->getMask()) {
12826 SDValue Op = DAG.getUNDEF(VT.getScalarType());
12828 int Idx = M % NumElts;
12829 SDValue &S = (M < (int)NumElts ? N0 : N1);
12830 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12831 Op = S.getOperand(Idx);
12832 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12834 Op = S.getOperand(0);
12836 // Operand can't be combined - bail out.
12842 if (Ops.size() == VT.getVectorNumElements()) {
12843 // BUILD_VECTOR requires all inputs to be of the same type, find the
12844 // maximum type and extend them all.
12845 EVT SVT = VT.getScalarType();
12846 if (SVT.isInteger())
12847 for (SDValue &Op : Ops)
12848 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12849 if (SVT != VT.getScalarType())
12850 for (SDValue &Op : Ops)
12851 Op = TLI.isZExtFree(Op.getValueType(), SVT)
12852 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12853 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12854 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12858 // If this shuffle only has a single input that is a bitcasted shuffle,
12859 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12860 // back to their original types.
12861 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12862 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12863 TLI.isTypeLegal(VT)) {
12865 // Peek through the bitcast only if there is one user.
12867 while (BC0.getOpcode() == ISD::BITCAST) {
12868 if (!BC0.hasOneUse())
12870 BC0 = BC0.getOperand(0);
12873 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12875 return SmallVector<int, 8>(Mask.begin(), Mask.end());
12877 SmallVector<int, 8> NewMask;
12879 for (int s = 0; s != Scale; ++s)
12880 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12884 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12885 EVT SVT = VT.getScalarType();
12886 EVT InnerVT = BC0->getValueType(0);
12887 EVT InnerSVT = InnerVT.getScalarType();
12889 // Determine which shuffle works with the smaller scalar type.
12890 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12891 EVT ScaleSVT = ScaleVT.getScalarType();
12893 if (TLI.isTypeLegal(ScaleVT) &&
12894 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12895 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12897 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12898 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12900 // Scale the shuffle masks to the smaller scalar type.
12901 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12902 SmallVector<int, 8> InnerMask =
12903 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12904 SmallVector<int, 8> OuterMask =
12905 ScaleShuffleMask(SVN->getMask(), OuterScale);
12907 // Merge the shuffle masks.
12908 SmallVector<int, 8> NewMask;
12909 for (int M : OuterMask)
12910 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12912 // Test for shuffle mask legality over both commutations.
12913 SDValue SV0 = BC0->getOperand(0);
12914 SDValue SV1 = BC0->getOperand(1);
12915 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12917 std::swap(SV0, SV1);
12918 ShuffleVectorSDNode::commuteMask(NewMask);
12919 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12923 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12924 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12925 return DAG.getNode(
12926 ISD::BITCAST, SDLoc(N), VT,
12927 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12933 // Canonicalize shuffles according to rules:
12934 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12935 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12936 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12937 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12938 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12939 TLI.isTypeLegal(VT)) {
12940 // The incoming shuffle must be of the same type as the result of the
12941 // current shuffle.
12942 assert(N1->getOperand(0).getValueType() == VT &&
12943 "Shuffle types don't match");
12945 SDValue SV0 = N1->getOperand(0);
12946 SDValue SV1 = N1->getOperand(1);
12947 bool HasSameOp0 = N0 == SV0;
12948 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12949 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12950 // Commute the operands of this shuffle so that next rule
12952 return DAG.getCommutedVectorShuffle(*SVN);
12955 // Try to fold according to rules:
12956 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12957 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12958 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12959 // Don't try to fold shuffles with illegal type.
12960 // Only fold if this shuffle is the only user of the other shuffle.
12961 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12962 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12963 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12965 // The incoming shuffle must be of the same type as the result of the
12966 // current shuffle.
12967 assert(OtherSV->getOperand(0).getValueType() == VT &&
12968 "Shuffle types don't match");
12971 SmallVector<int, 4> Mask;
12972 // Compute the combined shuffle mask for a shuffle with SV0 as the first
12973 // operand, and SV1 as the second operand.
12974 for (unsigned i = 0; i != NumElts; ++i) {
12975 int Idx = SVN->getMaskElt(i);
12977 // Propagate Undef.
12978 Mask.push_back(Idx);
12982 SDValue CurrentVec;
12983 if (Idx < (int)NumElts) {
12984 // This shuffle index refers to the inner shuffle N0. Lookup the inner
12985 // shuffle mask to identify which vector is actually referenced.
12986 Idx = OtherSV->getMaskElt(Idx);
12988 // Propagate Undef.
12989 Mask.push_back(Idx);
12993 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12994 : OtherSV->getOperand(1);
12996 // This shuffle index references an element within N1.
13000 // Simple case where 'CurrentVec' is UNDEF.
13001 if (CurrentVec.getOpcode() == ISD::UNDEF) {
13002 Mask.push_back(-1);
13006 // Canonicalize the shuffle index. We don't know yet if CurrentVec
13007 // will be the first or second operand of the combined shuffle.
13008 Idx = Idx % NumElts;
13009 if (!SV0.getNode() || SV0 == CurrentVec) {
13010 // Ok. CurrentVec is the left hand side.
13011 // Update the mask accordingly.
13013 Mask.push_back(Idx);
13017 // Bail out if we cannot convert the shuffle pair into a single shuffle.
13018 if (SV1.getNode() && SV1 != CurrentVec)
13021 // Ok. CurrentVec is the right hand side.
13022 // Update the mask accordingly.
13024 Mask.push_back(Idx + NumElts);
13027 // Check if all indices in Mask are Undef. In case, propagate Undef.
13028 bool isUndefMask = true;
13029 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13030 isUndefMask &= Mask[i] < 0;
13033 return DAG.getUNDEF(VT);
13035 if (!SV0.getNode())
13036 SV0 = DAG.getUNDEF(VT);
13037 if (!SV1.getNode())
13038 SV1 = DAG.getUNDEF(VT);
13040 // Avoid introducing shuffles with illegal mask.
13041 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13042 ShuffleVectorSDNode::commuteMask(Mask);
13044 if (!TLI.isShuffleMaskLegal(Mask, VT))
13047 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13048 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13049 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13050 std::swap(SV0, SV1);
13053 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13054 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13055 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13056 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13062 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13063 SDValue InVal = N->getOperand(0);
13064 EVT VT = N->getValueType(0);
13066 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13067 // with a VECTOR_SHUFFLE.
13068 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13069 SDValue InVec = InVal->getOperand(0);
13070 SDValue EltNo = InVal->getOperand(1);
13072 // FIXME: We could support implicit truncation if the shuffle can be
13073 // scaled to a smaller vector scalar type.
13074 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13075 if (C0 && VT == InVec.getValueType() &&
13076 VT.getScalarType() == InVal.getValueType()) {
13077 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13078 int Elt = C0->getZExtValue();
13081 if (TLI.isShuffleMaskLegal(NewMask, VT))
13082 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13090 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13091 SDValue N0 = N->getOperand(0);
13092 SDValue N2 = N->getOperand(2);
13094 // If the input vector is a concatenation, and the insert replaces
13095 // one of the halves, we can optimize into a single concat_vectors.
13096 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13097 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13098 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13099 EVT VT = N->getValueType(0);
13101 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13102 // (concat_vectors Z, Y)
13104 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13105 N->getOperand(1), N0.getOperand(1));
13107 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13108 // (concat_vectors X, Z)
13109 if (InsIdx == VT.getVectorNumElements()/2)
13110 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13111 N0.getOperand(0), N->getOperand(1));
13117 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13118 SDValue N0 = N->getOperand(0);
13120 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13121 if (N0->getOpcode() == ISD::FP16_TO_FP)
13122 return N0->getOperand(0);
13127 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13128 SDValue N0 = N->getOperand(0);
13130 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13131 if (N0->getOpcode() == ISD::AND) {
13132 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13133 if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13134 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13142 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13143 /// with the destination vector and a zero vector.
13144 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13145 /// vector_shuffle V, Zero, <0, 4, 2, 4>
13146 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13147 EVT VT = N->getValueType(0);
13148 SDValue LHS = N->getOperand(0);
13149 SDValue RHS = N->getOperand(1);
13152 // Make sure we're not running after operation legalization where it
13153 // may have custom lowered the vector shuffles.
13154 if (LegalOperations)
13157 if (N->getOpcode() != ISD::AND)
13160 if (RHS.getOpcode() == ISD::BITCAST)
13161 RHS = RHS.getOperand(0);
13163 if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13166 EVT RVT = RHS.getValueType();
13167 unsigned NumElts = RHS.getNumOperands();
13169 // Attempt to create a valid clear mask, splitting the mask into
13170 // sub elements and checking to see if each is
13171 // all zeros or all ones - suitable for shuffle masking.
13172 auto BuildClearMask = [&](int Split) {
13173 int NumSubElts = NumElts * Split;
13174 int NumSubBits = RVT.getScalarSizeInBits() / Split;
13176 SmallVector<int, 8> Indices;
13177 for (int i = 0; i != NumSubElts; ++i) {
13178 int EltIdx = i / Split;
13179 int SubIdx = i % Split;
13180 SDValue Elt = RHS.getOperand(EltIdx);
13181 if (Elt.getOpcode() == ISD::UNDEF) {
13182 Indices.push_back(-1);
13187 if (isa<ConstantSDNode>(Elt))
13188 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13189 else if (isa<ConstantFPSDNode>(Elt))
13190 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13194 // Extract the sub element from the constant bit mask.
13195 if (DAG.getDataLayout().isBigEndian()) {
13196 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13198 Bits = Bits.lshr(SubIdx * NumSubBits);
13202 Bits = Bits.trunc(NumSubBits);
13204 if (Bits.isAllOnesValue())
13205 Indices.push_back(i);
13206 else if (Bits == 0)
13207 Indices.push_back(i + NumSubElts);
13212 // Let's see if the target supports this vector_shuffle.
13213 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13214 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13215 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13218 SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13219 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13220 DAG.getBitcast(ClearVT, LHS),
13221 Zero, &Indices[0]));
13224 // Determine maximum split level (byte level masking).
13226 if (RVT.getScalarSizeInBits() % 8 == 0)
13227 MaxSplit = RVT.getScalarSizeInBits() / 8;
13229 for (int Split = 1; Split <= MaxSplit; ++Split)
13230 if (RVT.getScalarSizeInBits() % Split == 0)
13231 if (SDValue S = BuildClearMask(Split))
13237 /// Visit a binary vector operation, like ADD.
13238 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13239 assert(N->getValueType(0).isVector() &&
13240 "SimplifyVBinOp only works on vectors!");
13242 SDValue LHS = N->getOperand(0);
13243 SDValue RHS = N->getOperand(1);
13245 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
13247 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
13248 RHS.getOpcode() == ISD::BUILD_VECTOR) {
13249 // Check if both vectors are constants. If not bail out.
13250 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
13251 cast<BuildVectorSDNode>(RHS)->isConstant()))
13254 SmallVector<SDValue, 8> Ops;
13255 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
13256 SDValue LHSOp = LHS.getOperand(i);
13257 SDValue RHSOp = RHS.getOperand(i);
13259 // Can't fold divide by zero.
13260 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
13261 N->getOpcode() == ISD::FDIV) {
13262 if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP &&
13263 cast<ConstantFPSDNode>(RHSOp.getNode())->isZero()))
13267 EVT VT = LHSOp.getValueType();
13268 EVT RVT = RHSOp.getValueType();
13270 // Integer BUILD_VECTOR operands may have types larger than the element
13271 // size (e.g., when the element type is not legal). Prior to type
13272 // legalization, the types may not match between the two BUILD_VECTORS.
13273 // Truncate one of the operands to make them match.
13274 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
13275 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
13277 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
13281 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
13283 if (FoldOp.getOpcode() != ISD::UNDEF &&
13284 FoldOp.getOpcode() != ISD::Constant &&
13285 FoldOp.getOpcode() != ISD::ConstantFP)
13287 Ops.push_back(FoldOp);
13288 AddToWorklist(FoldOp.getNode());
13291 if (Ops.size() == LHS.getNumOperands())
13292 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
13295 // Try to convert a constant mask AND into a shuffle clear mask.
13296 if (SDValue Shuffle = XformToShuffleWithZero(N))
13299 // Type legalization might introduce new shuffles in the DAG.
13300 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13301 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
13302 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13303 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13304 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13305 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13306 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13307 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13309 if (SVN0->getMask().equals(SVN1->getMask())) {
13310 EVT VT = N->getValueType(0);
13311 SDValue UndefVector = LHS.getOperand(1);
13312 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13313 LHS.getOperand(0), RHS.getOperand(0));
13314 AddUsersToWorklist(N);
13315 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13316 &SVN0->getMask()[0]);
13323 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13324 SDValue N1, SDValue N2){
13325 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13327 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13328 cast<CondCodeSDNode>(N0.getOperand(2))->get());
13330 // If we got a simplified select_cc node back from SimplifySelectCC, then
13331 // break it down into a new SETCC node, and a new SELECT node, and then return
13332 // the SELECT node, since we were called with a SELECT node.
13333 if (SCC.getNode()) {
13334 // Check to see if we got a select_cc back (to turn into setcc/select).
13335 // Otherwise, just return whatever node we got back, like fabs.
13336 if (SCC.getOpcode() == ISD::SELECT_CC) {
13337 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13339 SCC.getOperand(0), SCC.getOperand(1),
13340 SCC.getOperand(4));
13341 AddToWorklist(SETCC.getNode());
13342 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13343 SCC.getOperand(2), SCC.getOperand(3));
13351 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13352 /// being selected between, see if we can simplify the select. Callers of this
13353 /// should assume that TheSelect is deleted if this returns true. As such, they
13354 /// should return the appropriate thing (e.g. the node) back to the top-level of
13355 /// the DAG combiner loop to avoid it being looked at.
13356 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13359 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13360 // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13361 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13362 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13363 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13364 SDValue Sqrt = RHS;
13367 const ConstantFPSDNode *NegZero = nullptr;
13369 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13370 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13371 CmpLHS = TheSelect->getOperand(0);
13372 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13374 // SELECT or VSELECT
13375 SDValue Cmp = TheSelect->getOperand(0);
13376 if (Cmp.getOpcode() == ISD::SETCC) {
13377 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13378 CmpLHS = Cmp.getOperand(0);
13379 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13382 if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13383 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13384 CC == ISD::SETULT || CC == ISD::SETLT)) {
13385 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13386 CombineTo(TheSelect, Sqrt);
13391 // Cannot simplify select with vector condition
13392 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13394 // If this is a select from two identical things, try to pull the operation
13395 // through the select.
13396 if (LHS.getOpcode() != RHS.getOpcode() ||
13397 !LHS.hasOneUse() || !RHS.hasOneUse())
13400 // If this is a load and the token chain is identical, replace the select
13401 // of two loads with a load through a select of the address to load from.
13402 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13403 // constants have been dropped into the constant pool.
13404 if (LHS.getOpcode() == ISD::LOAD) {
13405 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13406 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13408 // Token chains must be identical.
13409 if (LHS.getOperand(0) != RHS.getOperand(0) ||
13410 // Do not let this transformation reduce the number of volatile loads.
13411 LLD->isVolatile() || RLD->isVolatile() ||
13412 // FIXME: If either is a pre/post inc/dec load,
13413 // we'd need to split out the address adjustment.
13414 LLD->isIndexed() || RLD->isIndexed() ||
13415 // If this is an EXTLOAD, the VT's must match.
13416 LLD->getMemoryVT() != RLD->getMemoryVT() ||
13417 // If this is an EXTLOAD, the kind of extension must match.
13418 (LLD->getExtensionType() != RLD->getExtensionType() &&
13419 // The only exception is if one of the extensions is anyext.
13420 LLD->getExtensionType() != ISD::EXTLOAD &&
13421 RLD->getExtensionType() != ISD::EXTLOAD) ||
13422 // FIXME: this discards src value information. This is
13423 // over-conservative. It would be beneficial to be able to remember
13424 // both potential memory locations. Since we are discarding
13425 // src value info, don't do the transformation if the memory
13426 // locations are not in the default address space.
13427 LLD->getPointerInfo().getAddrSpace() != 0 ||
13428 RLD->getPointerInfo().getAddrSpace() != 0 ||
13429 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13430 LLD->getBasePtr().getValueType()))
13433 // Check that the select condition doesn't reach either load. If so,
13434 // folding this will induce a cycle into the DAG. If not, this is safe to
13435 // xform, so create a select of the addresses.
13437 if (TheSelect->getOpcode() == ISD::SELECT) {
13438 SDNode *CondNode = TheSelect->getOperand(0).getNode();
13439 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13440 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13442 // The loads must not depend on one another.
13443 if (LLD->isPredecessorOf(RLD) ||
13444 RLD->isPredecessorOf(LLD))
13446 Addr = DAG.getSelect(SDLoc(TheSelect),
13447 LLD->getBasePtr().getValueType(),
13448 TheSelect->getOperand(0), LLD->getBasePtr(),
13449 RLD->getBasePtr());
13450 } else { // Otherwise SELECT_CC
13451 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13452 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13454 if ((LLD->hasAnyUseOfValue(1) &&
13455 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13456 (RLD->hasAnyUseOfValue(1) &&
13457 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13460 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13461 LLD->getBasePtr().getValueType(),
13462 TheSelect->getOperand(0),
13463 TheSelect->getOperand(1),
13464 LLD->getBasePtr(), RLD->getBasePtr(),
13465 TheSelect->getOperand(4));
13469 // It is safe to replace the two loads if they have different alignments,
13470 // but the new load must be the minimum (most restrictive) alignment of the
13472 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13473 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13474 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13475 Load = DAG.getLoad(TheSelect->getValueType(0),
13477 // FIXME: Discards pointer and AA info.
13478 LLD->getChain(), Addr, MachinePointerInfo(),
13479 LLD->isVolatile(), LLD->isNonTemporal(),
13480 isInvariant, Alignment);
13482 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13483 RLD->getExtensionType() : LLD->getExtensionType(),
13485 TheSelect->getValueType(0),
13486 // FIXME: Discards pointer and AA info.
13487 LLD->getChain(), Addr, MachinePointerInfo(),
13488 LLD->getMemoryVT(), LLD->isVolatile(),
13489 LLD->isNonTemporal(), isInvariant, Alignment);
13492 // Users of the select now use the result of the load.
13493 CombineTo(TheSelect, Load);
13495 // Users of the old loads now use the new load's chain. We know the
13496 // old-load value is dead now.
13497 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13498 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13505 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13506 /// where 'cond' is the comparison specified by CC.
13507 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13508 SDValue N2, SDValue N3,
13509 ISD::CondCode CC, bool NotExtCompare) {
13510 // (x ? y : y) -> y.
13511 if (N2 == N3) return N2;
13513 EVT VT = N2.getValueType();
13514 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13515 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13517 // Determine if the condition we're dealing with is constant
13518 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13519 N0, N1, CC, DL, false);
13520 if (SCC.getNode()) AddToWorklist(SCC.getNode());
13522 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13523 // fold select_cc true, x, y -> x
13524 // fold select_cc false, x, y -> y
13525 return !SCCC->isNullValue() ? N2 : N3;
13528 // Check to see if we can simplify the select into an fabs node
13529 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13530 // Allow either -0.0 or 0.0
13531 if (CFP->isZero()) {
13532 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13533 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13534 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13535 N2 == N3.getOperand(0))
13536 return DAG.getNode(ISD::FABS, DL, VT, N0);
13538 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13539 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13540 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13541 N2.getOperand(0) == N3)
13542 return DAG.getNode(ISD::FABS, DL, VT, N3);
13546 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13547 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13548 // in it. This is a win when the constant is not otherwise available because
13549 // it replaces two constant pool loads with one. We only do this if the FP
13550 // type is known to be legal, because if it isn't, then we are before legalize
13551 // types an we want the other legalization to happen first (e.g. to avoid
13552 // messing with soft float) and if the ConstantFP is not legal, because if
13553 // it is legal, we may not need to store the FP constant in a constant pool.
13554 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13555 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13556 if (TLI.isTypeLegal(N2.getValueType()) &&
13557 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13558 TargetLowering::Legal &&
13559 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13560 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13561 // If both constants have multiple uses, then we won't need to do an
13562 // extra load, they are likely around in registers for other users.
13563 (TV->hasOneUse() || FV->hasOneUse())) {
13564 Constant *Elts[] = {
13565 const_cast<ConstantFP*>(FV->getConstantFPValue()),
13566 const_cast<ConstantFP*>(TV->getConstantFPValue())
13568 Type *FPTy = Elts[0]->getType();
13569 const DataLayout &TD = DAG.getDataLayout();
13571 // Create a ConstantArray of the two constants.
13572 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13574 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
13575 TD.getPrefTypeAlignment(FPTy));
13576 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13578 // Get the offsets to the 0 and 1 element of the array so that we can
13579 // select between them.
13580 SDValue Zero = DAG.getIntPtrConstant(0, DL);
13581 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13582 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13584 SDValue Cond = DAG.getSetCC(DL,
13585 getSetCCResultType(N0.getValueType()),
13587 AddToWorklist(Cond.getNode());
13588 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13590 AddToWorklist(CstOffset.getNode());
13591 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13593 AddToWorklist(CPIdx.getNode());
13594 return DAG.getLoad(
13595 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13596 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13597 false, false, false, Alignment);
13601 // Check to see if we can perform the "gzip trick", transforming
13602 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13603 if (isNullConstant(N3) && CC == ISD::SETLT &&
13604 (isNullConstant(N1) || // (a < 0) ? b : 0
13605 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0
13606 EVT XType = N0.getValueType();
13607 EVT AType = N2.getValueType();
13608 if (XType.bitsGE(AType)) {
13609 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13610 // single-bit constant.
13611 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13612 unsigned ShCtV = N2C->getAPIntValue().logBase2();
13613 ShCtV = XType.getSizeInBits() - ShCtV - 1;
13614 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13615 getShiftAmountTy(N0.getValueType()));
13616 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13618 AddToWorklist(Shift.getNode());
13620 if (XType.bitsGT(AType)) {
13621 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13622 AddToWorklist(Shift.getNode());
13625 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13628 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13630 DAG.getConstant(XType.getSizeInBits() - 1,
13632 getShiftAmountTy(N0.getValueType())));
13633 AddToWorklist(Shift.getNode());
13635 if (XType.bitsGT(AType)) {
13636 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13637 AddToWorklist(Shift.getNode());
13640 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13644 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13645 // where y is has a single bit set.
13646 // A plaintext description would be, we can turn the SELECT_CC into an AND
13647 // when the condition can be materialized as an all-ones register. Any
13648 // single bit-test can be materialized as an all-ones register with
13649 // shift-left and shift-right-arith.
13650 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13651 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13652 SDValue AndLHS = N0->getOperand(0);
13653 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13654 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13655 // Shift the tested bit over the sign bit.
13656 APInt AndMask = ConstAndRHS->getAPIntValue();
13658 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13659 getShiftAmountTy(AndLHS.getValueType()));
13660 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13662 // Now arithmetic right shift it all the way over, so the result is either
13663 // all-ones, or zero.
13665 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13666 getShiftAmountTy(Shl.getValueType()));
13667 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13669 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13673 // fold select C, 16, 0 -> shl C, 4
13674 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13675 TLI.getBooleanContents(N0.getValueType()) ==
13676 TargetLowering::ZeroOrOneBooleanContent) {
13678 // If the caller doesn't want us to simplify this into a zext of a compare,
13680 if (NotExtCompare && N2C->isOne())
13683 // Get a SetCC of the condition
13684 // NOTE: Don't create a SETCC if it's not legal on this target.
13685 if (!LegalOperations ||
13686 TLI.isOperationLegal(ISD::SETCC,
13687 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13689 // cast from setcc result type to select result type
13691 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13693 if (N2.getValueType().bitsLT(SCC.getValueType()))
13694 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13695 N2.getValueType());
13697 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13698 N2.getValueType(), SCC);
13700 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13701 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13702 N2.getValueType(), SCC);
13705 AddToWorklist(SCC.getNode());
13706 AddToWorklist(Temp.getNode());
13711 // shl setcc result by log2 n2c
13712 return DAG.getNode(
13713 ISD::SHL, DL, N2.getValueType(), Temp,
13714 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13715 getShiftAmountTy(Temp.getValueType())));
13719 // Check to see if this is the equivalent of setcc
13720 // FIXME: Turn all of these into setcc if setcc if setcc is legal
13721 // otherwise, go ahead with the folds.
13722 if (0 && isNullConstant(N3) && isOneConstant(N2)) {
13723 EVT XType = N0.getValueType();
13724 if (!LegalOperations ||
13725 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13726 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13727 if (Res.getValueType() != VT)
13728 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13732 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13733 if (isNullConstant(N1) && CC == ISD::SETEQ &&
13734 (!LegalOperations ||
13735 TLI.isOperationLegal(ISD::CTLZ, XType))) {
13736 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13737 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13738 DAG.getConstant(Log2_32(XType.getSizeInBits()),
13740 getShiftAmountTy(Ctlz.getValueType())));
13742 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13743 if (isNullConstant(N1) && CC == ISD::SETGT) {
13745 SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13746 XType, DAG.getConstant(0, DL, XType), N0);
13747 SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13748 return DAG.getNode(ISD::SRL, DL, XType,
13749 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13750 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13751 getShiftAmountTy(XType)));
13753 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13754 if (isAllOnesConstant(N1) && CC == ISD::SETGT) {
13756 SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13757 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13758 getShiftAmountTy(N0.getValueType())));
13759 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13764 // Check to see if this is an integer abs.
13765 // select_cc setg[te] X, 0, X, -X ->
13766 // select_cc setgt X, -1, X, -X ->
13767 // select_cc setl[te] X, 0, -X, X ->
13768 // select_cc setlt X, 1, -X, X ->
13769 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13771 ConstantSDNode *SubC = nullptr;
13772 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13773 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13774 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13775 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13776 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13777 (N1C->isOne() && CC == ISD::SETLT)) &&
13778 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13779 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13781 EVT XType = N0.getValueType();
13782 if (SubC && SubC->isNullValue() && XType.isInteger()) {
13784 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13786 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13787 getShiftAmountTy(N0.getValueType())));
13788 SDValue Add = DAG.getNode(ISD::ADD, DL,
13790 AddToWorklist(Shift.getNode());
13791 AddToWorklist(Add.getNode());
13792 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13799 /// This is a stub for TargetLowering::SimplifySetCC.
13800 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13801 SDValue N1, ISD::CondCode Cond,
13802 SDLoc DL, bool foldBooleans) {
13803 TargetLowering::DAGCombinerInfo
13804 DagCombineInfo(DAG, Level, false, this);
13805 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13808 /// Given an ISD::SDIV node expressing a divide by constant, return
13809 /// a DAG expression to select that will generate the same value by multiplying
13810 /// by a magic number.
13811 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13812 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13813 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13817 // Avoid division by zero.
13818 if (C->isNullValue())
13821 std::vector<SDNode*> Built;
13823 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13825 for (SDNode *N : Built)
13830 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13831 /// DAG expression that will generate the same value by right shifting.
13832 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13833 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13837 // Avoid division by zero.
13838 if (C->isNullValue())
13841 std::vector<SDNode *> Built;
13842 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13844 for (SDNode *N : Built)
13849 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13850 /// expression that will generate the same value by multiplying by a magic
13852 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13853 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13854 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13858 // Avoid division by zero.
13859 if (C->isNullValue())
13862 std::vector<SDNode*> Built;
13864 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13866 for (SDNode *N : Built)
13871 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13872 if (Level >= AfterLegalizeDAG)
13875 // Expose the DAG combiner to the target combiner implementations.
13876 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13878 unsigned Iterations = 0;
13879 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13881 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13882 // For the reciprocal, we need to find the zero of the function:
13883 // F(X) = A X - 1 [which has a zero at X = 1/A]
13885 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13886 // does not require additional intermediate precision]
13887 EVT VT = Op.getValueType();
13889 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13891 AddToWorklist(Est.getNode());
13893 // Newton iterations: Est = Est + Est (1 - Arg * Est)
13894 for (unsigned i = 0; i < Iterations; ++i) {
13895 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13896 AddToWorklist(NewEst.getNode());
13898 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13899 AddToWorklist(NewEst.getNode());
13901 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13902 AddToWorklist(NewEst.getNode());
13904 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13905 AddToWorklist(Est.getNode());
13914 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13915 /// For the reciprocal sqrt, we need to find the zero of the function:
13916 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13918 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13919 /// As a result, we precompute A/2 prior to the iteration loop.
13920 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13921 unsigned Iterations) {
13922 EVT VT = Arg.getValueType();
13924 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13926 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13927 // this entire sequence requires only one FP constant.
13928 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13929 AddToWorklist(HalfArg.getNode());
13931 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13932 AddToWorklist(HalfArg.getNode());
13934 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13935 for (unsigned i = 0; i < Iterations; ++i) {
13936 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13937 AddToWorklist(NewEst.getNode());
13939 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13940 AddToWorklist(NewEst.getNode());
13942 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13943 AddToWorklist(NewEst.getNode());
13945 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13946 AddToWorklist(Est.getNode());
13951 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13952 /// For the reciprocal sqrt, we need to find the zero of the function:
13953 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13955 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13956 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13957 unsigned Iterations) {
13958 EVT VT = Arg.getValueType();
13960 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13961 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13963 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13964 for (unsigned i = 0; i < Iterations; ++i) {
13965 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13966 AddToWorklist(HalfEst.getNode());
13968 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13969 AddToWorklist(Est.getNode());
13971 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13972 AddToWorklist(Est.getNode());
13974 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13975 AddToWorklist(Est.getNode());
13977 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13978 AddToWorklist(Est.getNode());
13983 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13984 if (Level >= AfterLegalizeDAG)
13987 // Expose the DAG combiner to the target combiner implementations.
13988 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13989 unsigned Iterations = 0;
13990 bool UseOneConstNR = false;
13991 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13992 AddToWorklist(Est.getNode());
13994 Est = UseOneConstNR ?
13995 BuildRsqrtNROneConst(Op, Est, Iterations) :
13996 BuildRsqrtNRTwoConst(Op, Est, Iterations);
14004 /// Return true if base is a frame index, which is known not to alias with
14005 /// anything but itself. Provides base object and offset as results.
14006 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14007 const GlobalValue *&GV, const void *&CV) {
14008 // Assume it is a primitive operation.
14009 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14011 // If it's an adding a simple constant then integrate the offset.
14012 if (Base.getOpcode() == ISD::ADD) {
14013 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14014 Base = Base.getOperand(0);
14015 Offset += C->getZExtValue();
14019 // Return the underlying GlobalValue, and update the Offset. Return false
14020 // for GlobalAddressSDNode since the same GlobalAddress may be represented
14021 // by multiple nodes with different offsets.
14022 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14023 GV = G->getGlobal();
14024 Offset += G->getOffset();
14028 // Return the underlying Constant value, and update the Offset. Return false
14029 // for ConstantSDNodes since the same constant pool entry may be represented
14030 // by multiple nodes with different offsets.
14031 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14032 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14033 : (const void *)C->getConstVal();
14034 Offset += C->getOffset();
14037 // If it's any of the following then it can't alias with anything but itself.
14038 return isa<FrameIndexSDNode>(Base);
14041 /// Return true if there is any possibility that the two addresses overlap.
14042 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14043 // If they are the same then they must be aliases.
14044 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14046 // If they are both volatile then they cannot be reordered.
14047 if (Op0->isVolatile() && Op1->isVolatile()) return true;
14049 // If one operation reads from invariant memory, and the other may store, they
14050 // cannot alias. These should really be checking the equivalent of mayWrite,
14051 // but it only matters for memory nodes other than load /store.
14052 if (Op0->isInvariant() && Op1->writeMem())
14055 if (Op1->isInvariant() && Op0->writeMem())
14058 // Gather base node and offset information.
14059 SDValue Base1, Base2;
14060 int64_t Offset1, Offset2;
14061 const GlobalValue *GV1, *GV2;
14062 const void *CV1, *CV2;
14063 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14064 Base1, Offset1, GV1, CV1);
14065 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14066 Base2, Offset2, GV2, CV2);
14068 // If they have a same base address then check to see if they overlap.
14069 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14070 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14071 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14073 // It is possible for different frame indices to alias each other, mostly
14074 // when tail call optimization reuses return address slots for arguments.
14075 // To catch this case, look up the actual index of frame indices to compute
14076 // the real alias relationship.
14077 if (isFrameIndex1 && isFrameIndex2) {
14078 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14079 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14080 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14081 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14082 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14085 // Otherwise, if we know what the bases are, and they aren't identical, then
14086 // we know they cannot alias.
14087 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14090 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14091 // compared to the size and offset of the access, we may be able to prove they
14092 // do not alias. This check is conservative for now to catch cases created by
14093 // splitting vector types.
14094 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14095 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14096 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14097 Op1->getMemoryVT().getSizeInBits() >> 3) &&
14098 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14099 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14100 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14102 // There is no overlap between these relatively aligned accesses of similar
14103 // size, return no alias.
14104 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14105 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14109 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14111 : DAG.getSubtarget().useAA();
14113 if (CombinerAAOnlyFunc.getNumOccurrences() &&
14114 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14118 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14119 // Use alias analysis information.
14120 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14121 Op1->getSrcValueOffset());
14122 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14123 Op0->getSrcValueOffset() - MinOffset;
14124 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14125 Op1->getSrcValueOffset() - MinOffset;
14126 AliasResult AAResult =
14127 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14128 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14129 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14130 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14131 if (AAResult == NoAlias)
14135 // Otherwise we have to assume they alias.
14139 /// Walk up chain skipping non-aliasing memory nodes,
14140 /// looking for aliasing nodes and adding them to the Aliases vector.
14141 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14142 SmallVectorImpl<SDValue> &Aliases) {
14143 SmallVector<SDValue, 8> Chains; // List of chains to visit.
14144 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
14146 // Get alias information for node.
14147 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14150 Chains.push_back(OriginalChain);
14151 unsigned Depth = 0;
14153 // Look at each chain and determine if it is an alias. If so, add it to the
14154 // aliases list. If not, then continue up the chain looking for the next
14156 while (!Chains.empty()) {
14157 SDValue Chain = Chains.pop_back_val();
14159 // For TokenFactor nodes, look at each operand and only continue up the
14160 // chain until we find two aliases. If we've seen two aliases, assume we'll
14161 // find more and revert to original chain since the xform is unlikely to be
14164 // FIXME: The depth check could be made to return the last non-aliasing
14165 // chain we found before we hit a tokenfactor rather than the original
14167 if (Depth > 6 || Aliases.size() == 2) {
14169 Aliases.push_back(OriginalChain);
14173 // Don't bother if we've been before.
14174 if (!Visited.insert(Chain.getNode()).second)
14177 switch (Chain.getOpcode()) {
14178 case ISD::EntryToken:
14179 // Entry token is ideal chain operand, but handled in FindBetterChain.
14184 // Get alias information for Chain.
14185 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14186 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14188 // If chain is alias then stop here.
14189 if (!(IsLoad && IsOpLoad) &&
14190 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14191 Aliases.push_back(Chain);
14193 // Look further up the chain.
14194 Chains.push_back(Chain.getOperand(0));
14200 case ISD::TokenFactor:
14201 // We have to check each of the operands of the token factor for "small"
14202 // token factors, so we queue them up. Adding the operands to the queue
14203 // (stack) in reverse order maintains the original order and increases the
14204 // likelihood that getNode will find a matching token factor (CSE.)
14205 if (Chain.getNumOperands() > 16) {
14206 Aliases.push_back(Chain);
14209 for (unsigned n = Chain.getNumOperands(); n;)
14210 Chains.push_back(Chain.getOperand(--n));
14215 // For all other instructions we will just have to take what we can get.
14216 Aliases.push_back(Chain);
14221 // We need to be careful here to also search for aliases through the
14222 // value operand of a store, etc. Consider the following situation:
14224 // L1 = load Token1, %52
14225 // S1 = store Token1, L1, %51
14226 // L2 = load Token1, %52+8
14227 // S2 = store Token1, L2, %51+8
14228 // Token2 = Token(S1, S2)
14229 // L3 = load Token2, %53
14230 // S3 = store Token2, L3, %52
14231 // L4 = load Token2, %53+8
14232 // S4 = store Token2, L4, %52+8
14233 // If we search for aliases of S3 (which loads address %52), and we look
14234 // only through the chain, then we'll miss the trivial dependence on L1
14235 // (which also loads from %52). We then might change all loads and
14236 // stores to use Token1 as their chain operand, which could result in
14237 // copying %53 into %52 before copying %52 into %51 (which should
14240 // The problem is, however, that searching for such data dependencies
14241 // can become expensive, and the cost is not directly related to the
14242 // chain depth. Instead, we'll rule out such configurations here by
14243 // insisting that we've visited all chain users (except for users
14244 // of the original chain, which is not necessary). When doing this,
14245 // we need to look through nodes we don't care about (otherwise, things
14246 // like register copies will interfere with trivial cases).
14248 SmallVector<const SDNode *, 16> Worklist;
14249 for (const SDNode *N : Visited)
14250 if (N != OriginalChain.getNode())
14251 Worklist.push_back(N);
14253 while (!Worklist.empty()) {
14254 const SDNode *M = Worklist.pop_back_val();
14256 // We have already visited M, and want to make sure we've visited any uses
14257 // of M that we care about. For uses that we've not visisted, and don't
14258 // care about, queue them to the worklist.
14260 for (SDNode::use_iterator UI = M->use_begin(),
14261 UIE = M->use_end(); UI != UIE; ++UI)
14262 if (UI.getUse().getValueType() == MVT::Other &&
14263 Visited.insert(*UI).second) {
14264 if (isa<MemSDNode>(*UI)) {
14265 // We've not visited this use, and we care about it (it could have an
14266 // ordering dependency with the original node).
14268 Aliases.push_back(OriginalChain);
14272 // We've not visited this use, but we don't care about it. Mark it as
14273 // visited and enqueue it to the worklist.
14274 Worklist.push_back(*UI);
14279 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14280 /// (aliasing node.)
14281 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14282 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
14284 // Accumulate all the aliases to this node.
14285 GatherAllAliases(N, OldChain, Aliases);
14287 // If no operands then chain to entry token.
14288 if (Aliases.size() == 0)
14289 return DAG.getEntryNode();
14291 // If a single operand then chain to it. We don't need to revisit it.
14292 if (Aliases.size() == 1)
14295 // Construct a custom tailored token factor.
14296 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14299 /// This is the entry point for the file.
14300 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14301 CodeGenOpt::Level OptLevel) {
14302 /// This is the main entry point to this class.
14303 DAGCombiner(*this, AA, OptLevel).Run(Level);