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 /// Replaces all uses of the results of one DAG node with new values.
160 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
163 /// Replaces all uses of the results of one DAG node with new values.
164 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
165 return CombineTo(N, &Res, 1, AddTo);
168 /// Replaces all uses of the results of one DAG node with new values.
169 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
171 SDValue To[] = { Res0, Res1 };
172 return CombineTo(N, To, 2, AddTo);
175 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
179 /// Check the specified integer node value to see if it can be simplified or
180 /// if things it uses can be simplified by bit propagation.
181 /// If so, return true.
182 bool SimplifyDemandedBits(SDValue Op) {
183 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
184 APInt Demanded = APInt::getAllOnesValue(BitWidth);
185 return SimplifyDemandedBits(Op, Demanded);
188 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
190 bool CombineToPreIndexedLoadStore(SDNode *N);
191 bool CombineToPostIndexedLoadStore(SDNode *N);
192 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
193 bool SliceUpLoad(SDNode *N);
195 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
198 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
199 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
200 /// \param EltNo index of the vector element to load.
201 /// \param OriginalLoad load that EVE came from to be replaced.
202 /// \returns EVE on success SDValue() on failure.
203 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
204 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
205 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
206 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
207 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
208 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
209 SDValue PromoteIntBinOp(SDValue Op);
210 SDValue PromoteIntShiftOp(SDValue Op);
211 SDValue PromoteExtend(SDValue Op);
212 bool PromoteLoad(SDValue Op);
214 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
215 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
216 ISD::NodeType ExtType);
218 /// Call the node-specific routine that knows how to fold each
219 /// particular type of node. If that doesn't do anything, try the
220 /// target-specific DAG combines.
221 SDValue combine(SDNode *N);
223 // Visitation implementation - Implement dag node combining for different
224 // node types. The semantics are as follows:
226 // SDValue.getNode() == 0 - No change was made
227 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
228 // otherwise - N should be replaced by the returned Operand.
230 SDValue visitTokenFactor(SDNode *N);
231 SDValue visitMERGE_VALUES(SDNode *N);
232 SDValue visitADD(SDNode *N);
233 SDValue visitSUB(SDNode *N);
234 SDValue visitADDC(SDNode *N);
235 SDValue visitSUBC(SDNode *N);
236 SDValue visitADDE(SDNode *N);
237 SDValue visitSUBE(SDNode *N);
238 SDValue visitMUL(SDNode *N);
239 SDValue visitSDIV(SDNode *N);
240 SDValue visitUDIV(SDNode *N);
241 SDValue visitREM(SDNode *N);
242 SDValue visitMULHU(SDNode *N);
243 SDValue visitMULHS(SDNode *N);
244 SDValue visitSMUL_LOHI(SDNode *N);
245 SDValue visitUMUL_LOHI(SDNode *N);
246 SDValue visitSMULO(SDNode *N);
247 SDValue visitUMULO(SDNode *N);
248 SDValue visitSDIVREM(SDNode *N);
249 SDValue visitUDIVREM(SDNode *N);
250 SDValue visitIMINMAX(SDNode *N);
251 SDValue visitAND(SDNode *N);
252 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
253 SDValue visitOR(SDNode *N);
254 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
255 SDValue visitXOR(SDNode *N);
256 SDValue SimplifyVBinOp(SDNode *N);
257 SDValue visitSHL(SDNode *N);
258 SDValue visitSRA(SDNode *N);
259 SDValue visitSRL(SDNode *N);
260 SDValue visitRotate(SDNode *N);
261 SDValue visitBSWAP(SDNode *N);
262 SDValue visitCTLZ(SDNode *N);
263 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
264 SDValue visitCTTZ(SDNode *N);
265 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
266 SDValue visitCTPOP(SDNode *N);
267 SDValue visitSELECT(SDNode *N);
268 SDValue visitVSELECT(SDNode *N);
269 SDValue visitSELECT_CC(SDNode *N);
270 SDValue visitSETCC(SDNode *N);
271 SDValue visitSIGN_EXTEND(SDNode *N);
272 SDValue visitZERO_EXTEND(SDNode *N);
273 SDValue visitANY_EXTEND(SDNode *N);
274 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
275 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
276 SDValue visitTRUNCATE(SDNode *N);
277 SDValue visitBITCAST(SDNode *N);
278 SDValue visitBUILD_PAIR(SDNode *N);
279 SDValue visitFADD(SDNode *N);
280 SDValue visitFSUB(SDNode *N);
281 SDValue visitFMUL(SDNode *N);
282 SDValue visitFMA(SDNode *N);
283 SDValue visitFDIV(SDNode *N);
284 SDValue visitFREM(SDNode *N);
285 SDValue visitFSQRT(SDNode *N);
286 SDValue visitFCOPYSIGN(SDNode *N);
287 SDValue visitSINT_TO_FP(SDNode *N);
288 SDValue visitUINT_TO_FP(SDNode *N);
289 SDValue visitFP_TO_SINT(SDNode *N);
290 SDValue visitFP_TO_UINT(SDNode *N);
291 SDValue visitFP_ROUND(SDNode *N);
292 SDValue visitFP_ROUND_INREG(SDNode *N);
293 SDValue visitFP_EXTEND(SDNode *N);
294 SDValue visitFNEG(SDNode *N);
295 SDValue visitFABS(SDNode *N);
296 SDValue visitFCEIL(SDNode *N);
297 SDValue visitFTRUNC(SDNode *N);
298 SDValue visitFFLOOR(SDNode *N);
299 SDValue visitFMINNUM(SDNode *N);
300 SDValue visitFMAXNUM(SDNode *N);
301 SDValue visitBRCOND(SDNode *N);
302 SDValue visitBR_CC(SDNode *N);
303 SDValue visitLOAD(SDNode *N);
305 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
306 SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
308 SDValue visitSTORE(SDNode *N);
309 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
310 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
311 SDValue visitBUILD_VECTOR(SDNode *N);
312 SDValue visitCONCAT_VECTORS(SDNode *N);
313 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
314 SDValue visitVECTOR_SHUFFLE(SDNode *N);
315 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
316 SDValue visitINSERT_SUBVECTOR(SDNode *N);
317 SDValue visitMLOAD(SDNode *N);
318 SDValue visitMSTORE(SDNode *N);
319 SDValue visitMGATHER(SDNode *N);
320 SDValue visitMSCATTER(SDNode *N);
321 SDValue visitFP_TO_FP16(SDNode *N);
322 SDValue visitFP16_TO_FP(SDNode *N);
324 SDValue visitFADDForFMACombine(SDNode *N);
325 SDValue visitFSUBForFMACombine(SDNode *N);
326 SDValue visitFMULForFMACombine(SDNode *N);
328 SDValue XformToShuffleWithZero(SDNode *N);
329 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
331 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
333 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
334 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
335 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
336 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
337 SDValue N3, ISD::CondCode CC,
338 bool NotExtCompare = false);
339 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
340 SDLoc DL, bool foldBooleans = true);
342 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
344 bool isOneUseSetCC(SDValue N) const;
346 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
348 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
349 SDValue CombineExtLoad(SDNode *N);
350 SDValue combineRepeatedFPDivisors(SDNode *N);
351 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
352 SDValue BuildSDIV(SDNode *N);
353 SDValue BuildSDIVPow2(SDNode *N);
354 SDValue BuildUDIV(SDNode *N);
355 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags);
356 SDValue BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags);
357 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
359 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
361 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
362 bool DemandHighBits = true);
363 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
364 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
365 SDValue InnerPos, SDValue InnerNeg,
366 unsigned PosOpcode, unsigned NegOpcode,
368 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
369 SDValue ReduceLoadWidth(SDNode *N);
370 SDValue ReduceLoadOpStoreWidth(SDNode *N);
371 SDValue TransformFPLoadStorePair(SDNode *N);
372 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
373 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
375 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
377 /// Walk up chain skipping non-aliasing memory nodes,
378 /// looking for aliasing nodes and adding them to the Aliases vector.
379 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
380 SmallVectorImpl<SDValue> &Aliases);
382 /// Return true if there is any possibility that the two addresses overlap.
383 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
385 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
386 /// chain (aliasing node.)
387 SDValue FindBetterChain(SDNode *N, SDValue Chain);
389 /// Do FindBetterChain for a store and any possibly adjacent stores on
390 /// consecutive chains.
391 bool findBetterNeighborChains(StoreSDNode *St);
393 /// Holds a pointer to an LSBaseSDNode as well as information on where it
394 /// is located in a sequence of memory operations connected by a chain.
396 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
397 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
398 // Ptr to the mem node.
399 LSBaseSDNode *MemNode;
400 // Offset from the base ptr.
401 int64_t OffsetFromBase;
402 // What is the sequence number of this mem node.
403 // Lowest mem operand in the DAG starts at zero.
404 unsigned SequenceNum;
407 /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
408 /// constant build_vector of the stored constant values in Stores.
409 SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
411 ArrayRef<MemOpLink> Stores,
412 SmallVectorImpl<SDValue> &Chains,
415 /// This is a helper function for MergeConsecutiveStores. When the source
416 /// elements of the consecutive stores are all constants or all extracted
417 /// vector elements, try to merge them into one larger store.
418 /// \return True if a merged store was created.
419 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
420 EVT MemVT, unsigned NumStores,
421 bool IsConstantSrc, bool UseVector);
423 /// This is a helper function for MergeConsecutiveStores.
424 /// Stores that may be merged are placed in StoreNodes.
425 /// Loads that may alias with those stores are placed in AliasLoadNodes.
426 void getStoreMergeAndAliasCandidates(
427 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
428 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
430 /// Merge consecutive store operations into a wide store.
431 /// This optimization uses wide integers or vectors when possible.
432 /// \return True if some memory operations were changed.
433 bool MergeConsecutiveStores(StoreSDNode *N);
435 /// \brief Try to transform a truncation where C is a constant:
436 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
438 /// \p N needs to be a truncation and its first operand an AND. Other
439 /// requirements are checked by the function (e.g. that trunc is
440 /// single-use) and if missed an empty SDValue is returned.
441 SDValue distributeTruncateThroughAnd(SDNode *N);
444 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
445 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
446 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
447 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
450 /// Runs the dag combiner on all nodes in the work list
451 void Run(CombineLevel AtLevel);
453 SelectionDAG &getDAG() const { return DAG; }
455 /// Returns a type large enough to hold any valid shift amount - before type
456 /// legalization these can be huge.
457 EVT getShiftAmountTy(EVT LHSTy) {
458 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
459 if (LHSTy.isVector())
461 auto &DL = DAG.getDataLayout();
462 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
463 : TLI.getPointerTy(DL);
466 /// This method returns true if we are running before type legalization or
467 /// if the specified VT is legal.
468 bool isTypeLegal(const EVT &VT) {
469 if (!LegalTypes) return true;
470 return TLI.isTypeLegal(VT);
473 /// Convenience wrapper around TargetLowering::getSetCCResultType
474 EVT getSetCCResultType(EVT VT) const {
475 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
482 /// This class is a DAGUpdateListener that removes any deleted
483 /// nodes from the worklist.
484 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
487 explicit WorklistRemover(DAGCombiner &dc)
488 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
490 void NodeDeleted(SDNode *N, SDNode *E) override {
491 DC.removeFromWorklist(N);
496 //===----------------------------------------------------------------------===//
497 // TargetLowering::DAGCombinerInfo implementation
498 //===----------------------------------------------------------------------===//
500 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
501 ((DAGCombiner*)DC)->AddToWorklist(N);
504 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
505 ((DAGCombiner*)DC)->removeFromWorklist(N);
508 SDValue TargetLowering::DAGCombinerInfo::
509 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
510 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
513 SDValue TargetLowering::DAGCombinerInfo::
514 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
515 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
519 SDValue TargetLowering::DAGCombinerInfo::
520 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
521 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
524 void TargetLowering::DAGCombinerInfo::
525 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
526 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
529 //===----------------------------------------------------------------------===//
531 //===----------------------------------------------------------------------===//
533 void DAGCombiner::deleteAndRecombine(SDNode *N) {
534 removeFromWorklist(N);
536 // If the operands of this node are only used by the node, they will now be
537 // dead. Make sure to re-visit them and recursively delete dead nodes.
538 for (const SDValue &Op : N->ops())
539 // For an operand generating multiple values, one of the values may
540 // become dead allowing further simplification (e.g. split index
541 // arithmetic from an indexed load).
542 if (Op->hasOneUse() || Op->getNumValues() > 1)
543 AddToWorklist(Op.getNode());
548 /// Return 1 if we can compute the negated form of the specified expression for
549 /// the same cost as the expression itself, or 2 if we can compute the negated
550 /// form more cheaply than the expression itself.
551 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
552 const TargetLowering &TLI,
553 const TargetOptions *Options,
554 unsigned Depth = 0) {
555 // fneg is removable even if it has multiple uses.
556 if (Op.getOpcode() == ISD::FNEG) return 2;
558 // Don't allow anything with multiple uses.
559 if (!Op.hasOneUse()) return 0;
561 // Don't recurse exponentially.
562 if (Depth > 6) return 0;
564 switch (Op.getOpcode()) {
565 default: return false;
566 case ISD::ConstantFP:
567 // Don't invert constant FP values after legalize. The negated constant
568 // isn't necessarily legal.
569 return LegalOperations ? 0 : 1;
571 // FIXME: determine better conditions for this xform.
572 if (!Options->UnsafeFPMath) return 0;
574 // After operation legalization, it might not be legal to create new FSUBs.
575 if (LegalOperations &&
576 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
579 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
580 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
583 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
584 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
587 // We can't turn -(A-B) into B-A when we honor signed zeros.
588 if (!Options->UnsafeFPMath) return 0;
590 // fold (fneg (fsub A, B)) -> (fsub B, A)
595 if (Options->HonorSignDependentRoundingFPMath()) return 0;
597 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
598 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
602 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
608 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
613 /// If isNegatibleForFree returns true, return the newly negated expression.
614 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
615 bool LegalOperations, unsigned Depth = 0) {
616 const TargetOptions &Options = DAG.getTarget().Options;
617 // fneg is removable even if it has multiple uses.
618 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
620 // Don't allow anything with multiple uses.
621 assert(Op.hasOneUse() && "Unknown reuse!");
623 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
625 const SDNodeFlags *Flags = Op.getNode()->getFlags();
627 switch (Op.getOpcode()) {
628 default: llvm_unreachable("Unknown code");
629 case ISD::ConstantFP: {
630 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
632 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
635 // FIXME: determine better conditions for this xform.
636 assert(Options.UnsafeFPMath);
638 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
639 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
640 DAG.getTargetLoweringInfo(), &Options, Depth+1))
641 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
642 GetNegatedExpression(Op.getOperand(0), DAG,
643 LegalOperations, Depth+1),
644 Op.getOperand(1), Flags);
645 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
646 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
647 GetNegatedExpression(Op.getOperand(1), DAG,
648 LegalOperations, Depth+1),
649 Op.getOperand(0), Flags);
651 // We can't turn -(A-B) into B-A when we honor signed zeros.
652 assert(Options.UnsafeFPMath);
654 // fold (fneg (fsub 0, B)) -> B
655 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
657 return Op.getOperand(1);
659 // fold (fneg (fsub A, B)) -> (fsub B, A)
660 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
661 Op.getOperand(1), Op.getOperand(0), Flags);
665 assert(!Options.HonorSignDependentRoundingFPMath());
667 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
668 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
669 DAG.getTargetLoweringInfo(), &Options, Depth+1))
670 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
671 GetNegatedExpression(Op.getOperand(0), DAG,
672 LegalOperations, Depth+1),
673 Op.getOperand(1), Flags);
675 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
676 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
678 GetNegatedExpression(Op.getOperand(1), DAG,
679 LegalOperations, Depth+1), Flags);
683 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
684 GetNegatedExpression(Op.getOperand(0), DAG,
685 LegalOperations, Depth+1));
687 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
688 GetNegatedExpression(Op.getOperand(0), DAG,
689 LegalOperations, Depth+1),
694 // Return true if this node is a setcc, or is a select_cc
695 // that selects between the target values used for true and false, making it
696 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
697 // the appropriate nodes based on the type of node we are checking. This
698 // simplifies life a bit for the callers.
699 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
701 if (N.getOpcode() == ISD::SETCC) {
702 LHS = N.getOperand(0);
703 RHS = N.getOperand(1);
704 CC = N.getOperand(2);
708 if (N.getOpcode() != ISD::SELECT_CC ||
709 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
710 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
713 if (TLI.getBooleanContents(N.getValueType()) ==
714 TargetLowering::UndefinedBooleanContent)
717 LHS = N.getOperand(0);
718 RHS = N.getOperand(1);
719 CC = N.getOperand(4);
723 /// Return true if this is a SetCC-equivalent operation with only one use.
724 /// If this is true, it allows the users to invert the operation for free when
725 /// it is profitable to do so.
726 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
728 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
733 /// Returns true if N is a BUILD_VECTOR node whose
734 /// elements are all the same constant or undefined.
735 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
736 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
741 unsigned SplatBitSize;
743 EVT EltVT = N->getValueType(0).getVectorElementType();
744 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
746 EltVT.getSizeInBits() >= SplatBitSize);
749 // \brief Returns the SDNode if it is a constant integer BuildVector
750 // or constant integer.
751 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
752 if (isa<ConstantSDNode>(N))
754 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
759 // \brief Returns the SDNode if it is a constant float BuildVector
760 // or constant float.
761 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
762 if (isa<ConstantFPSDNode>(N))
764 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
769 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
771 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
772 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
775 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
776 BitVector UndefElements;
777 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
779 // BuildVectors can truncate their operands. Ignore that case here.
780 // FIXME: We blindly ignore splats which include undef which is overly
782 if (CN && UndefElements.none() &&
783 CN->getValueType(0) == N.getValueType().getScalarType())
790 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
792 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
793 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
796 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
797 BitVector UndefElements;
798 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
800 if (CN && UndefElements.none())
807 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
808 SDValue N0, SDValue N1) {
809 EVT VT = N0.getValueType();
810 if (N0.getOpcode() == Opc) {
811 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
812 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
813 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
814 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
815 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
818 if (N0.hasOneUse()) {
819 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
821 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
822 if (!OpNode.getNode())
824 AddToWorklist(OpNode.getNode());
825 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
830 if (N1.getOpcode() == Opc) {
831 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
832 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
833 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
834 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
835 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
838 if (N1.hasOneUse()) {
839 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
841 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
842 if (!OpNode.getNode())
844 AddToWorklist(OpNode.getNode());
845 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
853 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
855 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
857 DEBUG(dbgs() << "\nReplacing.1 ";
859 dbgs() << "\nWith: ";
860 To[0].getNode()->dump(&DAG);
861 dbgs() << " and " << NumTo-1 << " other values\n");
862 for (unsigned i = 0, e = NumTo; i != e; ++i)
863 assert((!To[i].getNode() ||
864 N->getValueType(i) == To[i].getValueType()) &&
865 "Cannot combine value to value of different type!");
867 WorklistRemover DeadNodes(*this);
868 DAG.ReplaceAllUsesWith(N, To);
870 // Push the new nodes and any users onto the worklist
871 for (unsigned i = 0, e = NumTo; i != e; ++i) {
872 if (To[i].getNode()) {
873 AddToWorklist(To[i].getNode());
874 AddUsersToWorklist(To[i].getNode());
879 // Finally, if the node is now dead, remove it from the graph. The node
880 // may not be dead if the replacement process recursively simplified to
881 // something else needing this node.
883 deleteAndRecombine(N);
884 return SDValue(N, 0);
888 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
889 // Replace all uses. If any nodes become isomorphic to other nodes and
890 // are deleted, make sure to remove them from our worklist.
891 WorklistRemover DeadNodes(*this);
892 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
894 // Push the new node and any (possibly new) users onto the worklist.
895 AddToWorklist(TLO.New.getNode());
896 AddUsersToWorklist(TLO.New.getNode());
898 // Finally, if the node is now dead, remove it from the graph. The node
899 // may not be dead if the replacement process recursively simplified to
900 // something else needing this node.
901 if (TLO.Old.getNode()->use_empty())
902 deleteAndRecombine(TLO.Old.getNode());
905 /// Check the specified integer node value to see if it can be simplified or if
906 /// things it uses can be simplified by bit propagation. If so, return true.
907 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
908 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
909 APInt KnownZero, KnownOne;
910 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
914 AddToWorklist(Op.getNode());
916 // Replace the old value with the new one.
918 DEBUG(dbgs() << "\nReplacing.2 ";
919 TLO.Old.getNode()->dump(&DAG);
920 dbgs() << "\nWith: ";
921 TLO.New.getNode()->dump(&DAG);
924 CommitTargetLoweringOpt(TLO);
928 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
930 EVT VT = Load->getValueType(0);
931 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
933 DEBUG(dbgs() << "\nReplacing.9 ";
935 dbgs() << "\nWith: ";
936 Trunc.getNode()->dump(&DAG);
938 WorklistRemover DeadNodes(*this);
939 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
940 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
941 deleteAndRecombine(Load);
942 AddToWorklist(Trunc.getNode());
945 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
948 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
949 EVT MemVT = LD->getMemoryVT();
950 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
951 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
953 : LD->getExtensionType();
955 return DAG.getExtLoad(ExtType, dl, PVT,
956 LD->getChain(), LD->getBasePtr(),
957 MemVT, LD->getMemOperand());
960 unsigned Opc = Op.getOpcode();
963 case ISD::AssertSext:
964 return DAG.getNode(ISD::AssertSext, dl, PVT,
965 SExtPromoteOperand(Op.getOperand(0), PVT),
967 case ISD::AssertZext:
968 return DAG.getNode(ISD::AssertZext, dl, PVT,
969 ZExtPromoteOperand(Op.getOperand(0), PVT),
971 case ISD::Constant: {
973 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
974 return DAG.getNode(ExtOpc, dl, PVT, Op);
978 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
980 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
983 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
984 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
986 EVT OldVT = Op.getValueType();
988 bool Replace = false;
989 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
990 if (!NewOp.getNode())
992 AddToWorklist(NewOp.getNode());
995 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
996 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
997 DAG.getValueType(OldVT));
1000 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1001 EVT OldVT = Op.getValueType();
1003 bool Replace = false;
1004 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1005 if (!NewOp.getNode())
1007 AddToWorklist(NewOp.getNode());
1010 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1011 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
1014 /// Promote the specified integer binary operation if the target indicates it is
1015 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1016 /// i32 since i16 instructions are longer.
1017 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1018 if (!LegalOperations)
1021 EVT VT = Op.getValueType();
1022 if (VT.isVector() || !VT.isInteger())
1025 // If operation type is 'undesirable', e.g. i16 on x86, consider
1027 unsigned Opc = Op.getOpcode();
1028 if (TLI.isTypeDesirableForOp(Opc, VT))
1032 // Consult target whether it is a good idea to promote this operation and
1033 // what's the right type to promote it to.
1034 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1035 assert(PVT != VT && "Don't know what type to promote to!");
1037 bool Replace0 = false;
1038 SDValue N0 = Op.getOperand(0);
1039 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1043 bool Replace1 = false;
1044 SDValue N1 = Op.getOperand(1);
1049 NN1 = PromoteOperand(N1, PVT, Replace1);
1054 AddToWorklist(NN0.getNode());
1056 AddToWorklist(NN1.getNode());
1059 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1061 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1063 DEBUG(dbgs() << "\nPromoting ";
1064 Op.getNode()->dump(&DAG));
1066 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1067 DAG.getNode(Opc, dl, PVT, NN0, NN1));
1072 /// Promote the specified integer shift operation if the target indicates it is
1073 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1074 /// i32 since i16 instructions are longer.
1075 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1076 if (!LegalOperations)
1079 EVT VT = Op.getValueType();
1080 if (VT.isVector() || !VT.isInteger())
1083 // If operation type is 'undesirable', e.g. i16 on x86, consider
1085 unsigned Opc = Op.getOpcode();
1086 if (TLI.isTypeDesirableForOp(Opc, VT))
1090 // Consult target whether it is a good idea to promote this operation and
1091 // what's the right type to promote it to.
1092 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1093 assert(PVT != VT && "Don't know what type to promote to!");
1095 bool Replace = false;
1096 SDValue N0 = Op.getOperand(0);
1097 if (Opc == ISD::SRA)
1098 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1099 else if (Opc == ISD::SRL)
1100 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1102 N0 = PromoteOperand(N0, PVT, Replace);
1106 AddToWorklist(N0.getNode());
1108 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1110 DEBUG(dbgs() << "\nPromoting ";
1111 Op.getNode()->dump(&DAG));
1113 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1114 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1119 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1120 if (!LegalOperations)
1123 EVT VT = Op.getValueType();
1124 if (VT.isVector() || !VT.isInteger())
1127 // If operation type is 'undesirable', e.g. i16 on x86, consider
1129 unsigned Opc = Op.getOpcode();
1130 if (TLI.isTypeDesirableForOp(Opc, VT))
1134 // Consult target whether it is a good idea to promote this operation and
1135 // what's the right type to promote it to.
1136 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1137 assert(PVT != VT && "Don't know what type to promote to!");
1138 // fold (aext (aext x)) -> (aext x)
1139 // fold (aext (zext x)) -> (zext x)
1140 // fold (aext (sext x)) -> (sext x)
1141 DEBUG(dbgs() << "\nPromoting ";
1142 Op.getNode()->dump(&DAG));
1143 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1148 bool DAGCombiner::PromoteLoad(SDValue Op) {
1149 if (!LegalOperations)
1152 EVT VT = Op.getValueType();
1153 if (VT.isVector() || !VT.isInteger())
1156 // If operation type is 'undesirable', e.g. i16 on x86, consider
1158 unsigned Opc = Op.getOpcode();
1159 if (TLI.isTypeDesirableForOp(Opc, VT))
1163 // Consult target whether it is a good idea to promote this operation and
1164 // what's the right type to promote it to.
1165 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1166 assert(PVT != VT && "Don't know what type to promote to!");
1169 SDNode *N = Op.getNode();
1170 LoadSDNode *LD = cast<LoadSDNode>(N);
1171 EVT MemVT = LD->getMemoryVT();
1172 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1173 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1175 : LD->getExtensionType();
1176 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1177 LD->getChain(), LD->getBasePtr(),
1178 MemVT, LD->getMemOperand());
1179 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1181 DEBUG(dbgs() << "\nPromoting ";
1184 Result.getNode()->dump(&DAG);
1186 WorklistRemover DeadNodes(*this);
1187 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1188 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1189 deleteAndRecombine(N);
1190 AddToWorklist(Result.getNode());
1196 /// \brief Recursively delete a node which has no uses and any operands for
1197 /// which it is the only use.
1199 /// Note that this both deletes the nodes and removes them from the worklist.
1200 /// It also adds any nodes who have had a user deleted to the worklist as they
1201 /// may now have only one use and subject to other combines.
1202 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1203 if (!N->use_empty())
1206 SmallSetVector<SDNode *, 16> Nodes;
1209 N = Nodes.pop_back_val();
1213 if (N->use_empty()) {
1214 for (const SDValue &ChildN : N->op_values())
1215 Nodes.insert(ChildN.getNode());
1217 removeFromWorklist(N);
1222 } while (!Nodes.empty());
1226 //===----------------------------------------------------------------------===//
1227 // Main DAG Combiner implementation
1228 //===----------------------------------------------------------------------===//
1230 void DAGCombiner::Run(CombineLevel AtLevel) {
1231 // set the instance variables, so that the various visit routines may use it.
1233 LegalOperations = Level >= AfterLegalizeVectorOps;
1234 LegalTypes = Level >= AfterLegalizeTypes;
1236 // Add all the dag nodes to the worklist.
1237 for (SDNode &Node : DAG.allnodes())
1238 AddToWorklist(&Node);
1240 // Create a dummy node (which is not added to allnodes), that adds a reference
1241 // to the root node, preventing it from being deleted, and tracking any
1242 // changes of the root.
1243 HandleSDNode Dummy(DAG.getRoot());
1245 // while the worklist isn't empty, find a node and
1246 // try and combine it.
1247 while (!WorklistMap.empty()) {
1249 // The Worklist holds the SDNodes in order, but it may contain null entries.
1251 N = Worklist.pop_back_val();
1254 bool GoodWorklistEntry = WorklistMap.erase(N);
1255 (void)GoodWorklistEntry;
1256 assert(GoodWorklistEntry &&
1257 "Found a worklist entry without a corresponding map entry!");
1259 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1260 // N is deleted from the DAG, since they too may now be dead or may have a
1261 // reduced number of uses, allowing other xforms.
1262 if (recursivelyDeleteUnusedNodes(N))
1265 WorklistRemover DeadNodes(*this);
1267 // If this combine is running after legalizing the DAG, re-legalize any
1268 // nodes pulled off the worklist.
1269 if (Level == AfterLegalizeDAG) {
1270 SmallSetVector<SDNode *, 16> UpdatedNodes;
1271 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1273 for (SDNode *LN : UpdatedNodes) {
1275 AddUsersToWorklist(LN);
1281 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1283 // Add any operands of the new node which have not yet been combined to the
1284 // worklist as well. Because the worklist uniques things already, this
1285 // won't repeatedly process the same operand.
1286 CombinedNodes.insert(N);
1287 for (const SDValue &ChildN : N->op_values())
1288 if (!CombinedNodes.count(ChildN.getNode()))
1289 AddToWorklist(ChildN.getNode());
1291 SDValue RV = combine(N);
1298 // If we get back the same node we passed in, rather than a new node or
1299 // zero, we know that the node must have defined multiple values and
1300 // CombineTo was used. Since CombineTo takes care of the worklist
1301 // mechanics for us, we have no work to do in this case.
1302 if (RV.getNode() == N)
1305 assert(N->getOpcode() != ISD::DELETED_NODE &&
1306 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1307 "Node was deleted but visit returned new node!");
1309 DEBUG(dbgs() << " ... into: ";
1310 RV.getNode()->dump(&DAG));
1312 // Transfer debug value.
1313 DAG.TransferDbgValues(SDValue(N, 0), RV);
1314 if (N->getNumValues() == RV.getNode()->getNumValues())
1315 DAG.ReplaceAllUsesWith(N, RV.getNode());
1317 assert(N->getValueType(0) == RV.getValueType() &&
1318 N->getNumValues() == 1 && "Type mismatch");
1320 DAG.ReplaceAllUsesWith(N, &OpV);
1323 // Push the new node and any users onto the worklist
1324 AddToWorklist(RV.getNode());
1325 AddUsersToWorklist(RV.getNode());
1327 // Finally, if the node is now dead, remove it from the graph. The node
1328 // may not be dead if the replacement process recursively simplified to
1329 // something else needing this node. This will also take care of adding any
1330 // operands which have lost a user to the worklist.
1331 recursivelyDeleteUnusedNodes(N);
1334 // If the root changed (e.g. it was a dead load, update the root).
1335 DAG.setRoot(Dummy.getValue());
1336 DAG.RemoveDeadNodes();
1339 SDValue DAGCombiner::visit(SDNode *N) {
1340 switch (N->getOpcode()) {
1342 case ISD::TokenFactor: return visitTokenFactor(N);
1343 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1344 case ISD::ADD: return visitADD(N);
1345 case ISD::SUB: return visitSUB(N);
1346 case ISD::ADDC: return visitADDC(N);
1347 case ISD::SUBC: return visitSUBC(N);
1348 case ISD::ADDE: return visitADDE(N);
1349 case ISD::SUBE: return visitSUBE(N);
1350 case ISD::MUL: return visitMUL(N);
1351 case ISD::SDIV: return visitSDIV(N);
1352 case ISD::UDIV: return visitUDIV(N);
1354 case ISD::UREM: return visitREM(N);
1355 case ISD::MULHU: return visitMULHU(N);
1356 case ISD::MULHS: return visitMULHS(N);
1357 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1358 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1359 case ISD::SMULO: return visitSMULO(N);
1360 case ISD::UMULO: return visitUMULO(N);
1361 case ISD::SDIVREM: return visitSDIVREM(N);
1362 case ISD::UDIVREM: return visitUDIVREM(N);
1366 case ISD::UMAX: return visitIMINMAX(N);
1367 case ISD::AND: return visitAND(N);
1368 case ISD::OR: return visitOR(N);
1369 case ISD::XOR: return visitXOR(N);
1370 case ISD::SHL: return visitSHL(N);
1371 case ISD::SRA: return visitSRA(N);
1372 case ISD::SRL: return visitSRL(N);
1374 case ISD::ROTL: return visitRotate(N);
1375 case ISD::BSWAP: return visitBSWAP(N);
1376 case ISD::CTLZ: return visitCTLZ(N);
1377 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1378 case ISD::CTTZ: return visitCTTZ(N);
1379 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1380 case ISD::CTPOP: return visitCTPOP(N);
1381 case ISD::SELECT: return visitSELECT(N);
1382 case ISD::VSELECT: return visitVSELECT(N);
1383 case ISD::SELECT_CC: return visitSELECT_CC(N);
1384 case ISD::SETCC: return visitSETCC(N);
1385 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1386 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1387 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1388 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1389 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1390 case ISD::TRUNCATE: return visitTRUNCATE(N);
1391 case ISD::BITCAST: return visitBITCAST(N);
1392 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1393 case ISD::FADD: return visitFADD(N);
1394 case ISD::FSUB: return visitFSUB(N);
1395 case ISD::FMUL: return visitFMUL(N);
1396 case ISD::FMA: return visitFMA(N);
1397 case ISD::FDIV: return visitFDIV(N);
1398 case ISD::FREM: return visitFREM(N);
1399 case ISD::FSQRT: return visitFSQRT(N);
1400 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1401 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1402 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1403 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1404 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1405 case ISD::FP_ROUND: return visitFP_ROUND(N);
1406 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1407 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1408 case ISD::FNEG: return visitFNEG(N);
1409 case ISD::FABS: return visitFABS(N);
1410 case ISD::FFLOOR: return visitFFLOOR(N);
1411 case ISD::FMINNUM: return visitFMINNUM(N);
1412 case ISD::FMAXNUM: return visitFMAXNUM(N);
1413 case ISD::FCEIL: return visitFCEIL(N);
1414 case ISD::FTRUNC: return visitFTRUNC(N);
1415 case ISD::BRCOND: return visitBRCOND(N);
1416 case ISD::BR_CC: return visitBR_CC(N);
1417 case ISD::LOAD: return visitLOAD(N);
1418 case ISD::STORE: return visitSTORE(N);
1419 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1420 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1421 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1422 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1423 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1424 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1425 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1426 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1427 case ISD::MGATHER: return visitMGATHER(N);
1428 case ISD::MLOAD: return visitMLOAD(N);
1429 case ISD::MSCATTER: return visitMSCATTER(N);
1430 case ISD::MSTORE: return visitMSTORE(N);
1431 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
1432 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N);
1437 SDValue DAGCombiner::combine(SDNode *N) {
1438 SDValue RV = visit(N);
1440 // If nothing happened, try a target-specific DAG combine.
1441 if (!RV.getNode()) {
1442 assert(N->getOpcode() != ISD::DELETED_NODE &&
1443 "Node was deleted but visit returned NULL!");
1445 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1446 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1448 // Expose the DAG combiner to the target combiner impls.
1449 TargetLowering::DAGCombinerInfo
1450 DagCombineInfo(DAG, Level, false, this);
1452 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1456 // If nothing happened still, try promoting the operation.
1457 if (!RV.getNode()) {
1458 switch (N->getOpcode()) {
1466 RV = PromoteIntBinOp(SDValue(N, 0));
1471 RV = PromoteIntShiftOp(SDValue(N, 0));
1473 case ISD::SIGN_EXTEND:
1474 case ISD::ZERO_EXTEND:
1475 case ISD::ANY_EXTEND:
1476 RV = PromoteExtend(SDValue(N, 0));
1479 if (PromoteLoad(SDValue(N, 0)))
1485 // If N is a commutative binary node, try commuting it to enable more
1487 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1488 N->getNumValues() == 1) {
1489 SDValue N0 = N->getOperand(0);
1490 SDValue N1 = N->getOperand(1);
1492 // Constant operands are canonicalized to RHS.
1493 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1494 SDValue Ops[] = {N1, N0};
1495 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1498 return SDValue(CSENode, 0);
1505 /// Given a node, return its input chain if it has one, otherwise return a null
1507 static SDValue getInputChainForNode(SDNode *N) {
1508 if (unsigned NumOps = N->getNumOperands()) {
1509 if (N->getOperand(0).getValueType() == MVT::Other)
1510 return N->getOperand(0);
1511 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1512 return N->getOperand(NumOps-1);
1513 for (unsigned i = 1; i < NumOps-1; ++i)
1514 if (N->getOperand(i).getValueType() == MVT::Other)
1515 return N->getOperand(i);
1520 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1521 // If N has two operands, where one has an input chain equal to the other,
1522 // the 'other' chain is redundant.
1523 if (N->getNumOperands() == 2) {
1524 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1525 return N->getOperand(0);
1526 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1527 return N->getOperand(1);
1530 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1531 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1532 SmallPtrSet<SDNode*, 16> SeenOps;
1533 bool Changed = false; // If we should replace this token factor.
1535 // Start out with this token factor.
1538 // Iterate through token factors. The TFs grows when new token factors are
1540 for (unsigned i = 0; i < TFs.size(); ++i) {
1541 SDNode *TF = TFs[i];
1543 // Check each of the operands.
1544 for (const SDValue &Op : TF->op_values()) {
1546 switch (Op.getOpcode()) {
1547 case ISD::EntryToken:
1548 // Entry tokens don't need to be added to the list. They are
1553 case ISD::TokenFactor:
1554 if (Op.hasOneUse() &&
1555 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1556 // Queue up for processing.
1557 TFs.push_back(Op.getNode());
1558 // Clean up in case the token factor is removed.
1559 AddToWorklist(Op.getNode());
1566 // Only add if it isn't already in the list.
1567 if (SeenOps.insert(Op.getNode()).second)
1578 // If we've changed things around then replace token factor.
1581 // The entry token is the only possible outcome.
1582 Result = DAG.getEntryNode();
1584 // New and improved token factor.
1585 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1588 // Add users to worklist if AA is enabled, since it may introduce
1589 // a lot of new chained token factors while removing memory deps.
1590 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1591 : DAG.getSubtarget().useAA();
1592 return CombineTo(N, Result, UseAA /*add to worklist*/);
1598 /// MERGE_VALUES can always be eliminated.
1599 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1600 WorklistRemover DeadNodes(*this);
1601 // Replacing results may cause a different MERGE_VALUES to suddenly
1602 // be CSE'd with N, and carry its uses with it. Iterate until no
1603 // uses remain, to ensure that the node can be safely deleted.
1604 // First add the users of this node to the work list so that they
1605 // can be tried again once they have new operands.
1606 AddUsersToWorklist(N);
1608 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1609 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1610 } while (!N->use_empty());
1611 deleteAndRecombine(N);
1612 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1615 static bool isNullConstant(SDValue V) {
1616 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1617 return Const != nullptr && Const->isNullValue();
1620 static bool isNullFPConstant(SDValue V) {
1621 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1622 return Const != nullptr && Const->isZero() && !Const->isNegative();
1625 static bool isAllOnesConstant(SDValue V) {
1626 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1627 return Const != nullptr && Const->isAllOnesValue();
1630 static bool isOneConstant(SDValue V) {
1631 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1632 return Const != nullptr && Const->isOne();
1635 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1636 /// ContantSDNode pointer else nullptr.
1637 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1638 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1639 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1642 SDValue DAGCombiner::visitADD(SDNode *N) {
1643 SDValue N0 = N->getOperand(0);
1644 SDValue N1 = N->getOperand(1);
1645 EVT VT = N0.getValueType();
1648 if (VT.isVector()) {
1649 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1652 // fold (add x, 0) -> x, vector edition
1653 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1655 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1659 // fold (add x, undef) -> undef
1660 if (N0.getOpcode() == ISD::UNDEF)
1662 if (N1.getOpcode() == ISD::UNDEF)
1664 // fold (add c1, c2) -> c1+c2
1665 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1666 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1668 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1669 // canonicalize constant to RHS
1670 if (isConstantIntBuildVectorOrConstantInt(N0) &&
1671 !isConstantIntBuildVectorOrConstantInt(N1))
1672 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1673 // fold (add x, 0) -> x
1674 if (isNullConstant(N1))
1676 // fold (add Sym, c) -> Sym+c
1677 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1678 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1679 GA->getOpcode() == ISD::GlobalAddress)
1680 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1682 (uint64_t)N1C->getSExtValue());
1683 // fold ((c1-A)+c2) -> (c1+c2)-A
1684 if (N1C && N0.getOpcode() == ISD::SUB)
1685 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1687 return DAG.getNode(ISD::SUB, DL, VT,
1688 DAG.getConstant(N1C->getAPIntValue()+
1689 N0C->getAPIntValue(), DL, VT),
1693 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1695 // fold ((0-A) + B) -> B-A
1696 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1697 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1698 // fold (A + (0-B)) -> A-B
1699 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1700 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1701 // fold (A+(B-A)) -> B
1702 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1703 return N1.getOperand(0);
1704 // fold ((B-A)+A) -> B
1705 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1706 return N0.getOperand(0);
1707 // fold (A+(B-(A+C))) to (B-C)
1708 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1709 N0 == N1.getOperand(1).getOperand(0))
1710 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1711 N1.getOperand(1).getOperand(1));
1712 // fold (A+(B-(C+A))) to (B-C)
1713 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1714 N0 == N1.getOperand(1).getOperand(1))
1715 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1716 N1.getOperand(1).getOperand(0));
1717 // fold (A+((B-A)+or-C)) to (B+or-C)
1718 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1719 N1.getOperand(0).getOpcode() == ISD::SUB &&
1720 N0 == N1.getOperand(0).getOperand(1))
1721 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1722 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1724 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1725 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1726 SDValue N00 = N0.getOperand(0);
1727 SDValue N01 = N0.getOperand(1);
1728 SDValue N10 = N1.getOperand(0);
1729 SDValue N11 = N1.getOperand(1);
1731 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1732 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1733 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1734 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1737 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1738 return SDValue(N, 0);
1740 // fold (a+b) -> (a|b) iff a and b share no bits.
1741 if (VT.isInteger() && !VT.isVector()) {
1742 APInt LHSZero, LHSOne;
1743 APInt RHSZero, RHSOne;
1744 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1746 if (LHSZero.getBoolValue()) {
1747 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1749 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1750 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1751 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1752 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1753 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1758 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1759 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1760 isNullConstant(N1.getOperand(0).getOperand(0)))
1761 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1762 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1763 N1.getOperand(0).getOperand(1),
1765 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1766 isNullConstant(N0.getOperand(0).getOperand(0)))
1767 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1768 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1769 N0.getOperand(0).getOperand(1),
1772 if (N1.getOpcode() == ISD::AND) {
1773 SDValue AndOp0 = N1.getOperand(0);
1774 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1775 unsigned DestBits = VT.getScalarType().getSizeInBits();
1777 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1778 // and similar xforms where the inner op is either ~0 or 0.
1779 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1781 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1785 // add (sext i1), X -> sub X, (zext i1)
1786 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1787 N0.getOperand(0).getValueType() == MVT::i1 &&
1788 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1790 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1791 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1794 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1795 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1796 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1797 if (TN->getVT() == MVT::i1) {
1799 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1800 DAG.getConstant(1, DL, VT));
1801 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1808 SDValue DAGCombiner::visitADDC(SDNode *N) {
1809 SDValue N0 = N->getOperand(0);
1810 SDValue N1 = N->getOperand(1);
1811 EVT VT = N0.getValueType();
1813 // If the flag result is dead, turn this into an ADD.
1814 if (!N->hasAnyUseOfValue(1))
1815 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1816 DAG.getNode(ISD::CARRY_FALSE,
1817 SDLoc(N), MVT::Glue));
1819 // canonicalize constant to RHS.
1820 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1821 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1823 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1825 // fold (addc x, 0) -> x + no carry out
1826 if (isNullConstant(N1))
1827 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1828 SDLoc(N), MVT::Glue));
1830 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1831 APInt LHSZero, LHSOne;
1832 APInt RHSZero, RHSOne;
1833 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1835 if (LHSZero.getBoolValue()) {
1836 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1838 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1839 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1840 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1841 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1842 DAG.getNode(ISD::CARRY_FALSE,
1843 SDLoc(N), MVT::Glue));
1849 SDValue DAGCombiner::visitADDE(SDNode *N) {
1850 SDValue N0 = N->getOperand(0);
1851 SDValue N1 = N->getOperand(1);
1852 SDValue CarryIn = N->getOperand(2);
1854 // canonicalize constant to RHS
1855 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1856 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1858 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1861 // fold (adde x, y, false) -> (addc x, y)
1862 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1863 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1868 // Since it may not be valid to emit a fold to zero for vector initializers
1869 // check if we can before folding.
1870 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1872 bool LegalOperations, bool LegalTypes) {
1874 return DAG.getConstant(0, DL, VT);
1875 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1876 return DAG.getConstant(0, DL, VT);
1880 SDValue DAGCombiner::visitSUB(SDNode *N) {
1881 SDValue N0 = N->getOperand(0);
1882 SDValue N1 = N->getOperand(1);
1883 EVT VT = N0.getValueType();
1886 if (VT.isVector()) {
1887 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1890 // fold (sub x, 0) -> x, vector edition
1891 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1895 // fold (sub x, x) -> 0
1896 // FIXME: Refactor this and xor and other similar operations together.
1898 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1899 // fold (sub c1, c2) -> c1-c2
1900 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1901 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1903 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1904 // fold (sub x, c) -> (add x, -c)
1907 return DAG.getNode(ISD::ADD, DL, VT, N0,
1908 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1910 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1911 if (isAllOnesConstant(N0))
1912 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1913 // fold A-(A-B) -> B
1914 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1915 return N1.getOperand(1);
1916 // fold (A+B)-A -> B
1917 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1918 return N0.getOperand(1);
1919 // fold (A+B)-B -> A
1920 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1921 return N0.getOperand(0);
1922 // fold C2-(A+C1) -> (C2-C1)-A
1923 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1924 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1925 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1927 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1929 return DAG.getNode(ISD::SUB, DL, VT, NewC,
1932 // fold ((A+(B+or-C))-B) -> A+or-C
1933 if (N0.getOpcode() == ISD::ADD &&
1934 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1935 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1936 N0.getOperand(1).getOperand(0) == N1)
1937 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1938 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1939 // fold ((A+(C+B))-B) -> A+C
1940 if (N0.getOpcode() == ISD::ADD &&
1941 N0.getOperand(1).getOpcode() == ISD::ADD &&
1942 N0.getOperand(1).getOperand(1) == N1)
1943 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1944 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1945 // fold ((A-(B-C))-C) -> A-B
1946 if (N0.getOpcode() == ISD::SUB &&
1947 N0.getOperand(1).getOpcode() == ISD::SUB &&
1948 N0.getOperand(1).getOperand(1) == N1)
1949 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1950 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1952 // If either operand of a sub is undef, the result is undef
1953 if (N0.getOpcode() == ISD::UNDEF)
1955 if (N1.getOpcode() == ISD::UNDEF)
1958 // If the relocation model supports it, consider symbol offsets.
1959 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1960 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1961 // fold (sub Sym, c) -> Sym-c
1962 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1963 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1965 (uint64_t)N1C->getSExtValue());
1966 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1967 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1968 if (GA->getGlobal() == GB->getGlobal())
1969 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1973 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1974 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1975 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1976 if (TN->getVT() == MVT::i1) {
1978 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1979 DAG.getConstant(1, DL, VT));
1980 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1987 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1988 SDValue N0 = N->getOperand(0);
1989 SDValue N1 = N->getOperand(1);
1990 EVT VT = N0.getValueType();
1993 // If the flag result is dead, turn this into an SUB.
1994 if (!N->hasAnyUseOfValue(1))
1995 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
1996 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1998 // fold (subc x, x) -> 0 + no borrow
2000 return CombineTo(N, DAG.getConstant(0, DL, VT),
2001 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2003 // fold (subc x, 0) -> x + no borrow
2004 if (isNullConstant(N1))
2005 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2007 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2008 if (isAllOnesConstant(N0))
2009 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2010 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2015 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2016 SDValue N0 = N->getOperand(0);
2017 SDValue N1 = N->getOperand(1);
2018 SDValue CarryIn = N->getOperand(2);
2020 // fold (sube x, y, false) -> (subc x, y)
2021 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2022 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2027 SDValue DAGCombiner::visitMUL(SDNode *N) {
2028 SDValue N0 = N->getOperand(0);
2029 SDValue N1 = N->getOperand(1);
2030 EVT VT = N0.getValueType();
2032 // fold (mul x, undef) -> 0
2033 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2034 return DAG.getConstant(0, SDLoc(N), VT);
2036 bool N0IsConst = false;
2037 bool N1IsConst = false;
2038 bool N1IsOpaqueConst = false;
2039 bool N0IsOpaqueConst = false;
2040 APInt ConstValue0, ConstValue1;
2042 if (VT.isVector()) {
2043 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2046 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2047 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2049 N0IsConst = isa<ConstantSDNode>(N0);
2051 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2052 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2054 N1IsConst = isa<ConstantSDNode>(N1);
2056 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2057 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2061 // fold (mul c1, c2) -> c1*c2
2062 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2063 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2064 N0.getNode(), N1.getNode());
2066 // canonicalize constant to RHS (vector doesn't have to splat)
2067 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2068 !isConstantIntBuildVectorOrConstantInt(N1))
2069 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2070 // fold (mul x, 0) -> 0
2071 if (N1IsConst && ConstValue1 == 0)
2073 // We require a splat of the entire scalar bit width for non-contiguous
2076 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2077 // fold (mul x, 1) -> x
2078 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2080 // fold (mul x, -1) -> 0-x
2081 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2083 return DAG.getNode(ISD::SUB, DL, VT,
2084 DAG.getConstant(0, DL, VT), N0);
2086 // fold (mul x, (1 << c)) -> x << c
2087 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2090 return DAG.getNode(ISD::SHL, DL, VT, N0,
2091 DAG.getConstant(ConstValue1.logBase2(), DL,
2092 getShiftAmountTy(N0.getValueType())));
2094 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2095 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2097 unsigned Log2Val = (-ConstValue1).logBase2();
2099 // FIXME: If the input is something that is easily negated (e.g. a
2100 // single-use add), we should put the negate there.
2101 return DAG.getNode(ISD::SUB, DL, VT,
2102 DAG.getConstant(0, DL, VT),
2103 DAG.getNode(ISD::SHL, DL, VT, N0,
2104 DAG.getConstant(Log2Val, DL,
2105 getShiftAmountTy(N0.getValueType()))));
2109 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2110 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2111 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2112 isa<ConstantSDNode>(N0.getOperand(1)))) {
2113 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2114 N1, N0.getOperand(1));
2115 AddToWorklist(C3.getNode());
2116 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2117 N0.getOperand(0), C3);
2120 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2123 SDValue Sh(nullptr,0), Y(nullptr,0);
2124 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2125 if (N0.getOpcode() == ISD::SHL &&
2126 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2127 isa<ConstantSDNode>(N0.getOperand(1))) &&
2128 N0.getNode()->hasOneUse()) {
2130 } else if (N1.getOpcode() == ISD::SHL &&
2131 isa<ConstantSDNode>(N1.getOperand(1)) &&
2132 N1.getNode()->hasOneUse()) {
2137 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2138 Sh.getOperand(0), Y);
2139 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2140 Mul, Sh.getOperand(1));
2144 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2145 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2146 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2147 isa<ConstantSDNode>(N0.getOperand(1))))
2148 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2149 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2150 N0.getOperand(0), N1),
2151 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2152 N0.getOperand(1), N1));
2155 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2161 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2162 SDValue N0 = N->getOperand(0);
2163 SDValue N1 = N->getOperand(1);
2164 EVT VT = N->getValueType(0);
2168 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2173 // fold (sdiv c1, c2) -> c1/c2
2174 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2175 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2176 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2177 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2178 // fold (sdiv X, 1) -> X
2179 if (N1C && N1C->isOne())
2181 // fold (sdiv X, -1) -> 0-X
2182 if (N1C && N1C->isAllOnesValue())
2183 return DAG.getNode(ISD::SUB, DL, VT,
2184 DAG.getConstant(0, DL, VT), N0);
2186 // If we know the sign bits of both operands are zero, strength reduce to a
2187 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2188 if (!VT.isVector()) {
2189 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2190 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2193 // fold (sdiv X, pow2) -> simple ops after legalize
2194 // FIXME: We check for the exact bit here because the generic lowering gives
2195 // better results in that case. The target-specific lowering should learn how
2196 // to handle exact sdivs efficiently.
2197 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2198 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2199 (N1C->getAPIntValue().isPowerOf2() ||
2200 (-N1C->getAPIntValue()).isPowerOf2())) {
2201 // Target-specific implementation of sdiv x, pow2.
2202 if (SDValue Res = BuildSDIVPow2(N))
2205 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2207 // Splat the sign bit into the register
2209 DAG.getNode(ISD::SRA, DL, VT, N0,
2210 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2211 getShiftAmountTy(N0.getValueType())));
2212 AddToWorklist(SGN.getNode());
2214 // Add (N0 < 0) ? abs2 - 1 : 0;
2216 DAG.getNode(ISD::SRL, DL, VT, SGN,
2217 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2218 getShiftAmountTy(SGN.getValueType())));
2219 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2220 AddToWorklist(SRL.getNode());
2221 AddToWorklist(ADD.getNode()); // Divide by pow2
2222 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2223 DAG.getConstant(lg2, DL,
2224 getShiftAmountTy(ADD.getValueType())));
2226 // If we're dividing by a positive value, we're done. Otherwise, we must
2227 // negate the result.
2228 if (N1C->getAPIntValue().isNonNegative())
2231 AddToWorklist(SRA.getNode());
2232 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2235 // If integer divide is expensive and we satisfy the requirements, emit an
2236 // alternate sequence. Targets may check function attributes for size/speed
2238 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2239 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2240 if (SDValue Op = BuildSDIV(N))
2244 if (N0.getOpcode() == ISD::UNDEF)
2245 return DAG.getConstant(0, DL, VT);
2246 // X / undef -> undef
2247 if (N1.getOpcode() == ISD::UNDEF)
2253 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2254 SDValue N0 = N->getOperand(0);
2255 SDValue N1 = N->getOperand(1);
2256 EVT VT = N->getValueType(0);
2260 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2265 // fold (udiv c1, c2) -> c1/c2
2266 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2267 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2269 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2272 // fold (udiv x, (1 << c)) -> x >>u c
2273 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2())
2274 return DAG.getNode(ISD::SRL, DL, VT, N0,
2275 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2276 getShiftAmountTy(N0.getValueType())));
2278 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2279 if (N1.getOpcode() == ISD::SHL) {
2280 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2281 if (SHC->getAPIntValue().isPowerOf2()) {
2282 EVT ADDVT = N1.getOperand(1).getValueType();
2283 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2285 DAG.getConstant(SHC->getAPIntValue()
2288 AddToWorklist(Add.getNode());
2289 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2294 // fold (udiv x, c) -> alternate
2295 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2296 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2297 if (SDValue Op = BuildUDIV(N))
2301 if (N0.getOpcode() == ISD::UNDEF)
2302 return DAG.getConstant(0, DL, VT);
2303 // X / undef -> undef
2304 if (N1.getOpcode() == ISD::UNDEF)
2310 // handles ISD::SREM and ISD::UREM
2311 SDValue DAGCombiner::visitREM(SDNode *N) {
2312 unsigned Opcode = N->getOpcode();
2313 SDValue N0 = N->getOperand(0);
2314 SDValue N1 = N->getOperand(1);
2315 EVT VT = N->getValueType(0);
2316 bool isSigned = (Opcode == ISD::SREM);
2319 // fold (rem c1, c2) -> c1%c2
2320 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2321 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2323 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2327 // If we know the sign bits of both operands are zero, strength reduce to a
2328 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2329 if (!VT.isVector()) {
2330 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2331 return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2334 // fold (urem x, pow2) -> (and x, pow2-1)
2335 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2336 N1C->getAPIntValue().isPowerOf2()) {
2337 return DAG.getNode(ISD::AND, DL, VT, N0,
2338 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2340 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2341 if (N1.getOpcode() == ISD::SHL) {
2342 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2343 if (SHC->getAPIntValue().isPowerOf2()) {
2345 DAG.getNode(ISD::ADD, DL, VT, N1,
2346 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2348 AddToWorklist(Add.getNode());
2349 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2355 // If X/C can be simplified by the division-by-constant logic, lower
2356 // X%C to the equivalent of X-X/C*C.
2357 if (N1C && !N1C->isNullValue()) {
2358 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2359 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2360 AddToWorklist(Div.getNode());
2361 SDValue OptimizedDiv = combine(Div.getNode());
2362 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2363 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2364 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2365 AddToWorklist(Mul.getNode());
2371 if (N0.getOpcode() == ISD::UNDEF)
2372 return DAG.getConstant(0, DL, VT);
2373 // X % undef -> undef
2374 if (N1.getOpcode() == ISD::UNDEF)
2380 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2381 SDValue N0 = N->getOperand(0);
2382 SDValue N1 = N->getOperand(1);
2383 EVT VT = N->getValueType(0);
2386 // fold (mulhs x, 0) -> 0
2387 if (isNullConstant(N1))
2389 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2390 if (isOneConstant(N1)) {
2392 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2393 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2395 getShiftAmountTy(N0.getValueType())));
2397 // fold (mulhs x, undef) -> 0
2398 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2399 return DAG.getConstant(0, SDLoc(N), VT);
2401 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2403 if (VT.isSimple() && !VT.isVector()) {
2404 MVT Simple = VT.getSimpleVT();
2405 unsigned SimpleSize = Simple.getSizeInBits();
2406 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2407 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2408 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2409 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2410 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2411 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2412 DAG.getConstant(SimpleSize, DL,
2413 getShiftAmountTy(N1.getValueType())));
2414 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2421 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2422 SDValue N0 = N->getOperand(0);
2423 SDValue N1 = N->getOperand(1);
2424 EVT VT = N->getValueType(0);
2427 // fold (mulhu x, 0) -> 0
2428 if (isNullConstant(N1))
2430 // fold (mulhu x, 1) -> 0
2431 if (isOneConstant(N1))
2432 return DAG.getConstant(0, DL, N0.getValueType());
2433 // fold (mulhu x, undef) -> 0
2434 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2435 return DAG.getConstant(0, DL, VT);
2437 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2439 if (VT.isSimple() && !VT.isVector()) {
2440 MVT Simple = VT.getSimpleVT();
2441 unsigned SimpleSize = Simple.getSizeInBits();
2442 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2443 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2444 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2445 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2446 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2447 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2448 DAG.getConstant(SimpleSize, DL,
2449 getShiftAmountTy(N1.getValueType())));
2450 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2457 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2458 /// give the opcodes for the two computations that are being performed. Return
2459 /// true if a simplification was made.
2460 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2462 // If the high half is not needed, just compute the low half.
2463 bool HiExists = N->hasAnyUseOfValue(1);
2465 (!LegalOperations ||
2466 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2467 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2468 return CombineTo(N, Res, Res);
2471 // If the low half is not needed, just compute the high half.
2472 bool LoExists = N->hasAnyUseOfValue(0);
2474 (!LegalOperations ||
2475 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2476 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2477 return CombineTo(N, Res, Res);
2480 // If both halves are used, return as it is.
2481 if (LoExists && HiExists)
2484 // If the two computed results can be simplified separately, separate them.
2486 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2487 AddToWorklist(Lo.getNode());
2488 SDValue LoOpt = combine(Lo.getNode());
2489 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2490 (!LegalOperations ||
2491 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2492 return CombineTo(N, LoOpt, LoOpt);
2496 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2497 AddToWorklist(Hi.getNode());
2498 SDValue HiOpt = combine(Hi.getNode());
2499 if (HiOpt.getNode() && HiOpt != Hi &&
2500 (!LegalOperations ||
2501 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2502 return CombineTo(N, HiOpt, HiOpt);
2508 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2509 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2512 EVT VT = N->getValueType(0);
2515 // If the type is twice as wide is legal, transform the mulhu to a wider
2516 // multiply plus a shift.
2517 if (VT.isSimple() && !VT.isVector()) {
2518 MVT Simple = VT.getSimpleVT();
2519 unsigned SimpleSize = Simple.getSizeInBits();
2520 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2521 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2522 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2523 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2524 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2525 // Compute the high part as N1.
2526 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2527 DAG.getConstant(SimpleSize, DL,
2528 getShiftAmountTy(Lo.getValueType())));
2529 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2530 // Compute the low part as N0.
2531 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2532 return CombineTo(N, Lo, Hi);
2539 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2540 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2543 EVT VT = N->getValueType(0);
2546 // If the type is twice as wide is legal, transform the mulhu to a wider
2547 // multiply plus a shift.
2548 if (VT.isSimple() && !VT.isVector()) {
2549 MVT Simple = VT.getSimpleVT();
2550 unsigned SimpleSize = Simple.getSizeInBits();
2551 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2552 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2553 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2554 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2555 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2556 // Compute the high part as N1.
2557 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2558 DAG.getConstant(SimpleSize, DL,
2559 getShiftAmountTy(Lo.getValueType())));
2560 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2561 // Compute the low part as N0.
2562 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2563 return CombineTo(N, Lo, Hi);
2570 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2571 // (smulo x, 2) -> (saddo x, x)
2572 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2573 if (C2->getAPIntValue() == 2)
2574 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2575 N->getOperand(0), N->getOperand(0));
2580 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2581 // (umulo x, 2) -> (uaddo x, x)
2582 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2583 if (C2->getAPIntValue() == 2)
2584 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2585 N->getOperand(0), N->getOperand(0));
2590 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2591 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM))
2597 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2598 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM))
2604 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2605 SDValue N0 = N->getOperand(0);
2606 SDValue N1 = N->getOperand(1);
2607 EVT VT = N0.getValueType();
2611 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2614 // fold (add c1, c2) -> c1+c2
2615 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2616 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2618 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2620 // canonicalize constant to RHS
2621 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2622 !isConstantIntBuildVectorOrConstantInt(N1))
2623 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2628 /// If this is a binary operator with two operands of the same opcode, try to
2630 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2631 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2632 EVT VT = N0.getValueType();
2633 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2635 // Bail early if none of these transforms apply.
2636 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2638 // For each of OP in AND/OR/XOR:
2639 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2640 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2641 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2642 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2643 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2645 // do not sink logical op inside of a vector extend, since it may combine
2647 EVT Op0VT = N0.getOperand(0).getValueType();
2648 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2649 N0.getOpcode() == ISD::SIGN_EXTEND ||
2650 N0.getOpcode() == ISD::BSWAP ||
2651 // Avoid infinite looping with PromoteIntBinOp.
2652 (N0.getOpcode() == ISD::ANY_EXTEND &&
2653 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2654 (N0.getOpcode() == ISD::TRUNCATE &&
2655 (!TLI.isZExtFree(VT, Op0VT) ||
2656 !TLI.isTruncateFree(Op0VT, VT)) &&
2657 TLI.isTypeLegal(Op0VT))) &&
2659 Op0VT == N1.getOperand(0).getValueType() &&
2660 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2661 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2662 N0.getOperand(0).getValueType(),
2663 N0.getOperand(0), N1.getOperand(0));
2664 AddToWorklist(ORNode.getNode());
2665 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2668 // For each of OP in SHL/SRL/SRA/AND...
2669 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2670 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2671 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2672 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2673 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2674 N0.getOperand(1) == N1.getOperand(1)) {
2675 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2676 N0.getOperand(0).getValueType(),
2677 N0.getOperand(0), N1.getOperand(0));
2678 AddToWorklist(ORNode.getNode());
2679 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2680 ORNode, N0.getOperand(1));
2683 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2684 // Only perform this optimization after type legalization and before
2685 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2686 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2687 // we don't want to undo this promotion.
2688 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2690 if ((N0.getOpcode() == ISD::BITCAST ||
2691 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2692 Level == AfterLegalizeTypes) {
2693 SDValue In0 = N0.getOperand(0);
2694 SDValue In1 = N1.getOperand(0);
2695 EVT In0Ty = In0.getValueType();
2696 EVT In1Ty = In1.getValueType();
2698 // If both incoming values are integers, and the original types are the
2700 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2701 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2702 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2703 AddToWorklist(Op.getNode());
2708 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2709 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2710 // If both shuffles use the same mask, and both shuffle within a single
2711 // vector, then it is worthwhile to move the swizzle after the operation.
2712 // The type-legalizer generates this pattern when loading illegal
2713 // vector types from memory. In many cases this allows additional shuffle
2715 // There are other cases where moving the shuffle after the xor/and/or
2716 // is profitable even if shuffles don't perform a swizzle.
2717 // If both shuffles use the same mask, and both shuffles have the same first
2718 // or second operand, then it might still be profitable to move the shuffle
2719 // after the xor/and/or operation.
2720 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2721 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2722 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2724 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2725 "Inputs to shuffles are not the same type");
2727 // Check that both shuffles use the same mask. The masks are known to be of
2728 // the same length because the result vector type is the same.
2729 // Check also that shuffles have only one use to avoid introducing extra
2731 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2732 SVN0->getMask().equals(SVN1->getMask())) {
2733 SDValue ShOp = N0->getOperand(1);
2735 // Don't try to fold this node if it requires introducing a
2736 // build vector of all zeros that might be illegal at this stage.
2737 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2739 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2744 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2745 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2746 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2747 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2748 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2749 N0->getOperand(0), N1->getOperand(0));
2750 AddToWorklist(NewNode.getNode());
2751 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2752 &SVN0->getMask()[0]);
2755 // Don't try to fold this node if it requires introducing a
2756 // build vector of all zeros that might be illegal at this stage.
2757 ShOp = N0->getOperand(0);
2758 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2760 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2765 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2766 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2767 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2768 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2769 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2770 N0->getOperand(1), N1->getOperand(1));
2771 AddToWorklist(NewNode.getNode());
2772 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2773 &SVN0->getMask()[0]);
2781 /// This contains all DAGCombine rules which reduce two values combined by
2782 /// an And operation to a single value. This makes them reusable in the context
2783 /// of visitSELECT(). Rules involving constants are not included as
2784 /// visitSELECT() already handles those cases.
2785 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2786 SDNode *LocReference) {
2787 EVT VT = N1.getValueType();
2789 // fold (and x, undef) -> 0
2790 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2791 return DAG.getConstant(0, SDLoc(LocReference), VT);
2792 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2793 SDValue LL, LR, RL, RR, CC0, CC1;
2794 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2795 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2796 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2798 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2799 LL.getValueType().isInteger()) {
2800 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2801 if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2802 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2803 LR.getValueType(), LL, RL);
2804 AddToWorklist(ORNode.getNode());
2805 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2807 if (isAllOnesConstant(LR)) {
2808 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2809 if (Op1 == ISD::SETEQ) {
2810 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2811 LR.getValueType(), LL, RL);
2812 AddToWorklist(ANDNode.getNode());
2813 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2815 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2816 if (Op1 == ISD::SETGT) {
2817 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2818 LR.getValueType(), LL, RL);
2819 AddToWorklist(ORNode.getNode());
2820 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2824 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2825 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2826 Op0 == Op1 && LL.getValueType().isInteger() &&
2827 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2828 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2830 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2831 LL, DAG.getConstant(1, DL,
2832 LL.getValueType()));
2833 AddToWorklist(ADDNode.getNode());
2834 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2835 DAG.getConstant(2, DL, LL.getValueType()),
2838 // canonicalize equivalent to ll == rl
2839 if (LL == RR && LR == RL) {
2840 Op1 = ISD::getSetCCSwappedOperands(Op1);
2843 if (LL == RL && LR == RR) {
2844 bool isInteger = LL.getValueType().isInteger();
2845 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2846 if (Result != ISD::SETCC_INVALID &&
2847 (!LegalOperations ||
2848 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2849 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
2850 EVT CCVT = getSetCCResultType(LL.getValueType());
2851 if (N0.getValueType() == CCVT ||
2852 (!LegalOperations && N0.getValueType() == MVT::i1))
2853 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2859 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2860 VT.getSizeInBits() <= 64) {
2861 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2862 APInt ADDC = ADDI->getAPIntValue();
2863 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2864 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2865 // immediate for an add, but it is legal if its top c2 bits are set,
2866 // transform the ADD so the immediate doesn't need to be materialized
2868 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2869 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2870 SRLI->getZExtValue());
2871 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2873 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2876 DAG.getNode(ISD::ADD, DL, VT,
2877 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2878 CombineTo(N0.getNode(), NewAdd);
2879 // Return N so it doesn't get rechecked!
2880 return SDValue(LocReference, 0);
2891 SDValue DAGCombiner::visitAND(SDNode *N) {
2892 SDValue N0 = N->getOperand(0);
2893 SDValue N1 = N->getOperand(1);
2894 EVT VT = N1.getValueType();
2897 if (VT.isVector()) {
2898 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2901 // fold (and x, 0) -> 0, vector edition
2902 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2903 // do not return N0, because undef node may exist in N0
2904 return DAG.getConstant(
2905 APInt::getNullValue(
2906 N0.getValueType().getScalarType().getSizeInBits()),
2907 SDLoc(N), N0.getValueType());
2908 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2909 // do not return N1, because undef node may exist in N1
2910 return DAG.getConstant(
2911 APInt::getNullValue(
2912 N1.getValueType().getScalarType().getSizeInBits()),
2913 SDLoc(N), N1.getValueType());
2915 // fold (and x, -1) -> x, vector edition
2916 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2918 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2922 // fold (and c1, c2) -> c1&c2
2923 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2924 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2925 if (N0C && N1C && !N1C->isOpaque())
2926 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2927 // canonicalize constant to RHS
2928 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2929 !isConstantIntBuildVectorOrConstantInt(N1))
2930 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2931 // fold (and x, -1) -> x
2932 if (isAllOnesConstant(N1))
2934 // if (and x, c) is known to be zero, return 0
2935 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2936 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2937 APInt::getAllOnesValue(BitWidth)))
2938 return DAG.getConstant(0, SDLoc(N), VT);
2940 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2942 // fold (and (or x, C), D) -> D if (C & D) == D
2943 if (N1C && N0.getOpcode() == ISD::OR)
2944 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2945 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2947 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2948 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2949 SDValue N0Op0 = N0.getOperand(0);
2950 APInt Mask = ~N1C->getAPIntValue();
2951 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2952 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2953 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2954 N0.getValueType(), N0Op0);
2956 // Replace uses of the AND with uses of the Zero extend node.
2959 // We actually want to replace all uses of the any_extend with the
2960 // zero_extend, to avoid duplicating things. This will later cause this
2961 // AND to be folded.
2962 CombineTo(N0.getNode(), Zext);
2963 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2966 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2967 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2968 // already be zero by virtue of the width of the base type of the load.
2970 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2972 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2973 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2974 N0.getOpcode() == ISD::LOAD) {
2975 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2976 N0 : N0.getOperand(0) );
2978 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2979 // This can be a pure constant or a vector splat, in which case we treat the
2980 // vector as a scalar and use the splat value.
2981 APInt Constant = APInt::getNullValue(1);
2982 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2983 Constant = C->getAPIntValue();
2984 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2985 APInt SplatValue, SplatUndef;
2986 unsigned SplatBitSize;
2988 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2989 SplatBitSize, HasAnyUndefs);
2991 // Undef bits can contribute to a possible optimisation if set, so
2993 SplatValue |= SplatUndef;
2995 // The splat value may be something like "0x00FFFFFF", which means 0 for
2996 // the first vector value and FF for the rest, repeating. We need a mask
2997 // that will apply equally to all members of the vector, so AND all the
2998 // lanes of the constant together.
2999 EVT VT = Vector->getValueType(0);
3000 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3002 // If the splat value has been compressed to a bitlength lower
3003 // than the size of the vector lane, we need to re-expand it to
3005 if (BitWidth > SplatBitSize)
3006 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3007 SplatBitSize < BitWidth;
3008 SplatBitSize = SplatBitSize * 2)
3009 SplatValue |= SplatValue.shl(SplatBitSize);
3011 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3012 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3013 if (SplatBitSize % BitWidth == 0) {
3014 Constant = APInt::getAllOnesValue(BitWidth);
3015 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3016 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3021 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3022 // actually legal and isn't going to get expanded, else this is a false
3024 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3025 Load->getValueType(0),
3026 Load->getMemoryVT());
3028 // Resize the constant to the same size as the original memory access before
3029 // extension. If it is still the AllOnesValue then this AND is completely
3032 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3035 switch (Load->getExtensionType()) {
3036 default: B = false; break;
3037 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3039 case ISD::NON_EXTLOAD: B = true; break;
3042 if (B && Constant.isAllOnesValue()) {
3043 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3044 // preserve semantics once we get rid of the AND.
3045 SDValue NewLoad(Load, 0);
3046 if (Load->getExtensionType() == ISD::EXTLOAD) {
3047 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3048 Load->getValueType(0), SDLoc(Load),
3049 Load->getChain(), Load->getBasePtr(),
3050 Load->getOffset(), Load->getMemoryVT(),
3051 Load->getMemOperand());
3052 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3053 if (Load->getNumValues() == 3) {
3054 // PRE/POST_INC loads have 3 values.
3055 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3056 NewLoad.getValue(2) };
3057 CombineTo(Load, To, 3, true);
3059 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3063 // Fold the AND away, taking care not to fold to the old load node if we
3065 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3067 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3071 // fold (and (load x), 255) -> (zextload x, i8)
3072 // fold (and (extload x, i16), 255) -> (zextload x, i8)
3073 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3074 if (N1C && (N0.getOpcode() == ISD::LOAD ||
3075 (N0.getOpcode() == ISD::ANY_EXTEND &&
3076 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3077 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3078 LoadSDNode *LN0 = HasAnyExt
3079 ? cast<LoadSDNode>(N0.getOperand(0))
3080 : cast<LoadSDNode>(N0);
3081 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3082 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3083 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3084 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3085 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3086 EVT LoadedVT = LN0->getMemoryVT();
3087 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3089 if (ExtVT == LoadedVT &&
3090 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3094 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3095 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3096 LN0->getMemOperand());
3098 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3099 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3102 // Do not change the width of a volatile load.
3103 // Do not generate loads of non-round integer types since these can
3104 // be expensive (and would be wrong if the type is not byte sized).
3105 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3106 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3108 EVT PtrType = LN0->getOperand(1).getValueType();
3110 unsigned Alignment = LN0->getAlignment();
3111 SDValue NewPtr = LN0->getBasePtr();
3113 // For big endian targets, we need to add an offset to the pointer
3114 // to load the correct bytes. For little endian systems, we merely
3115 // need to read fewer bytes from the same pointer.
3116 if (DAG.getDataLayout().isBigEndian()) {
3117 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3118 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3119 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3121 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3122 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3123 Alignment = MinAlign(Alignment, PtrOff);
3126 AddToWorklist(NewPtr.getNode());
3129 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3130 LN0->getChain(), NewPtr,
3131 LN0->getPointerInfo(),
3132 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3133 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3135 CombineTo(LN0, Load, Load.getValue(1));
3136 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3142 if (SDValue Combined = visitANDLike(N0, N1, N))
3145 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3146 if (N0.getOpcode() == N1.getOpcode())
3147 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3150 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3151 // fold (and (sra)) -> (and (srl)) when possible.
3152 if (!VT.isVector() &&
3153 SimplifyDemandedBits(SDValue(N, 0)))
3154 return SDValue(N, 0);
3156 // fold (zext_inreg (extload x)) -> (zextload x)
3157 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3158 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3159 EVT MemVT = LN0->getMemoryVT();
3160 // If we zero all the possible extended bits, then we can turn this into
3161 // a zextload if we are running before legalize or the operation is legal.
3162 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3163 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3164 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3165 ((!LegalOperations && !LN0->isVolatile()) ||
3166 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3167 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3168 LN0->getChain(), LN0->getBasePtr(),
3169 MemVT, LN0->getMemOperand());
3171 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3172 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3175 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3176 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3178 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3179 EVT MemVT = LN0->getMemoryVT();
3180 // If we zero all the possible extended bits, then we can turn this into
3181 // a zextload if we are running before legalize or the operation is legal.
3182 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3183 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3184 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3185 ((!LegalOperations && !LN0->isVolatile()) ||
3186 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3187 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3188 LN0->getChain(), LN0->getBasePtr(),
3189 MemVT, LN0->getMemOperand());
3191 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3192 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3195 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3196 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3197 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3198 N0.getOperand(1), false);
3199 if (BSwap.getNode())
3206 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3207 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3208 bool DemandHighBits) {
3209 if (!LegalOperations)
3212 EVT VT = N->getValueType(0);
3213 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3215 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3218 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3219 bool LookPassAnd0 = false;
3220 bool LookPassAnd1 = false;
3221 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3223 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3225 if (N0.getOpcode() == ISD::AND) {
3226 if (!N0.getNode()->hasOneUse())
3228 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3229 if (!N01C || N01C->getZExtValue() != 0xFF00)
3231 N0 = N0.getOperand(0);
3232 LookPassAnd0 = true;
3235 if (N1.getOpcode() == ISD::AND) {
3236 if (!N1.getNode()->hasOneUse())
3238 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3239 if (!N11C || N11C->getZExtValue() != 0xFF)
3241 N1 = N1.getOperand(0);
3242 LookPassAnd1 = true;
3245 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3247 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3249 if (!N0.getNode()->hasOneUse() ||
3250 !N1.getNode()->hasOneUse())
3253 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3254 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3257 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3260 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3261 SDValue N00 = N0->getOperand(0);
3262 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3263 if (!N00.getNode()->hasOneUse())
3265 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3266 if (!N001C || N001C->getZExtValue() != 0xFF)
3268 N00 = N00.getOperand(0);
3269 LookPassAnd0 = true;
3272 SDValue N10 = N1->getOperand(0);
3273 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3274 if (!N10.getNode()->hasOneUse())
3276 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3277 if (!N101C || N101C->getZExtValue() != 0xFF00)
3279 N10 = N10.getOperand(0);
3280 LookPassAnd1 = true;
3286 // Make sure everything beyond the low halfword gets set to zero since the SRL
3287 // 16 will clear the top bits.
3288 unsigned OpSizeInBits = VT.getSizeInBits();
3289 if (DemandHighBits && OpSizeInBits > 16) {
3290 // If the left-shift isn't masked out then the only way this is a bswap is
3291 // if all bits beyond the low 8 are 0. In that case the entire pattern
3292 // reduces to a left shift anyway: leave it for other parts of the combiner.
3296 // However, if the right shift isn't masked out then it might be because
3297 // it's not needed. See if we can spot that too.
3298 if (!LookPassAnd1 &&
3299 !DAG.MaskedValueIsZero(
3300 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3304 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3305 if (OpSizeInBits > 16) {
3307 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3308 DAG.getConstant(OpSizeInBits - 16, DL,
3309 getShiftAmountTy(VT)));
3314 /// Return true if the specified node is an element that makes up a 32-bit
3315 /// packed halfword byteswap.
3316 /// ((x & 0x000000ff) << 8) |
3317 /// ((x & 0x0000ff00) >> 8) |
3318 /// ((x & 0x00ff0000) << 8) |
3319 /// ((x & 0xff000000) >> 8)
3320 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3321 if (!N.getNode()->hasOneUse())
3324 unsigned Opc = N.getOpcode();
3325 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3328 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3333 switch (N1C->getZExtValue()) {
3336 case 0xFF: Num = 0; break;
3337 case 0xFF00: Num = 1; break;
3338 case 0xFF0000: Num = 2; break;
3339 case 0xFF000000: Num = 3; break;
3342 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3343 SDValue N0 = N.getOperand(0);
3344 if (Opc == ISD::AND) {
3345 if (Num == 0 || Num == 2) {
3347 // (x >> 8) & 0xff0000
3348 if (N0.getOpcode() != ISD::SRL)
3350 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3351 if (!C || C->getZExtValue() != 8)
3354 // (x << 8) & 0xff00
3355 // (x << 8) & 0xff000000
3356 if (N0.getOpcode() != ISD::SHL)
3358 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3359 if (!C || C->getZExtValue() != 8)
3362 } else if (Opc == ISD::SHL) {
3364 // (x & 0xff0000) << 8
3365 if (Num != 0 && Num != 2)
3367 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3368 if (!C || C->getZExtValue() != 8)
3370 } else { // Opc == ISD::SRL
3371 // (x & 0xff00) >> 8
3372 // (x & 0xff000000) >> 8
3373 if (Num != 1 && Num != 3)
3375 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3376 if (!C || C->getZExtValue() != 8)
3383 Parts[Num] = N0.getOperand(0).getNode();
3387 /// Match a 32-bit packed halfword bswap. That is
3388 /// ((x & 0x000000ff) << 8) |
3389 /// ((x & 0x0000ff00) >> 8) |
3390 /// ((x & 0x00ff0000) << 8) |
3391 /// ((x & 0xff000000) >> 8)
3392 /// => (rotl (bswap x), 16)
3393 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3394 if (!LegalOperations)
3397 EVT VT = N->getValueType(0);
3400 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3404 // (or (or (and), (and)), (or (and), (and)))
3405 // (or (or (or (and), (and)), (and)), (and))
3406 if (N0.getOpcode() != ISD::OR)
3408 SDValue N00 = N0.getOperand(0);
3409 SDValue N01 = N0.getOperand(1);
3410 SDNode *Parts[4] = {};
3412 if (N1.getOpcode() == ISD::OR &&
3413 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3414 // (or (or (and), (and)), (or (and), (and)))
3415 SDValue N000 = N00.getOperand(0);
3416 if (!isBSwapHWordElement(N000, Parts))
3419 SDValue N001 = N00.getOperand(1);
3420 if (!isBSwapHWordElement(N001, Parts))
3422 SDValue N010 = N01.getOperand(0);
3423 if (!isBSwapHWordElement(N010, Parts))
3425 SDValue N011 = N01.getOperand(1);
3426 if (!isBSwapHWordElement(N011, Parts))
3429 // (or (or (or (and), (and)), (and)), (and))
3430 if (!isBSwapHWordElement(N1, Parts))
3432 if (!isBSwapHWordElement(N01, Parts))
3434 if (N00.getOpcode() != ISD::OR)
3436 SDValue N000 = N00.getOperand(0);
3437 if (!isBSwapHWordElement(N000, Parts))
3439 SDValue N001 = N00.getOperand(1);
3440 if (!isBSwapHWordElement(N001, Parts))
3444 // Make sure the parts are all coming from the same node.
3445 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3449 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3450 SDValue(Parts[0], 0));
3452 // Result of the bswap should be rotated by 16. If it's not legal, then
3453 // do (x << 16) | (x >> 16).
3454 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3455 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3456 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3457 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3458 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3459 return DAG.getNode(ISD::OR, DL, VT,
3460 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3461 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3464 /// This contains all DAGCombine rules which reduce two values combined by
3465 /// an Or operation to a single value \see visitANDLike().
3466 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3467 EVT VT = N1.getValueType();
3468 // fold (or x, undef) -> -1
3469 if (!LegalOperations &&
3470 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3471 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3472 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3473 SDLoc(LocReference), VT);
3475 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3476 SDValue LL, LR, RL, RR, CC0, CC1;
3477 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3478 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3479 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3481 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3482 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3483 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3484 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3485 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3486 LR.getValueType(), LL, RL);
3487 AddToWorklist(ORNode.getNode());
3488 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3490 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3491 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3492 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3493 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3494 LR.getValueType(), LL, RL);
3495 AddToWorklist(ANDNode.getNode());
3496 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3499 // canonicalize equivalent to ll == rl
3500 if (LL == RR && LR == RL) {
3501 Op1 = ISD::getSetCCSwappedOperands(Op1);
3504 if (LL == RL && LR == RR) {
3505 bool isInteger = LL.getValueType().isInteger();
3506 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3507 if (Result != ISD::SETCC_INVALID &&
3508 (!LegalOperations ||
3509 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3510 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3511 EVT CCVT = getSetCCResultType(LL.getValueType());
3512 if (N0.getValueType() == CCVT ||
3513 (!LegalOperations && N0.getValueType() == MVT::i1))
3514 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3520 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3521 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3522 // Don't increase # computations.
3523 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3524 // We can only do this xform if we know that bits from X that are set in C2
3525 // but not in C1 are already zero. Likewise for Y.
3526 if (const ConstantSDNode *N0O1C =
3527 getAsNonOpaqueConstant(N0.getOperand(1))) {
3528 if (const ConstantSDNode *N1O1C =
3529 getAsNonOpaqueConstant(N1.getOperand(1))) {
3530 // We can only do this xform if we know that bits from X that are set in
3531 // C2 but not in C1 are already zero. Likewise for Y.
3532 const APInt &LHSMask = N0O1C->getAPIntValue();
3533 const APInt &RHSMask = N1O1C->getAPIntValue();
3535 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3536 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3537 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3538 N0.getOperand(0), N1.getOperand(0));
3539 SDLoc DL(LocReference);
3540 return DAG.getNode(ISD::AND, DL, VT, X,
3541 DAG.getConstant(LHSMask | RHSMask, DL, VT));
3547 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3548 if (N0.getOpcode() == ISD::AND &&
3549 N1.getOpcode() == ISD::AND &&
3550 N0.getOperand(0) == N1.getOperand(0) &&
3551 // Don't increase # computations.
3552 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3553 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3554 N0.getOperand(1), N1.getOperand(1));
3555 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3561 SDValue DAGCombiner::visitOR(SDNode *N) {
3562 SDValue N0 = N->getOperand(0);
3563 SDValue N1 = N->getOperand(1);
3564 EVT VT = N1.getValueType();
3567 if (VT.isVector()) {
3568 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3571 // fold (or x, 0) -> x, vector edition
3572 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3574 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3577 // fold (or x, -1) -> -1, vector edition
3578 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3579 // do not return N0, because undef node may exist in N0
3580 return DAG.getConstant(
3581 APInt::getAllOnesValue(
3582 N0.getValueType().getScalarType().getSizeInBits()),
3583 SDLoc(N), N0.getValueType());
3584 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3585 // do not return N1, because undef node may exist in N1
3586 return DAG.getConstant(
3587 APInt::getAllOnesValue(
3588 N1.getValueType().getScalarType().getSizeInBits()),
3589 SDLoc(N), N1.getValueType());
3591 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3592 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3593 // Do this only if the resulting shuffle is legal.
3594 if (isa<ShuffleVectorSDNode>(N0) &&
3595 isa<ShuffleVectorSDNode>(N1) &&
3596 // Avoid folding a node with illegal type.
3597 TLI.isTypeLegal(VT) &&
3598 N0->getOperand(1) == N1->getOperand(1) &&
3599 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3600 bool CanFold = true;
3601 unsigned NumElts = VT.getVectorNumElements();
3602 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3603 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3604 // We construct two shuffle masks:
3605 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3606 // and N1 as the second operand.
3607 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3608 // and N0 as the second operand.
3609 // We do this because OR is commutable and therefore there might be
3610 // two ways to fold this node into a shuffle.
3611 SmallVector<int,4> Mask1;
3612 SmallVector<int,4> Mask2;
3614 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3615 int M0 = SV0->getMaskElt(i);
3616 int M1 = SV1->getMaskElt(i);
3618 // Both shuffle indexes are undef. Propagate Undef.
3619 if (M0 < 0 && M1 < 0) {
3620 Mask1.push_back(M0);
3621 Mask2.push_back(M0);
3625 if (M0 < 0 || M1 < 0 ||
3626 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3627 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3632 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3633 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3637 // Fold this sequence only if the resulting shuffle is 'legal'.
3638 if (TLI.isShuffleMaskLegal(Mask1, VT))
3639 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3640 N1->getOperand(0), &Mask1[0]);
3641 if (TLI.isShuffleMaskLegal(Mask2, VT))
3642 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3643 N0->getOperand(0), &Mask2[0]);
3648 // fold (or c1, c2) -> c1|c2
3649 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3650 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3651 if (N0C && N1C && !N1C->isOpaque())
3652 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3653 // canonicalize constant to RHS
3654 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3655 !isConstantIntBuildVectorOrConstantInt(N1))
3656 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3657 // fold (or x, 0) -> x
3658 if (isNullConstant(N1))
3660 // fold (or x, -1) -> -1
3661 if (isAllOnesConstant(N1))
3663 // fold (or x, c) -> c iff (x & ~c) == 0
3664 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3667 if (SDValue Combined = visitORLike(N0, N1, N))
3670 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3671 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3673 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3677 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3679 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3680 // iff (c1 & c2) == 0.
3681 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3682 isa<ConstantSDNode>(N0.getOperand(1))) {
3683 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3684 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3685 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3688 ISD::AND, SDLoc(N), VT,
3689 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3693 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3694 if (N0.getOpcode() == N1.getOpcode())
3695 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3698 // See if this is some rotate idiom.
3699 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3700 return SDValue(Rot, 0);
3702 // Simplify the operands using demanded-bits information.
3703 if (!VT.isVector() &&
3704 SimplifyDemandedBits(SDValue(N, 0)))
3705 return SDValue(N, 0);
3710 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3711 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3712 if (Op.getOpcode() == ISD::AND) {
3713 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3714 Mask = Op.getOperand(1);
3715 Op = Op.getOperand(0);
3721 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3729 // Return true if we can prove that, whenever Neg and Pos are both in the
3730 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3731 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3733 // (or (shift1 X, Neg), (shift2 X, Pos))
3735 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3736 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3737 // to consider shift amounts with defined behavior.
3738 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3739 // If OpSize is a power of 2 then:
3741 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3742 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3744 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3745 // for the stronger condition:
3747 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3749 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3750 // we can just replace Neg with Neg' for the rest of the function.
3752 // In other cases we check for the even stronger condition:
3754 // Neg == OpSize - Pos [B]
3756 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3757 // behavior if Pos == 0 (and consequently Neg == OpSize).
3759 // We could actually use [A] whenever OpSize is a power of 2, but the
3760 // only extra cases that it would match are those uninteresting ones
3761 // where Neg and Pos are never in range at the same time. E.g. for
3762 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3763 // as well as (sub 32, Pos), but:
3765 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3767 // always invokes undefined behavior for 32-bit X.
3769 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3770 unsigned MaskLoBits = 0;
3771 if (Neg.getOpcode() == ISD::AND &&
3772 isPowerOf2_64(OpSize) &&
3773 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3774 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3775 Neg = Neg.getOperand(0);
3776 MaskLoBits = Log2_64(OpSize);
3779 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3780 if (Neg.getOpcode() != ISD::SUB)
3782 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3785 SDValue NegOp1 = Neg.getOperand(1);
3787 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3788 // Pos'. The truncation is redundant for the purpose of the equality.
3790 Pos.getOpcode() == ISD::AND &&
3791 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3792 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3793 Pos = Pos.getOperand(0);
3795 // The condition we need is now:
3797 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3799 // If NegOp1 == Pos then we need:
3801 // OpSize & Mask == NegC & Mask
3803 // (because "x & Mask" is a truncation and distributes through subtraction).
3806 Width = NegC->getAPIntValue();
3807 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3808 // Then the condition we want to prove becomes:
3810 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3812 // which, again because "x & Mask" is a truncation, becomes:
3814 // NegC & Mask == (OpSize - PosC) & Mask
3815 // OpSize & Mask == (NegC + PosC) & Mask
3816 else if (Pos.getOpcode() == ISD::ADD &&
3817 Pos.getOperand(0) == NegOp1 &&
3818 Pos.getOperand(1).getOpcode() == ISD::Constant)
3819 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3820 NegC->getAPIntValue());
3824 // Now we just need to check that OpSize & Mask == Width & Mask.
3826 // Opsize & Mask is 0 since Mask is Opsize - 1.
3827 return Width.getLoBits(MaskLoBits) == 0;
3828 return Width == OpSize;
3831 // A subroutine of MatchRotate used once we have found an OR of two opposite
3832 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3833 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3834 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3835 // Neg with outer conversions stripped away.
3836 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3837 SDValue Neg, SDValue InnerPos,
3838 SDValue InnerNeg, unsigned PosOpcode,
3839 unsigned NegOpcode, SDLoc DL) {
3840 // fold (or (shl x, (*ext y)),
3841 // (srl x, (*ext (sub 32, y)))) ->
3842 // (rotl x, y) or (rotr x, (sub 32, y))
3844 // fold (or (shl x, (*ext (sub 32, y))),
3845 // (srl x, (*ext y))) ->
3846 // (rotr x, y) or (rotl x, (sub 32, y))
3847 EVT VT = Shifted.getValueType();
3848 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3849 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3850 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3851 HasPos ? Pos : Neg).getNode();
3857 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3858 // idioms for rotate, and if the target supports rotation instructions, generate
3860 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3861 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3862 EVT VT = LHS.getValueType();
3863 if (!TLI.isTypeLegal(VT)) return nullptr;
3865 // The target must have at least one rotate flavor.
3866 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3867 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3868 if (!HasROTL && !HasROTR) return nullptr;
3870 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3871 SDValue LHSShift; // The shift.
3872 SDValue LHSMask; // AND value if any.
3873 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3874 return nullptr; // Not part of a rotate.
3876 SDValue RHSShift; // The shift.
3877 SDValue RHSMask; // AND value if any.
3878 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3879 return nullptr; // Not part of a rotate.
3881 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3882 return nullptr; // Not shifting the same value.
3884 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3885 return nullptr; // Shifts must disagree.
3887 // Canonicalize shl to left side in a shl/srl pair.
3888 if (RHSShift.getOpcode() == ISD::SHL) {
3889 std::swap(LHS, RHS);
3890 std::swap(LHSShift, RHSShift);
3891 std::swap(LHSMask , RHSMask );
3894 unsigned OpSizeInBits = VT.getSizeInBits();
3895 SDValue LHSShiftArg = LHSShift.getOperand(0);
3896 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3897 SDValue RHSShiftArg = RHSShift.getOperand(0);
3898 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3900 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3901 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3902 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3903 RHSShiftAmt.getOpcode() == ISD::Constant) {
3904 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3905 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3906 if ((LShVal + RShVal) != OpSizeInBits)
3909 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3910 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3912 // If there is an AND of either shifted operand, apply it to the result.
3913 if (LHSMask.getNode() || RHSMask.getNode()) {
3914 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3916 if (LHSMask.getNode()) {
3917 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3918 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3920 if (RHSMask.getNode()) {
3921 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3922 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3925 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3928 return Rot.getNode();
3931 // If there is a mask here, and we have a variable shift, we can't be sure
3932 // that we're masking out the right stuff.
3933 if (LHSMask.getNode() || RHSMask.getNode())
3936 // If the shift amount is sign/zext/any-extended just peel it off.
3937 SDValue LExtOp0 = LHSShiftAmt;
3938 SDValue RExtOp0 = RHSShiftAmt;
3939 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3940 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3941 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3942 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3943 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3944 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3945 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3946 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3947 LExtOp0 = LHSShiftAmt.getOperand(0);
3948 RExtOp0 = RHSShiftAmt.getOperand(0);
3951 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3952 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3956 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3957 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3964 SDValue DAGCombiner::visitXOR(SDNode *N) {
3965 SDValue N0 = N->getOperand(0);
3966 SDValue N1 = N->getOperand(1);
3967 EVT VT = N0.getValueType();
3970 if (VT.isVector()) {
3971 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3974 // fold (xor x, 0) -> x, vector edition
3975 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3977 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3981 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3982 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3983 return DAG.getConstant(0, SDLoc(N), VT);
3984 // fold (xor x, undef) -> undef
3985 if (N0.getOpcode() == ISD::UNDEF)
3987 if (N1.getOpcode() == ISD::UNDEF)
3989 // fold (xor c1, c2) -> c1^c2
3990 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3991 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3993 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3994 // canonicalize constant to RHS
3995 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3996 !isConstantIntBuildVectorOrConstantInt(N1))
3997 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3998 // fold (xor x, 0) -> x
3999 if (isNullConstant(N1))
4002 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4005 // fold !(x cc y) -> (x !cc y)
4006 SDValue LHS, RHS, CC;
4007 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4008 bool isInt = LHS.getValueType().isInteger();
4009 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4012 if (!LegalOperations ||
4013 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4014 switch (N0.getOpcode()) {
4016 llvm_unreachable("Unhandled SetCC Equivalent!");
4018 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4019 case ISD::SELECT_CC:
4020 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4021 N0.getOperand(3), NotCC);
4026 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4027 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4028 N0.getNode()->hasOneUse() &&
4029 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4030 SDValue V = N0.getOperand(0);
4032 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4033 DAG.getConstant(1, DL, V.getValueType()));
4034 AddToWorklist(V.getNode());
4035 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4038 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4039 if (isOneConstant(N1) && VT == MVT::i1 &&
4040 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4041 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4042 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4043 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4044 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4045 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4046 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4047 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4050 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4051 if (isAllOnesConstant(N1) &&
4052 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4053 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4054 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4055 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4056 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4057 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4058 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4059 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4062 // fold (xor (and x, y), y) -> (and (not x), y)
4063 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4064 N0->getOperand(1) == N1) {
4065 SDValue X = N0->getOperand(0);
4066 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4067 AddToWorklist(NotX.getNode());
4068 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4070 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4071 if (N1C && N0.getOpcode() == ISD::XOR) {
4072 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4074 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4075 DAG.getConstant(N1C->getAPIntValue() ^
4076 N00C->getAPIntValue(), DL, VT));
4078 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4080 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4081 DAG.getConstant(N1C->getAPIntValue() ^
4082 N01C->getAPIntValue(), DL, VT));
4085 // fold (xor x, x) -> 0
4087 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4089 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4090 // Here is a concrete example of this equivalence:
4092 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
4093 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4097 // i16 ~1 == 0b1111111111111110
4098 // i16 rol(~1, 14) == 0b1011111111111111
4100 // Some additional tips to help conceptualize this transform:
4101 // - Try to see the operation as placing a single zero in a value of all ones.
4102 // - There exists no value for x which would allow the result to contain zero.
4103 // - Values of x larger than the bitwidth are undefined and do not require a
4104 // consistent result.
4105 // - Pushing the zero left requires shifting one bits in from the right.
4106 // A rotate left of ~1 is a nice way of achieving the desired result.
4107 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4108 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4110 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4114 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4115 if (N0.getOpcode() == N1.getOpcode())
4116 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4119 // Simplify the expression using non-local knowledge.
4120 if (!VT.isVector() &&
4121 SimplifyDemandedBits(SDValue(N, 0)))
4122 return SDValue(N, 0);
4127 /// Handle transforms common to the three shifts, when the shift amount is a
4129 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4130 SDNode *LHS = N->getOperand(0).getNode();
4131 if (!LHS->hasOneUse()) return SDValue();
4133 // We want to pull some binops through shifts, so that we have (and (shift))
4134 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4135 // thing happens with address calculations, so it's important to canonicalize
4137 bool HighBitSet = false; // Can we transform this if the high bit is set?
4139 switch (LHS->getOpcode()) {
4140 default: return SDValue();
4143 HighBitSet = false; // We can only transform sra if the high bit is clear.
4146 HighBitSet = true; // We can only transform sra if the high bit is set.
4149 if (N->getOpcode() != ISD::SHL)
4150 return SDValue(); // only shl(add) not sr[al](add).
4151 HighBitSet = false; // We can only transform sra if the high bit is clear.
4155 // We require the RHS of the binop to be a constant and not opaque as well.
4156 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4157 if (!BinOpCst) return SDValue();
4159 // FIXME: disable this unless the input to the binop is a shift by a constant.
4160 // If it is not a shift, it pessimizes some common cases like:
4162 // void foo(int *X, int i) { X[i & 1235] = 1; }
4163 // int bar(int *X, int i) { return X[i & 255]; }
4164 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4165 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4166 BinOpLHSVal->getOpcode() != ISD::SRA &&
4167 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4168 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4171 EVT VT = N->getValueType(0);
4173 // If this is a signed shift right, and the high bit is modified by the
4174 // logical operation, do not perform the transformation. The highBitSet
4175 // boolean indicates the value of the high bit of the constant which would
4176 // cause it to be modified for this operation.
4177 if (N->getOpcode() == ISD::SRA) {
4178 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4179 if (BinOpRHSSignSet != HighBitSet)
4183 if (!TLI.isDesirableToCommuteWithShift(LHS))
4186 // Fold the constants, shifting the binop RHS by the shift amount.
4187 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4189 LHS->getOperand(1), N->getOperand(1));
4190 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4192 // Create the new shift.
4193 SDValue NewShift = DAG.getNode(N->getOpcode(),
4194 SDLoc(LHS->getOperand(0)),
4195 VT, LHS->getOperand(0), N->getOperand(1));
4197 // Create the new binop.
4198 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4201 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4202 assert(N->getOpcode() == ISD::TRUNCATE);
4203 assert(N->getOperand(0).getOpcode() == ISD::AND);
4205 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4206 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4207 SDValue N01 = N->getOperand(0).getOperand(1);
4209 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4210 if (!N01C->isOpaque()) {
4211 EVT TruncVT = N->getValueType(0);
4212 SDValue N00 = N->getOperand(0).getOperand(0);
4213 APInt TruncC = N01C->getAPIntValue();
4214 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4217 return DAG.getNode(ISD::AND, DL, TruncVT,
4218 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4219 DAG.getConstant(TruncC, DL, TruncVT));
4227 SDValue DAGCombiner::visitRotate(SDNode *N) {
4228 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4229 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4230 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4231 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4232 if (NewOp1.getNode())
4233 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4234 N->getOperand(0), NewOp1);
4239 SDValue DAGCombiner::visitSHL(SDNode *N) {
4240 SDValue N0 = N->getOperand(0);
4241 SDValue N1 = N->getOperand(1);
4242 EVT VT = N0.getValueType();
4243 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4246 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4247 if (VT.isVector()) {
4248 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4251 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4252 // If setcc produces all-one true value then:
4253 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4254 if (N1CV && N1CV->isConstant()) {
4255 if (N0.getOpcode() == ISD::AND) {
4256 SDValue N00 = N0->getOperand(0);
4257 SDValue N01 = N0->getOperand(1);
4258 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4260 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4261 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4262 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4263 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4265 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4268 N1C = isConstOrConstSplat(N1);
4273 // fold (shl c1, c2) -> c1<<c2
4274 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4275 if (N0C && N1C && !N1C->isOpaque())
4276 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4277 // fold (shl 0, x) -> 0
4278 if (isNullConstant(N0))
4280 // fold (shl x, c >= size(x)) -> undef
4281 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4282 return DAG.getUNDEF(VT);
4283 // fold (shl x, 0) -> x
4284 if (N1C && N1C->isNullValue())
4286 // fold (shl undef, x) -> 0
4287 if (N0.getOpcode() == ISD::UNDEF)
4288 return DAG.getConstant(0, SDLoc(N), VT);
4289 // if (shl x, c) is known to be zero, return 0
4290 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4291 APInt::getAllOnesValue(OpSizeInBits)))
4292 return DAG.getConstant(0, SDLoc(N), VT);
4293 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4294 if (N1.getOpcode() == ISD::TRUNCATE &&
4295 N1.getOperand(0).getOpcode() == ISD::AND) {
4296 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4297 if (NewOp1.getNode())
4298 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4301 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4302 return SDValue(N, 0);
4304 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4305 if (N1C && N0.getOpcode() == ISD::SHL) {
4306 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4307 uint64_t c1 = N0C1->getZExtValue();
4308 uint64_t c2 = N1C->getZExtValue();
4310 if (c1 + c2 >= OpSizeInBits)
4311 return DAG.getConstant(0, DL, VT);
4312 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4313 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4317 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4318 // For this to be valid, the second form must not preserve any of the bits
4319 // that are shifted out by the inner shift in the first form. This means
4320 // the outer shift size must be >= the number of bits added by the ext.
4321 // As a corollary, we don't care what kind of ext it is.
4322 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4323 N0.getOpcode() == ISD::ANY_EXTEND ||
4324 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4325 N0.getOperand(0).getOpcode() == ISD::SHL) {
4326 SDValue N0Op0 = N0.getOperand(0);
4327 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4328 uint64_t c1 = N0Op0C1->getZExtValue();
4329 uint64_t c2 = N1C->getZExtValue();
4330 EVT InnerShiftVT = N0Op0.getValueType();
4331 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4332 if (c2 >= OpSizeInBits - InnerShiftSize) {
4334 if (c1 + c2 >= OpSizeInBits)
4335 return DAG.getConstant(0, DL, VT);
4336 return DAG.getNode(ISD::SHL, DL, VT,
4337 DAG.getNode(N0.getOpcode(), DL, VT,
4338 N0Op0->getOperand(0)),
4339 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4344 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4345 // Only fold this if the inner zext has no other uses to avoid increasing
4346 // the total number of instructions.
4347 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4348 N0.getOperand(0).getOpcode() == ISD::SRL) {
4349 SDValue N0Op0 = N0.getOperand(0);
4350 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4351 uint64_t c1 = N0Op0C1->getZExtValue();
4352 if (c1 < VT.getScalarSizeInBits()) {
4353 uint64_t c2 = N1C->getZExtValue();
4355 SDValue NewOp0 = N0.getOperand(0);
4356 EVT CountVT = NewOp0.getOperand(1).getValueType();
4358 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4360 DAG.getConstant(c2, DL, CountVT));
4361 AddToWorklist(NewSHL.getNode());
4362 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4368 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
4369 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2
4370 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4371 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4372 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4373 uint64_t C1 = N0C1->getZExtValue();
4374 uint64_t C2 = N1C->getZExtValue();
4377 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4378 DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4379 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4380 DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4384 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4385 // (and (srl x, (sub c1, c2), MASK)
4386 // Only fold this if the inner shift has no other uses -- if it does, folding
4387 // this will increase the total number of instructions.
4388 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4389 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4390 uint64_t c1 = N0C1->getZExtValue();
4391 if (c1 < OpSizeInBits) {
4392 uint64_t c2 = N1C->getZExtValue();
4393 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4396 Mask = Mask.shl(c2 - c1);
4398 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4399 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4401 Mask = Mask.lshr(c1 - c2);
4403 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4404 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4407 return DAG.getNode(ISD::AND, DL, VT, Shift,
4408 DAG.getConstant(Mask, DL, VT));
4412 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4413 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4414 unsigned BitSize = VT.getScalarSizeInBits();
4416 SDValue HiBitsMask =
4417 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4418 BitSize - N1C->getZExtValue()),
4420 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4424 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4425 // Variant of version done on multiply, except mul by a power of 2 is turned
4428 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4429 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4430 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4431 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4432 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4433 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4436 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4437 if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4438 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4439 if (SDValue Folded =
4440 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4441 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4445 if (N1C && !N1C->isOpaque())
4446 if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4452 SDValue DAGCombiner::visitSRA(SDNode *N) {
4453 SDValue N0 = N->getOperand(0);
4454 SDValue N1 = N->getOperand(1);
4455 EVT VT = N0.getValueType();
4456 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4459 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4460 if (VT.isVector()) {
4461 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4464 N1C = isConstOrConstSplat(N1);
4467 // fold (sra c1, c2) -> (sra c1, c2)
4468 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4469 if (N0C && N1C && !N1C->isOpaque())
4470 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4471 // fold (sra 0, x) -> 0
4472 if (isNullConstant(N0))
4474 // fold (sra -1, x) -> -1
4475 if (isAllOnesConstant(N0))
4477 // fold (sra x, (setge c, size(x))) -> undef
4478 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4479 return DAG.getUNDEF(VT);
4480 // fold (sra x, 0) -> x
4481 if (N1C && N1C->isNullValue())
4483 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4485 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4486 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4487 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4489 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4490 ExtVT, VT.getVectorNumElements());
4491 if ((!LegalOperations ||
4492 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4493 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4494 N0.getOperand(0), DAG.getValueType(ExtVT));
4497 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4498 if (N1C && N0.getOpcode() == ISD::SRA) {
4499 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4500 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4501 if (Sum >= OpSizeInBits)
4502 Sum = OpSizeInBits - 1;
4504 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4505 DAG.getConstant(Sum, DL, N1.getValueType()));
4509 // fold (sra (shl X, m), (sub result_size, n))
4510 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4511 // result_size - n != m.
4512 // If truncate is free for the target sext(shl) is likely to result in better
4514 if (N0.getOpcode() == ISD::SHL && N1C) {
4515 // Get the two constanst of the shifts, CN0 = m, CN = n.
4516 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4518 LLVMContext &Ctx = *DAG.getContext();
4519 // Determine what the truncate's result bitsize and type would be.
4520 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4523 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4525 // Determine the residual right-shift amount.
4526 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4528 // If the shift is not a no-op (in which case this should be just a sign
4529 // extend already), the truncated to type is legal, sign_extend is legal
4530 // on that type, and the truncate to that type is both legal and free,
4531 // perform the transform.
4532 if ((ShiftAmt > 0) &&
4533 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4534 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4535 TLI.isTruncateFree(VT, TruncVT)) {
4538 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4539 getShiftAmountTy(N0.getOperand(0).getValueType()));
4540 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4541 N0.getOperand(0), Amt);
4542 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4544 return DAG.getNode(ISD::SIGN_EXTEND, DL,
4545 N->getValueType(0), Trunc);
4550 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4551 if (N1.getOpcode() == ISD::TRUNCATE &&
4552 N1.getOperand(0).getOpcode() == ISD::AND) {
4553 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4554 if (NewOp1.getNode())
4555 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4558 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4559 // if c1 is equal to the number of bits the trunc removes
4560 if (N0.getOpcode() == ISD::TRUNCATE &&
4561 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4562 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4563 N0.getOperand(0).hasOneUse() &&
4564 N0.getOperand(0).getOperand(1).hasOneUse() &&
4566 SDValue N0Op0 = N0.getOperand(0);
4567 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4568 unsigned LargeShiftVal = LargeShift->getZExtValue();
4569 EVT LargeVT = N0Op0.getValueType();
4571 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4574 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4575 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4576 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4577 N0Op0.getOperand(0), Amt);
4578 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4583 // Simplify, based on bits shifted out of the LHS.
4584 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4585 return SDValue(N, 0);
4588 // If the sign bit is known to be zero, switch this to a SRL.
4589 if (DAG.SignBitIsZero(N0))
4590 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4592 if (N1C && !N1C->isOpaque())
4593 if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4599 SDValue DAGCombiner::visitSRL(SDNode *N) {
4600 SDValue N0 = N->getOperand(0);
4601 SDValue N1 = N->getOperand(1);
4602 EVT VT = N0.getValueType();
4603 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4606 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4607 if (VT.isVector()) {
4608 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4611 N1C = isConstOrConstSplat(N1);
4614 // fold (srl c1, c2) -> c1 >>u c2
4615 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4616 if (N0C && N1C && !N1C->isOpaque())
4617 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4618 // fold (srl 0, x) -> 0
4619 if (isNullConstant(N0))
4621 // fold (srl x, c >= size(x)) -> undef
4622 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4623 return DAG.getUNDEF(VT);
4624 // fold (srl x, 0) -> x
4625 if (N1C && N1C->isNullValue())
4627 // if (srl x, c) is known to be zero, return 0
4628 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4629 APInt::getAllOnesValue(OpSizeInBits)))
4630 return DAG.getConstant(0, SDLoc(N), VT);
4632 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4633 if (N1C && N0.getOpcode() == ISD::SRL) {
4634 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4635 uint64_t c1 = N01C->getZExtValue();
4636 uint64_t c2 = N1C->getZExtValue();
4638 if (c1 + c2 >= OpSizeInBits)
4639 return DAG.getConstant(0, DL, VT);
4640 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4641 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4645 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4646 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4647 N0.getOperand(0).getOpcode() == ISD::SRL &&
4648 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4650 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4651 uint64_t c2 = N1C->getZExtValue();
4652 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4653 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4654 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4655 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4656 if (c1 + OpSizeInBits == InnerShiftSize) {
4658 if (c1 + c2 >= InnerShiftSize)
4659 return DAG.getConstant(0, DL, VT);
4660 return DAG.getNode(ISD::TRUNCATE, DL, VT,
4661 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4662 N0.getOperand(0)->getOperand(0),
4663 DAG.getConstant(c1 + c2, DL,
4668 // fold (srl (shl x, c), c) -> (and x, cst2)
4669 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4670 unsigned BitSize = N0.getScalarValueSizeInBits();
4671 if (BitSize <= 64) {
4672 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4674 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4675 DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4679 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4680 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4681 // Shifting in all undef bits?
4682 EVT SmallVT = N0.getOperand(0).getValueType();
4683 unsigned BitSize = SmallVT.getScalarSizeInBits();
4684 if (N1C->getZExtValue() >= BitSize)
4685 return DAG.getUNDEF(VT);
4687 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4688 uint64_t ShiftAmt = N1C->getZExtValue();
4690 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4692 DAG.getConstant(ShiftAmt, DL0,
4693 getShiftAmountTy(SmallVT)));
4694 AddToWorklist(SmallShift.getNode());
4695 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4697 return DAG.getNode(ISD::AND, DL, VT,
4698 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4699 DAG.getConstant(Mask, DL, VT));
4703 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4704 // bit, which is unmodified by sra.
4705 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4706 if (N0.getOpcode() == ISD::SRA)
4707 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4710 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4711 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4712 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4713 APInt KnownZero, KnownOne;
4714 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4716 // If any of the input bits are KnownOne, then the input couldn't be all
4717 // zeros, thus the result of the srl will always be zero.
4718 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4720 // If all of the bits input the to ctlz node are known to be zero, then
4721 // the result of the ctlz is "32" and the result of the shift is one.
4722 APInt UnknownBits = ~KnownZero;
4723 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4725 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4726 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4727 // Okay, we know that only that the single bit specified by UnknownBits
4728 // could be set on input to the CTLZ node. If this bit is set, the SRL
4729 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4730 // to an SRL/XOR pair, which is likely to simplify more.
4731 unsigned ShAmt = UnknownBits.countTrailingZeros();
4732 SDValue Op = N0.getOperand(0);
4736 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4737 DAG.getConstant(ShAmt, DL,
4738 getShiftAmountTy(Op.getValueType())));
4739 AddToWorklist(Op.getNode());
4743 return DAG.getNode(ISD::XOR, DL, VT,
4744 Op, DAG.getConstant(1, DL, VT));
4748 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4749 if (N1.getOpcode() == ISD::TRUNCATE &&
4750 N1.getOperand(0).getOpcode() == ISD::AND) {
4751 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4752 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4755 // fold operands of srl based on knowledge that the low bits are not
4757 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4758 return SDValue(N, 0);
4760 if (N1C && !N1C->isOpaque())
4761 if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4764 // Attempt to convert a srl of a load into a narrower zero-extending load.
4765 if (SDValue NarrowLoad = ReduceLoadWidth(N))
4768 // Here is a common situation. We want to optimize:
4771 // %b = and i32 %a, 2
4772 // %c = srl i32 %b, 1
4773 // brcond i32 %c ...
4779 // %c = setcc eq %b, 0
4782 // However when after the source operand of SRL is optimized into AND, the SRL
4783 // itself may not be optimized further. Look for it and add the BRCOND into
4785 if (N->hasOneUse()) {
4786 SDNode *Use = *N->use_begin();
4787 if (Use->getOpcode() == ISD::BRCOND)
4789 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4790 // Also look pass the truncate.
4791 Use = *Use->use_begin();
4792 if (Use->getOpcode() == ISD::BRCOND)
4800 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4801 SDValue N0 = N->getOperand(0);
4802 EVT VT = N->getValueType(0);
4804 // fold (bswap c1) -> c2
4805 if (isConstantIntBuildVectorOrConstantInt(N0))
4806 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4807 // fold (bswap (bswap x)) -> x
4808 if (N0.getOpcode() == ISD::BSWAP)
4809 return N0->getOperand(0);
4813 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4814 SDValue N0 = N->getOperand(0);
4815 EVT VT = N->getValueType(0);
4817 // fold (ctlz c1) -> c2
4818 if (isConstantIntBuildVectorOrConstantInt(N0))
4819 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4823 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4824 SDValue N0 = N->getOperand(0);
4825 EVT VT = N->getValueType(0);
4827 // fold (ctlz_zero_undef c1) -> c2
4828 if (isConstantIntBuildVectorOrConstantInt(N0))
4829 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4833 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4834 SDValue N0 = N->getOperand(0);
4835 EVT VT = N->getValueType(0);
4837 // fold (cttz c1) -> c2
4838 if (isConstantIntBuildVectorOrConstantInt(N0))
4839 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4843 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4844 SDValue N0 = N->getOperand(0);
4845 EVT VT = N->getValueType(0);
4847 // fold (cttz_zero_undef c1) -> c2
4848 if (isConstantIntBuildVectorOrConstantInt(N0))
4849 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4853 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4854 SDValue N0 = N->getOperand(0);
4855 EVT VT = N->getValueType(0);
4857 // fold (ctpop c1) -> c2
4858 if (isConstantIntBuildVectorOrConstantInt(N0))
4859 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4864 /// \brief Generate Min/Max node
4865 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4866 SDValue True, SDValue False,
4867 ISD::CondCode CC, const TargetLowering &TLI,
4868 SelectionDAG &DAG) {
4869 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4879 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4880 if (TLI.isOperationLegal(Opcode, VT))
4881 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4890 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4891 if (TLI.isOperationLegal(Opcode, VT))
4892 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4900 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4901 SDValue N0 = N->getOperand(0);
4902 SDValue N1 = N->getOperand(1);
4903 SDValue N2 = N->getOperand(2);
4904 EVT VT = N->getValueType(0);
4905 EVT VT0 = N0.getValueType();
4907 // fold (select C, X, X) -> X
4910 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4911 // fold (select true, X, Y) -> X
4912 // fold (select false, X, Y) -> Y
4913 return !N0C->isNullValue() ? N1 : N2;
4915 // fold (select C, 1, X) -> (or C, X)
4916 if (VT == MVT::i1 && isOneConstant(N1))
4917 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4918 // fold (select C, 0, 1) -> (xor C, 1)
4919 // We can't do this reliably if integer based booleans have different contents
4920 // to floating point based booleans. This is because we can't tell whether we
4921 // have an integer-based boolean or a floating-point-based boolean unless we
4922 // can find the SETCC that produced it and inspect its operands. This is
4923 // fairly easy if C is the SETCC node, but it can potentially be
4924 // undiscoverable (or not reasonably discoverable). For example, it could be
4925 // in another basic block or it could require searching a complicated
4927 if (VT.isInteger() &&
4928 (VT0 == MVT::i1 || (VT0.isInteger() &&
4929 TLI.getBooleanContents(false, false) ==
4930 TLI.getBooleanContents(false, true) &&
4931 TLI.getBooleanContents(false, false) ==
4932 TargetLowering::ZeroOrOneBooleanContent)) &&
4933 isNullConstant(N1) && isOneConstant(N2)) {
4937 return DAG.getNode(ISD::XOR, DL, VT0,
4938 N0, DAG.getConstant(1, DL, VT0));
4941 XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4942 N0, DAG.getConstant(1, DL0, VT0));
4943 AddToWorklist(XORNode.getNode());
4945 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4946 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4948 // fold (select C, 0, X) -> (and (not C), X)
4949 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4950 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4951 AddToWorklist(NOTNode.getNode());
4952 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4954 // fold (select C, X, 1) -> (or (not C), X)
4955 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
4956 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4957 AddToWorklist(NOTNode.getNode());
4958 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4960 // fold (select C, X, 0) -> (and C, X)
4961 if (VT == MVT::i1 && isNullConstant(N2))
4962 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4963 // fold (select X, X, Y) -> (or X, Y)
4964 // fold (select X, 1, Y) -> (or X, Y)
4965 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
4966 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4967 // fold (select X, Y, X) -> (and X, Y)
4968 // fold (select X, Y, 0) -> (and X, Y)
4969 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
4970 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4972 // If we can fold this based on the true/false value, do so.
4973 if (SimplifySelectOps(N, N1, N2))
4974 return SDValue(N, 0); // Don't revisit N.
4976 if (VT0 == MVT::i1) {
4977 // The code in this block deals with the following 2 equivalences:
4978 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
4979 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
4980 // The target can specify its prefered form with the
4981 // shouldNormalizeToSelectSequence() callback. However we always transform
4982 // to the right anyway if we find the inner select exists in the DAG anyway
4983 // and we always transform to the left side if we know that we can further
4984 // optimize the combination of the conditions.
4985 bool normalizeToSequence
4986 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
4987 // select (and Cond0, Cond1), X, Y
4988 // -> select Cond0, (select Cond1, X, Y), Y
4989 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4990 SDValue Cond0 = N0->getOperand(0);
4991 SDValue Cond1 = N0->getOperand(1);
4992 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4993 N1.getValueType(), Cond1, N1, N2);
4994 if (normalizeToSequence || !InnerSelect.use_empty())
4995 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4998 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4999 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5000 SDValue Cond0 = N0->getOperand(0);
5001 SDValue Cond1 = N0->getOperand(1);
5002 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5003 N1.getValueType(), Cond1, N1, N2);
5004 if (normalizeToSequence || !InnerSelect.use_empty())
5005 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5009 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5010 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5011 SDValue N1_0 = N1->getOperand(0);
5012 SDValue N1_1 = N1->getOperand(1);
5013 SDValue N1_2 = N1->getOperand(2);
5014 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5015 // Create the actual and node if we can generate good code for it.
5016 if (!normalizeToSequence) {
5017 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5019 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5022 // Otherwise see if we can optimize the "and" to a better pattern.
5023 if (SDValue Combined = visitANDLike(N0, N1_0, N))
5024 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5028 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5029 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5030 SDValue N2_0 = N2->getOperand(0);
5031 SDValue N2_1 = N2->getOperand(1);
5032 SDValue N2_2 = N2->getOperand(2);
5033 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5034 // Create the actual or node if we can generate good code for it.
5035 if (!normalizeToSequence) {
5036 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5038 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5041 // Otherwise see if we can optimize to a better pattern.
5042 if (SDValue Combined = visitORLike(N0, N2_0, N))
5043 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5049 // fold selects based on a setcc into other things, such as min/max/abs
5050 if (N0.getOpcode() == ISD::SETCC) {
5051 // select x, y (fcmp lt x, y) -> fminnum x, y
5052 // select x, y (fcmp gt x, y) -> fmaxnum x, y
5054 // This is OK if we don't care about what happens if either operand is a
5058 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5059 // no signed zeros as well as no nans.
5060 const TargetOptions &Options = DAG.getTarget().Options;
5061 if (Options.UnsafeFPMath &&
5062 VT.isFloatingPoint() && N0.hasOneUse() &&
5063 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5064 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5066 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5067 N0.getOperand(1), N1, N2, CC,
5072 if ((!LegalOperations &&
5073 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5074 TLI.isOperationLegal(ISD::SELECT_CC, VT))
5075 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5076 N0.getOperand(0), N0.getOperand(1),
5077 N1, N2, N0.getOperand(2));
5078 return SimplifySelect(SDLoc(N), N0, N1, N2);
5085 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5088 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5090 // Split the inputs.
5091 SDValue Lo, Hi, LL, LH, RL, RH;
5092 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5093 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5095 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5096 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5098 return std::make_pair(Lo, Hi);
5101 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5102 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5103 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5105 SDValue Cond = N->getOperand(0);
5106 SDValue LHS = N->getOperand(1);
5107 SDValue RHS = N->getOperand(2);
5108 EVT VT = N->getValueType(0);
5109 int NumElems = VT.getVectorNumElements();
5110 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5111 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5112 Cond.getOpcode() == ISD::BUILD_VECTOR);
5114 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5115 // binary ones here.
5116 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5119 // We're sure we have an even number of elements due to the
5120 // concat_vectors we have as arguments to vselect.
5121 // Skip BV elements until we find one that's not an UNDEF
5122 // After we find an UNDEF element, keep looping until we get to half the
5123 // length of the BV and see if all the non-undef nodes are the same.
5124 ConstantSDNode *BottomHalf = nullptr;
5125 for (int i = 0; i < NumElems / 2; ++i) {
5126 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5129 if (BottomHalf == nullptr)
5130 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5131 else if (Cond->getOperand(i).getNode() != BottomHalf)
5135 // Do the same for the second half of the BuildVector
5136 ConstantSDNode *TopHalf = nullptr;
5137 for (int i = NumElems / 2; i < NumElems; ++i) {
5138 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5141 if (TopHalf == nullptr)
5142 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5143 else if (Cond->getOperand(i).getNode() != TopHalf)
5147 assert(TopHalf && BottomHalf &&
5148 "One half of the selector was all UNDEFs and the other was all the "
5149 "same value. This should have been addressed before this function.");
5151 ISD::CONCAT_VECTORS, dl, VT,
5152 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5153 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5156 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5158 if (Level >= AfterLegalizeTypes)
5161 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5162 SDValue Mask = MSC->getMask();
5163 SDValue Data = MSC->getValue();
5166 // If the MSCATTER data type requires splitting and the mask is provided by a
5167 // SETCC, then split both nodes and its operands before legalization. This
5168 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5169 // and enables future optimizations (e.g. min/max pattern matching on X86).
5170 if (Mask.getOpcode() != ISD::SETCC)
5173 // Check if any splitting is required.
5174 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5175 TargetLowering::TypeSplitVector)
5177 SDValue MaskLo, MaskHi, Lo, Hi;
5178 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5181 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5183 SDValue Chain = MSC->getChain();
5185 EVT MemoryVT = MSC->getMemoryVT();
5186 unsigned Alignment = MSC->getOriginalAlignment();
5188 EVT LoMemVT, HiMemVT;
5189 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5191 SDValue DataLo, DataHi;
5192 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5194 SDValue BasePtr = MSC->getBasePtr();
5195 SDValue IndexLo, IndexHi;
5196 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5198 MachineMemOperand *MMO = DAG.getMachineFunction().
5199 getMachineMemOperand(MSC->getPointerInfo(),
5200 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5201 Alignment, MSC->getAAInfo(), MSC->getRanges());
5203 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5204 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5207 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5208 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5211 AddToWorklist(Lo.getNode());
5212 AddToWorklist(Hi.getNode());
5214 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5217 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5219 if (Level >= AfterLegalizeTypes)
5222 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5223 SDValue Mask = MST->getMask();
5224 SDValue Data = MST->getValue();
5227 // If the MSTORE data type requires splitting and the mask is provided by a
5228 // SETCC, then split both nodes and its operands before legalization. This
5229 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5230 // and enables future optimizations (e.g. min/max pattern matching on X86).
5231 if (Mask.getOpcode() == ISD::SETCC) {
5233 // Check if any splitting is required.
5234 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5235 TargetLowering::TypeSplitVector)
5238 SDValue MaskLo, MaskHi, Lo, Hi;
5239 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5242 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5244 SDValue Chain = MST->getChain();
5245 SDValue Ptr = MST->getBasePtr();
5247 EVT MemoryVT = MST->getMemoryVT();
5248 unsigned Alignment = MST->getOriginalAlignment();
5250 // if Alignment is equal to the vector size,
5251 // take the half of it for the second part
5252 unsigned SecondHalfAlignment =
5253 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5254 Alignment/2 : Alignment;
5256 EVT LoMemVT, HiMemVT;
5257 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5259 SDValue DataLo, DataHi;
5260 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5262 MachineMemOperand *MMO = DAG.getMachineFunction().
5263 getMachineMemOperand(MST->getPointerInfo(),
5264 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5265 Alignment, MST->getAAInfo(), MST->getRanges());
5267 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5268 MST->isTruncatingStore());
5270 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5271 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5272 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5274 MMO = DAG.getMachineFunction().
5275 getMachineMemOperand(MST->getPointerInfo(),
5276 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5277 SecondHalfAlignment, MST->getAAInfo(),
5280 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5281 MST->isTruncatingStore());
5283 AddToWorklist(Lo.getNode());
5284 AddToWorklist(Hi.getNode());
5286 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5291 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5293 if (Level >= AfterLegalizeTypes)
5296 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5297 SDValue Mask = MGT->getMask();
5300 // If the MGATHER result requires splitting and the mask is provided by a
5301 // SETCC, then split both nodes and its operands before legalization. This
5302 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5303 // and enables future optimizations (e.g. min/max pattern matching on X86).
5305 if (Mask.getOpcode() != ISD::SETCC)
5308 EVT VT = N->getValueType(0);
5310 // Check if any splitting is required.
5311 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5312 TargetLowering::TypeSplitVector)
5315 SDValue MaskLo, MaskHi, Lo, Hi;
5316 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5318 SDValue Src0 = MGT->getValue();
5319 SDValue Src0Lo, Src0Hi;
5320 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5323 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5325 SDValue Chain = MGT->getChain();
5326 EVT MemoryVT = MGT->getMemoryVT();
5327 unsigned Alignment = MGT->getOriginalAlignment();
5329 EVT LoMemVT, HiMemVT;
5330 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5332 SDValue BasePtr = MGT->getBasePtr();
5333 SDValue Index = MGT->getIndex();
5334 SDValue IndexLo, IndexHi;
5335 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5337 MachineMemOperand *MMO = DAG.getMachineFunction().
5338 getMachineMemOperand(MGT->getPointerInfo(),
5339 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5340 Alignment, MGT->getAAInfo(), MGT->getRanges());
5342 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5343 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5346 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5347 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5350 AddToWorklist(Lo.getNode());
5351 AddToWorklist(Hi.getNode());
5353 // Build a factor node to remember that this load is independent of the
5355 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5358 // Legalized the chain result - switch anything that used the old chain to
5360 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5362 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5364 SDValue RetOps[] = { GatherRes, Chain };
5365 return DAG.getMergeValues(RetOps, DL);
5368 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5370 if (Level >= AfterLegalizeTypes)
5373 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5374 SDValue Mask = MLD->getMask();
5377 // If the MLOAD result requires splitting and the mask is provided by a
5378 // SETCC, then split both nodes and its operands before legalization. This
5379 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5380 // and enables future optimizations (e.g. min/max pattern matching on X86).
5382 if (Mask.getOpcode() == ISD::SETCC) {
5383 EVT VT = N->getValueType(0);
5385 // Check if any splitting is required.
5386 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5387 TargetLowering::TypeSplitVector)
5390 SDValue MaskLo, MaskHi, Lo, Hi;
5391 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5393 SDValue Src0 = MLD->getSrc0();
5394 SDValue Src0Lo, Src0Hi;
5395 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5398 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5400 SDValue Chain = MLD->getChain();
5401 SDValue Ptr = MLD->getBasePtr();
5402 EVT MemoryVT = MLD->getMemoryVT();
5403 unsigned Alignment = MLD->getOriginalAlignment();
5405 // if Alignment is equal to the vector size,
5406 // take the half of it for the second part
5407 unsigned SecondHalfAlignment =
5408 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5409 Alignment/2 : Alignment;
5411 EVT LoMemVT, HiMemVT;
5412 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5414 MachineMemOperand *MMO = DAG.getMachineFunction().
5415 getMachineMemOperand(MLD->getPointerInfo(),
5416 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5417 Alignment, MLD->getAAInfo(), MLD->getRanges());
5419 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5422 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5423 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5424 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5426 MMO = DAG.getMachineFunction().
5427 getMachineMemOperand(MLD->getPointerInfo(),
5428 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5429 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5431 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5434 AddToWorklist(Lo.getNode());
5435 AddToWorklist(Hi.getNode());
5437 // Build a factor node to remember that this load is independent of the
5439 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5442 // Legalized the chain result - switch anything that used the old chain to
5444 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5446 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5448 SDValue RetOps[] = { LoadRes, Chain };
5449 return DAG.getMergeValues(RetOps, DL);
5454 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5455 SDValue N0 = N->getOperand(0);
5456 SDValue N1 = N->getOperand(1);
5457 SDValue N2 = N->getOperand(2);
5460 // Canonicalize integer abs.
5461 // vselect (setg[te] X, 0), X, -X ->
5462 // vselect (setgt X, -1), X, -X ->
5463 // vselect (setl[te] X, 0), -X, X ->
5464 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5465 if (N0.getOpcode() == ISD::SETCC) {
5466 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5467 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5469 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5471 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5472 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5473 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5474 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5475 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5476 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5477 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5480 EVT VT = LHS.getValueType();
5481 SDValue Shift = DAG.getNode(
5482 ISD::SRA, DL, VT, LHS,
5483 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5484 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5485 AddToWorklist(Shift.getNode());
5486 AddToWorklist(Add.getNode());
5487 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5491 if (SimplifySelectOps(N, N1, N2))
5492 return SDValue(N, 0); // Don't revisit N.
5494 // If the VSELECT result requires splitting and the mask is provided by a
5495 // SETCC, then split both nodes and its operands before legalization. This
5496 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5497 // and enables future optimizations (e.g. min/max pattern matching on X86).
5498 if (N0.getOpcode() == ISD::SETCC) {
5499 EVT VT = N->getValueType(0);
5501 // Check if any splitting is required.
5502 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5503 TargetLowering::TypeSplitVector)
5506 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5507 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5508 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5509 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5511 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5512 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5514 // Add the new VSELECT nodes to the work list in case they need to be split
5516 AddToWorklist(Lo.getNode());
5517 AddToWorklist(Hi.getNode());
5519 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5522 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5523 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5525 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5526 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5529 // The ConvertSelectToConcatVector function is assuming both the above
5530 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5532 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5533 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5534 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5535 if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5542 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5543 SDValue N0 = N->getOperand(0);
5544 SDValue N1 = N->getOperand(1);
5545 SDValue N2 = N->getOperand(2);
5546 SDValue N3 = N->getOperand(3);
5547 SDValue N4 = N->getOperand(4);
5548 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5550 // fold select_cc lhs, rhs, x, x, cc -> x
5554 // Determine if the condition we're dealing with is constant
5555 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5556 N0, N1, CC, SDLoc(N), false);
5557 if (SCC.getNode()) {
5558 AddToWorklist(SCC.getNode());
5560 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5561 if (!SCCC->isNullValue())
5562 return N2; // cond always true -> true val
5564 return N3; // cond always false -> false val
5565 } else if (SCC->getOpcode() == ISD::UNDEF) {
5566 // When the condition is UNDEF, just return the first operand. This is
5567 // coherent the DAG creation, no setcc node is created in this case
5569 } else if (SCC.getOpcode() == ISD::SETCC) {
5570 // Fold to a simpler select_cc
5571 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5572 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5577 // If we can fold this based on the true/false value, do so.
5578 if (SimplifySelectOps(N, N2, N3))
5579 return SDValue(N, 0); // Don't revisit N.
5581 // fold select_cc into other things, such as min/max/abs
5582 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5585 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5586 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5587 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5591 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5592 /// a build_vector of constants.
5593 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5594 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5595 /// Vector extends are not folded if operations are legal; this is to
5596 /// avoid introducing illegal build_vector dag nodes.
5597 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5598 SelectionDAG &DAG, bool LegalTypes,
5599 bool LegalOperations) {
5600 unsigned Opcode = N->getOpcode();
5601 SDValue N0 = N->getOperand(0);
5602 EVT VT = N->getValueType(0);
5604 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5605 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5606 && "Expected EXTEND dag node in input!");
5608 // fold (sext c1) -> c1
5609 // fold (zext c1) -> c1
5610 // fold (aext c1) -> c1
5611 if (isa<ConstantSDNode>(N0))
5612 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5614 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5615 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5616 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5617 EVT SVT = VT.getScalarType();
5618 if (!(VT.isVector() &&
5619 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5620 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5623 // We can fold this node into a build_vector.
5624 unsigned VTBits = SVT.getSizeInBits();
5625 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5626 SmallVector<SDValue, 8> Elts;
5627 unsigned NumElts = VT.getVectorNumElements();
5630 for (unsigned i=0; i != NumElts; ++i) {
5631 SDValue Op = N0->getOperand(i);
5632 if (Op->getOpcode() == ISD::UNDEF) {
5633 Elts.push_back(DAG.getUNDEF(SVT));
5638 // Get the constant value and if needed trunc it to the size of the type.
5639 // Nodes like build_vector might have constants wider than the scalar type.
5640 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5641 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5642 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5644 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5647 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5650 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5651 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5652 // transformation. Returns true if extension are possible and the above
5653 // mentioned transformation is profitable.
5654 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5656 SmallVectorImpl<SDNode *> &ExtendNodes,
5657 const TargetLowering &TLI) {
5658 bool HasCopyToRegUses = false;
5659 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5660 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5661 UE = N0.getNode()->use_end();
5666 if (UI.getUse().getResNo() != N0.getResNo())
5668 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5669 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5670 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5671 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5672 // Sign bits will be lost after a zext.
5675 for (unsigned i = 0; i != 2; ++i) {
5676 SDValue UseOp = User->getOperand(i);
5679 if (!isa<ConstantSDNode>(UseOp))
5684 ExtendNodes.push_back(User);
5687 // If truncates aren't free and there are users we can't
5688 // extend, it isn't worthwhile.
5691 // Remember if this value is live-out.
5692 if (User->getOpcode() == ISD::CopyToReg)
5693 HasCopyToRegUses = true;
5696 if (HasCopyToRegUses) {
5697 bool BothLiveOut = false;
5698 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5700 SDUse &Use = UI.getUse();
5701 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5707 // Both unextended and extended values are live out. There had better be
5708 // a good reason for the transformation.
5709 return ExtendNodes.size();
5714 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5715 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5716 ISD::NodeType ExtType) {
5717 // Extend SetCC uses if necessary.
5718 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5719 SDNode *SetCC = SetCCs[i];
5720 SmallVector<SDValue, 4> Ops;
5722 for (unsigned j = 0; j != 2; ++j) {
5723 SDValue SOp = SetCC->getOperand(j);
5725 Ops.push_back(ExtLoad);
5727 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5730 Ops.push_back(SetCC->getOperand(2));
5731 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5735 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5736 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5737 SDValue N0 = N->getOperand(0);
5738 EVT DstVT = N->getValueType(0);
5739 EVT SrcVT = N0.getValueType();
5741 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5742 N->getOpcode() == ISD::ZERO_EXTEND) &&
5743 "Unexpected node type (not an extend)!");
5745 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5746 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5747 // (v8i32 (sext (v8i16 (load x))))
5749 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5750 // (v4i32 (sextload (x + 16)))))
5751 // Where uses of the original load, i.e.:
5753 // are replaced with:
5755 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5756 // (v4i32 (sextload (x + 16)))))))
5758 // This combine is only applicable to illegal, but splittable, vectors.
5759 // All legal types, and illegal non-vector types, are handled elsewhere.
5760 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5762 if (N0->getOpcode() != ISD::LOAD)
5765 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5767 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5768 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5769 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5772 SmallVector<SDNode *, 4> SetCCs;
5773 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5776 ISD::LoadExtType ExtType =
5777 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5779 // Try to split the vector types to get down to legal types.
5780 EVT SplitSrcVT = SrcVT;
5781 EVT SplitDstVT = DstVT;
5782 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5783 SplitSrcVT.getVectorNumElements() > 1) {
5784 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5785 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5788 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5792 const unsigned NumSplits =
5793 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5794 const unsigned Stride = SplitSrcVT.getStoreSize();
5795 SmallVector<SDValue, 4> Loads;
5796 SmallVector<SDValue, 4> Chains;
5798 SDValue BasePtr = LN0->getBasePtr();
5799 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5800 const unsigned Offset = Idx * Stride;
5801 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5803 SDValue SplitLoad = DAG.getExtLoad(
5804 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5805 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5806 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5807 Align, LN0->getAAInfo());
5809 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5810 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5812 Loads.push_back(SplitLoad.getValue(0));
5813 Chains.push_back(SplitLoad.getValue(1));
5816 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5817 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5819 CombineTo(N, NewValue);
5821 // Replace uses of the original load (before extension)
5822 // with a truncate of the concatenated sextloaded vectors.
5824 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5825 CombineTo(N0.getNode(), Trunc, NewChain);
5826 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5827 (ISD::NodeType)N->getOpcode());
5828 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5831 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5832 SDValue N0 = N->getOperand(0);
5833 EVT VT = N->getValueType(0);
5835 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5837 return SDValue(Res, 0);
5839 // fold (sext (sext x)) -> (sext x)
5840 // fold (sext (aext x)) -> (sext x)
5841 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5842 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5845 if (N0.getOpcode() == ISD::TRUNCATE) {
5846 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5847 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5848 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
5849 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5850 if (NarrowLoad.getNode() != N0.getNode()) {
5851 CombineTo(N0.getNode(), NarrowLoad);
5852 // CombineTo deleted the truncate, if needed, but not what's under it.
5855 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5858 // See if the value being truncated is already sign extended. If so, just
5859 // eliminate the trunc/sext pair.
5860 SDValue Op = N0.getOperand(0);
5861 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5862 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5863 unsigned DestBits = VT.getScalarType().getSizeInBits();
5864 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5866 if (OpBits == DestBits) {
5867 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5868 // bits, it is already ready.
5869 if (NumSignBits > DestBits-MidBits)
5871 } else if (OpBits < DestBits) {
5872 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5873 // bits, just sext from i32.
5874 if (NumSignBits > OpBits-MidBits)
5875 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5877 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5878 // bits, just truncate to i32.
5879 if (NumSignBits > OpBits-MidBits)
5880 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5883 // fold (sext (truncate x)) -> (sextinreg x).
5884 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5885 N0.getValueType())) {
5886 if (OpBits < DestBits)
5887 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5888 else if (OpBits > DestBits)
5889 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5890 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5891 DAG.getValueType(N0.getValueType()));
5895 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5896 // Only generate vector extloads when 1) they're legal, and 2) they are
5897 // deemed desirable by the target.
5898 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5899 ((!LegalOperations && !VT.isVector() &&
5900 !cast<LoadSDNode>(N0)->isVolatile()) ||
5901 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5902 bool DoXform = true;
5903 SmallVector<SDNode*, 4> SetCCs;
5904 if (!N0.hasOneUse())
5905 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5907 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5909 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5910 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5912 LN0->getBasePtr(), N0.getValueType(),
5913 LN0->getMemOperand());
5914 CombineTo(N, ExtLoad);
5915 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5916 N0.getValueType(), ExtLoad);
5917 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5918 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5920 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5924 // fold (sext (load x)) to multiple smaller sextloads.
5925 // Only on illegal but splittable vectors.
5926 if (SDValue ExtLoad = CombineExtLoad(N))
5929 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5930 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5931 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5932 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5933 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5934 EVT MemVT = LN0->getMemoryVT();
5935 if ((!LegalOperations && !LN0->isVolatile()) ||
5936 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5937 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5939 LN0->getBasePtr(), MemVT,
5940 LN0->getMemOperand());
5941 CombineTo(N, ExtLoad);
5942 CombineTo(N0.getNode(),
5943 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5944 N0.getValueType(), ExtLoad),
5945 ExtLoad.getValue(1));
5946 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5950 // fold (sext (and/or/xor (load x), cst)) ->
5951 // (and/or/xor (sextload x), (sext cst))
5952 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5953 N0.getOpcode() == ISD::XOR) &&
5954 isa<LoadSDNode>(N0.getOperand(0)) &&
5955 N0.getOperand(1).getOpcode() == ISD::Constant &&
5956 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5957 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5958 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5959 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5960 bool DoXform = true;
5961 SmallVector<SDNode*, 4> SetCCs;
5962 if (!N0.hasOneUse())
5963 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5966 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5967 LN0->getChain(), LN0->getBasePtr(),
5969 LN0->getMemOperand());
5970 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5971 Mask = Mask.sext(VT.getSizeInBits());
5973 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5974 ExtLoad, DAG.getConstant(Mask, DL, VT));
5975 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5976 SDLoc(N0.getOperand(0)),
5977 N0.getOperand(0).getValueType(), ExtLoad);
5979 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5980 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5982 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5987 if (N0.getOpcode() == ISD::SETCC) {
5988 EVT N0VT = N0.getOperand(0).getValueType();
5989 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5990 // Only do this before legalize for now.
5991 if (VT.isVector() && !LegalOperations &&
5992 TLI.getBooleanContents(N0VT) ==
5993 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5994 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5995 // of the same size as the compared operands. Only optimize sext(setcc())
5996 // if this is the case.
5997 EVT SVT = getSetCCResultType(N0VT);
5999 // We know that the # elements of the results is the same as the
6000 // # elements of the compare (and the # elements of the compare result
6001 // for that matter). Check to see that they are the same size. If so,
6002 // we know that the element size of the sext'd result matches the
6003 // element size of the compare operands.
6004 if (VT.getSizeInBits() == SVT.getSizeInBits())
6005 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6007 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6009 // If the desired elements are smaller or larger than the source
6010 // elements we can use a matching integer vector type and then
6011 // truncate/sign extend
6012 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6013 if (SVT == MatchingVectorType) {
6014 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6015 N0.getOperand(0), N0.getOperand(1),
6016 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6017 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6021 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6022 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6025 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6027 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6028 NegOne, DAG.getConstant(0, DL, VT),
6029 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6030 if (SCC.getNode()) return SCC;
6032 if (!VT.isVector()) {
6033 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6034 if (!LegalOperations ||
6035 TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6037 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6038 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6039 N0.getOperand(0), N0.getOperand(1), CC);
6040 return DAG.getSelect(DL, VT, SetCC,
6041 NegOne, DAG.getConstant(0, DL, VT));
6046 // fold (sext x) -> (zext x) if the sign bit is known zero.
6047 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6048 DAG.SignBitIsZero(N0))
6049 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6054 // isTruncateOf - If N is a truncate of some other value, return true, record
6055 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6056 // This function computes KnownZero to avoid a duplicated call to
6057 // computeKnownBits in the caller.
6058 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6061 if (N->getOpcode() == ISD::TRUNCATE) {
6062 Op = N->getOperand(0);
6063 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6067 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6068 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6071 SDValue Op0 = N->getOperand(0);
6072 SDValue Op1 = N->getOperand(1);
6073 assert(Op0.getValueType() == Op1.getValueType());
6075 if (isNullConstant(Op0))
6077 else if (isNullConstant(Op1))
6082 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6084 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6090 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6091 SDValue N0 = N->getOperand(0);
6092 EVT VT = N->getValueType(0);
6094 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6096 return SDValue(Res, 0);
6098 // fold (zext (zext x)) -> (zext x)
6099 // fold (zext (aext x)) -> (zext x)
6100 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6101 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6104 // fold (zext (truncate x)) -> (zext x) or
6105 // (zext (truncate x)) -> (truncate x)
6106 // This is valid when the truncated bits of x are already zero.
6107 // FIXME: We should extend this to work for vectors too.
6110 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6111 APInt TruncatedBits =
6112 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6113 APInt(Op.getValueSizeInBits(), 0) :
6114 APInt::getBitsSet(Op.getValueSizeInBits(),
6115 N0.getValueSizeInBits(),
6116 std::min(Op.getValueSizeInBits(),
6117 VT.getSizeInBits()));
6118 if (TruncatedBits == (KnownZero & TruncatedBits)) {
6119 if (VT.bitsGT(Op.getValueType()))
6120 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6121 if (VT.bitsLT(Op.getValueType()))
6122 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6128 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6129 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6130 if (N0.getOpcode() == ISD::TRUNCATE) {
6131 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6132 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6133 if (NarrowLoad.getNode() != N0.getNode()) {
6134 CombineTo(N0.getNode(), NarrowLoad);
6135 // CombineTo deleted the truncate, if needed, but not what's under it.
6138 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6142 // fold (zext (truncate x)) -> (and x, mask)
6143 if (N0.getOpcode() == ISD::TRUNCATE) {
6144 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6145 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6146 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6147 SDNode *oye = N0.getNode()->getOperand(0).getNode();
6148 if (NarrowLoad.getNode() != N0.getNode()) {
6149 CombineTo(N0.getNode(), NarrowLoad);
6150 // CombineTo deleted the truncate, if needed, but not what's under it.
6153 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6156 EVT SrcVT = N0.getOperand(0).getValueType();
6157 EVT MinVT = N0.getValueType();
6159 // Try to mask before the extension to avoid having to generate a larger mask,
6160 // possibly over several sub-vectors.
6161 if (SrcVT.bitsLT(VT)) {
6162 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6163 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6164 SDValue Op = N0.getOperand(0);
6165 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6166 AddToWorklist(Op.getNode());
6167 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6171 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6172 SDValue Op = N0.getOperand(0);
6173 if (SrcVT.bitsLT(VT)) {
6174 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6175 AddToWorklist(Op.getNode());
6176 } else if (SrcVT.bitsGT(VT)) {
6177 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6178 AddToWorklist(Op.getNode());
6180 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6184 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6185 // if either of the casts is not free.
6186 if (N0.getOpcode() == ISD::AND &&
6187 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6188 N0.getOperand(1).getOpcode() == ISD::Constant &&
6189 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6190 N0.getValueType()) ||
6191 !TLI.isZExtFree(N0.getValueType(), VT))) {
6192 SDValue X = N0.getOperand(0).getOperand(0);
6193 if (X.getValueType().bitsLT(VT)) {
6194 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6195 } else if (X.getValueType().bitsGT(VT)) {
6196 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6198 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6199 Mask = Mask.zext(VT.getSizeInBits());
6201 return DAG.getNode(ISD::AND, DL, VT,
6202 X, DAG.getConstant(Mask, DL, VT));
6205 // fold (zext (load x)) -> (zext (truncate (zextload x)))
6206 // Only generate vector extloads when 1) they're legal, and 2) they are
6207 // deemed desirable by the target.
6208 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6209 ((!LegalOperations && !VT.isVector() &&
6210 !cast<LoadSDNode>(N0)->isVolatile()) ||
6211 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6212 bool DoXform = true;
6213 SmallVector<SDNode*, 4> SetCCs;
6214 if (!N0.hasOneUse())
6215 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6217 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6219 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6220 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6222 LN0->getBasePtr(), N0.getValueType(),
6223 LN0->getMemOperand());
6224 CombineTo(N, ExtLoad);
6225 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6226 N0.getValueType(), ExtLoad);
6227 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6229 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6231 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6235 // fold (zext (load x)) to multiple smaller zextloads.
6236 // Only on illegal but splittable vectors.
6237 if (SDValue ExtLoad = CombineExtLoad(N))
6240 // fold (zext (and/or/xor (load x), cst)) ->
6241 // (and/or/xor (zextload x), (zext cst))
6242 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6243 N0.getOpcode() == ISD::XOR) &&
6244 isa<LoadSDNode>(N0.getOperand(0)) &&
6245 N0.getOperand(1).getOpcode() == ISD::Constant &&
6246 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6247 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6248 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6249 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6250 bool DoXform = true;
6251 SmallVector<SDNode*, 4> SetCCs;
6252 if (!N0.hasOneUse())
6253 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6256 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6257 LN0->getChain(), LN0->getBasePtr(),
6259 LN0->getMemOperand());
6260 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6261 Mask = Mask.zext(VT.getSizeInBits());
6263 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6264 ExtLoad, DAG.getConstant(Mask, DL, VT));
6265 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6266 SDLoc(N0.getOperand(0)),
6267 N0.getOperand(0).getValueType(), ExtLoad);
6269 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6270 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6272 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6277 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6278 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6279 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6280 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6281 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6282 EVT MemVT = LN0->getMemoryVT();
6283 if ((!LegalOperations && !LN0->isVolatile()) ||
6284 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6285 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6287 LN0->getBasePtr(), MemVT,
6288 LN0->getMemOperand());
6289 CombineTo(N, ExtLoad);
6290 CombineTo(N0.getNode(),
6291 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6293 ExtLoad.getValue(1));
6294 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6298 if (N0.getOpcode() == ISD::SETCC) {
6299 if (!LegalOperations && VT.isVector() &&
6300 N0.getValueType().getVectorElementType() == MVT::i1) {
6301 EVT N0VT = N0.getOperand(0).getValueType();
6302 if (getSetCCResultType(N0VT) == N0.getValueType())
6305 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6306 // Only do this before legalize for now.
6307 EVT EltVT = VT.getVectorElementType();
6309 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6310 DAG.getConstant(1, DL, EltVT));
6311 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6312 // We know that the # elements of the results is the same as the
6313 // # elements of the compare (and the # elements of the compare result
6314 // for that matter). Check to see that they are the same size. If so,
6315 // we know that the element size of the sext'd result matches the
6316 // element size of the compare operands.
6317 return DAG.getNode(ISD::AND, DL, VT,
6318 DAG.getSetCC(DL, VT, N0.getOperand(0),
6320 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6321 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6324 // If the desired elements are smaller or larger than the source
6325 // elements we can use a matching integer vector type and then
6326 // truncate/sign extend
6327 EVT MatchingElementType =
6328 EVT::getIntegerVT(*DAG.getContext(),
6329 N0VT.getScalarType().getSizeInBits());
6330 EVT MatchingVectorType =
6331 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6332 N0VT.getVectorNumElements());
6334 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6336 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6337 return DAG.getNode(ISD::AND, DL, VT,
6338 DAG.getSExtOrTrunc(VsetCC, DL, VT),
6339 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6342 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6345 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6346 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6347 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6348 if (SCC.getNode()) return SCC;
6351 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6352 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6353 isa<ConstantSDNode>(N0.getOperand(1)) &&
6354 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6356 SDValue ShAmt = N0.getOperand(1);
6357 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6358 if (N0.getOpcode() == ISD::SHL) {
6359 SDValue InnerZExt = N0.getOperand(0);
6360 // If the original shl may be shifting out bits, do not perform this
6362 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6363 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6364 if (ShAmtVal > KnownZeroBits)
6370 // Ensure that the shift amount is wide enough for the shifted value.
6371 if (VT.getSizeInBits() >= 256)
6372 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6374 return DAG.getNode(N0.getOpcode(), DL, VT,
6375 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6382 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6383 SDValue N0 = N->getOperand(0);
6384 EVT VT = N->getValueType(0);
6386 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6388 return SDValue(Res, 0);
6390 // fold (aext (aext x)) -> (aext x)
6391 // fold (aext (zext x)) -> (zext x)
6392 // fold (aext (sext x)) -> (sext x)
6393 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6394 N0.getOpcode() == ISD::ZERO_EXTEND ||
6395 N0.getOpcode() == ISD::SIGN_EXTEND)
6396 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6398 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6399 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6400 if (N0.getOpcode() == ISD::TRUNCATE) {
6401 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6402 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6403 if (NarrowLoad.getNode() != N0.getNode()) {
6404 CombineTo(N0.getNode(), NarrowLoad);
6405 // CombineTo deleted the truncate, if needed, but not what's under it.
6408 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6412 // fold (aext (truncate x))
6413 if (N0.getOpcode() == ISD::TRUNCATE) {
6414 SDValue TruncOp = N0.getOperand(0);
6415 if (TruncOp.getValueType() == VT)
6416 return TruncOp; // x iff x size == zext size.
6417 if (TruncOp.getValueType().bitsGT(VT))
6418 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6419 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6422 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6423 // if the trunc is not free.
6424 if (N0.getOpcode() == ISD::AND &&
6425 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6426 N0.getOperand(1).getOpcode() == ISD::Constant &&
6427 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6428 N0.getValueType())) {
6429 SDValue X = N0.getOperand(0).getOperand(0);
6430 if (X.getValueType().bitsLT(VT)) {
6431 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6432 } else if (X.getValueType().bitsGT(VT)) {
6433 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6435 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6436 Mask = Mask.zext(VT.getSizeInBits());
6438 return DAG.getNode(ISD::AND, DL, VT,
6439 X, DAG.getConstant(Mask, DL, VT));
6442 // fold (aext (load x)) -> (aext (truncate (extload x)))
6443 // None of the supported targets knows how to perform load and any_ext
6444 // on vectors in one instruction. We only perform this transformation on
6446 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6447 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6448 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6449 bool DoXform = true;
6450 SmallVector<SDNode*, 4> SetCCs;
6451 if (!N0.hasOneUse())
6452 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6454 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6455 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6457 LN0->getBasePtr(), N0.getValueType(),
6458 LN0->getMemOperand());
6459 CombineTo(N, ExtLoad);
6460 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6461 N0.getValueType(), ExtLoad);
6462 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6463 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6465 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6469 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6470 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6471 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6472 if (N0.getOpcode() == ISD::LOAD &&
6473 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6475 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6476 ISD::LoadExtType ExtType = LN0->getExtensionType();
6477 EVT MemVT = LN0->getMemoryVT();
6478 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6479 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6480 VT, LN0->getChain(), LN0->getBasePtr(),
6481 MemVT, LN0->getMemOperand());
6482 CombineTo(N, ExtLoad);
6483 CombineTo(N0.getNode(),
6484 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6485 N0.getValueType(), ExtLoad),
6486 ExtLoad.getValue(1));
6487 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6491 if (N0.getOpcode() == ISD::SETCC) {
6493 // aext(setcc) -> vsetcc
6494 // aext(setcc) -> truncate(vsetcc)
6495 // aext(setcc) -> aext(vsetcc)
6496 // Only do this before legalize for now.
6497 if (VT.isVector() && !LegalOperations) {
6498 EVT N0VT = N0.getOperand(0).getValueType();
6499 // We know that the # elements of the results is the same as the
6500 // # elements of the compare (and the # elements of the compare result
6501 // for that matter). Check to see that they are the same size. If so,
6502 // we know that the element size of the sext'd result matches the
6503 // element size of the compare operands.
6504 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6505 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6507 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6508 // If the desired elements are smaller or larger than the source
6509 // elements we can use a matching integer vector type and then
6510 // truncate/any extend
6512 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6514 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6516 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6517 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6521 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6524 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6525 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6526 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6534 /// See if the specified operand can be simplified with the knowledge that only
6535 /// the bits specified by Mask are used. If so, return the simpler operand,
6536 /// otherwise return a null SDValue.
6537 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6538 switch (V.getOpcode()) {
6540 case ISD::Constant: {
6541 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6542 assert(CV && "Const value should be ConstSDNode.");
6543 const APInt &CVal = CV->getAPIntValue();
6544 APInt NewVal = CVal & Mask;
6546 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6551 // If the LHS or RHS don't contribute bits to the or, drop them.
6552 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6553 return V.getOperand(1);
6554 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6555 return V.getOperand(0);
6558 // Only look at single-use SRLs.
6559 if (!V.getNode()->hasOneUse())
6561 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6562 // See if we can recursively simplify the LHS.
6563 unsigned Amt = RHSC->getZExtValue();
6565 // Watch out for shift count overflow though.
6566 if (Amt >= Mask.getBitWidth()) break;
6567 APInt NewMask = Mask << Amt;
6568 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6569 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6570 SimplifyLHS, V.getOperand(1));
6576 /// If the result of a wider load is shifted to right of N bits and then
6577 /// truncated to a narrower type and where N is a multiple of number of bits of
6578 /// the narrower type, transform it to a narrower load from address + N / num of
6579 /// bits of new type. If the result is to be extended, also fold the extension
6580 /// to form a extending load.
6581 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6582 unsigned Opc = N->getOpcode();
6584 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6585 SDValue N0 = N->getOperand(0);
6586 EVT VT = N->getValueType(0);
6589 // This transformation isn't valid for vector loads.
6593 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6595 if (Opc == ISD::SIGN_EXTEND_INREG) {
6596 ExtType = ISD::SEXTLOAD;
6597 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6598 } else if (Opc == ISD::SRL) {
6599 // Another special-case: SRL is basically zero-extending a narrower value.
6600 ExtType = ISD::ZEXTLOAD;
6602 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6603 if (!N01) return SDValue();
6604 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6605 VT.getSizeInBits() - N01->getZExtValue());
6607 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6610 unsigned EVTBits = ExtVT.getSizeInBits();
6612 // Do not generate loads of non-round integer types since these can
6613 // be expensive (and would be wrong if the type is not byte sized).
6614 if (!ExtVT.isRound())
6618 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6619 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6620 ShAmt = N01->getZExtValue();
6621 // Is the shift amount a multiple of size of VT?
6622 if ((ShAmt & (EVTBits-1)) == 0) {
6623 N0 = N0.getOperand(0);
6624 // Is the load width a multiple of size of VT?
6625 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6629 // At this point, we must have a load or else we can't do the transform.
6630 if (!isa<LoadSDNode>(N0)) return SDValue();
6632 // Because a SRL must be assumed to *need* to zero-extend the high bits
6633 // (as opposed to anyext the high bits), we can't combine the zextload
6634 // lowering of SRL and an sextload.
6635 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6638 // If the shift amount is larger than the input type then we're not
6639 // accessing any of the loaded bytes. If the load was a zextload/extload
6640 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6641 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6646 // If the load is shifted left (and the result isn't shifted back right),
6647 // we can fold the truncate through the shift.
6648 unsigned ShLeftAmt = 0;
6649 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6650 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6651 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6652 ShLeftAmt = N01->getZExtValue();
6653 N0 = N0.getOperand(0);
6657 // If we haven't found a load, we can't narrow it. Don't transform one with
6658 // multiple uses, this would require adding a new load.
6659 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6662 // Don't change the width of a volatile load.
6663 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6664 if (LN0->isVolatile())
6667 // Verify that we are actually reducing a load width here.
6668 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6671 // For the transform to be legal, the load must produce only two values
6672 // (the value loaded and the chain). Don't transform a pre-increment
6673 // load, for example, which produces an extra value. Otherwise the
6674 // transformation is not equivalent, and the downstream logic to replace
6675 // uses gets things wrong.
6676 if (LN0->getNumValues() > 2)
6679 // If the load that we're shrinking is an extload and we're not just
6680 // discarding the extension we can't simply shrink the load. Bail.
6681 // TODO: It would be possible to merge the extensions in some cases.
6682 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6683 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6686 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6689 EVT PtrType = N0.getOperand(1).getValueType();
6691 if (PtrType == MVT::Untyped || PtrType.isExtended())
6692 // It's not possible to generate a constant of extended or untyped type.
6695 // For big endian targets, we need to adjust the offset to the pointer to
6696 // load the correct bytes.
6697 if (DAG.getDataLayout().isBigEndian()) {
6698 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6699 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6700 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6703 uint64_t PtrOff = ShAmt / 8;
6704 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6706 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6707 PtrType, LN0->getBasePtr(),
6708 DAG.getConstant(PtrOff, DL, PtrType));
6709 AddToWorklist(NewPtr.getNode());
6712 if (ExtType == ISD::NON_EXTLOAD)
6713 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6714 LN0->getPointerInfo().getWithOffset(PtrOff),
6715 LN0->isVolatile(), LN0->isNonTemporal(),
6716 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6718 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6719 LN0->getPointerInfo().getWithOffset(PtrOff),
6720 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6721 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6723 // Replace the old load's chain with the new load's chain.
6724 WorklistRemover DeadNodes(*this);
6725 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6727 // Shift the result left, if we've swallowed a left shift.
6728 SDValue Result = Load;
6729 if (ShLeftAmt != 0) {
6730 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6731 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6733 // If the shift amount is as large as the result size (but, presumably,
6734 // no larger than the source) then the useful bits of the result are
6735 // zero; we can't simply return the shortened shift, because the result
6736 // of that operation is undefined.
6738 if (ShLeftAmt >= VT.getSizeInBits())
6739 Result = DAG.getConstant(0, DL, VT);
6741 Result = DAG.getNode(ISD::SHL, DL, VT,
6742 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6745 // Return the new loaded value.
6749 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6750 SDValue N0 = N->getOperand(0);
6751 SDValue N1 = N->getOperand(1);
6752 EVT VT = N->getValueType(0);
6753 EVT EVT = cast<VTSDNode>(N1)->getVT();
6754 unsigned VTBits = VT.getScalarType().getSizeInBits();
6755 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6758 return DAG.getUNDEF(VT);
6760 // fold (sext_in_reg c1) -> c1
6761 if (isConstantIntBuildVectorOrConstantInt(N0))
6762 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6764 // If the input is already sign extended, just drop the extension.
6765 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6768 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6769 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6770 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6771 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6772 N0.getOperand(0), N1);
6774 // fold (sext_in_reg (sext x)) -> (sext x)
6775 // fold (sext_in_reg (aext x)) -> (sext x)
6776 // if x is small enough.
6777 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6778 SDValue N00 = N0.getOperand(0);
6779 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6780 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6781 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6784 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6785 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6786 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6788 // fold operands of sext_in_reg based on knowledge that the top bits are not
6790 if (SimplifyDemandedBits(SDValue(N, 0)))
6791 return SDValue(N, 0);
6793 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6794 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6795 if (SDValue NarrowLoad = ReduceLoadWidth(N))
6798 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6799 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6800 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6801 if (N0.getOpcode() == ISD::SRL) {
6802 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6803 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6804 // We can turn this into an SRA iff the input to the SRL is already sign
6806 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6807 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6808 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6809 N0.getOperand(0), N0.getOperand(1));
6813 // fold (sext_inreg (extload x)) -> (sextload x)
6814 if (ISD::isEXTLoad(N0.getNode()) &&
6815 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6816 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6817 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6818 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6819 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6820 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6822 LN0->getBasePtr(), EVT,
6823 LN0->getMemOperand());
6824 CombineTo(N, ExtLoad);
6825 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6826 AddToWorklist(ExtLoad.getNode());
6827 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6829 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6830 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6832 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6833 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6834 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6835 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6836 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6838 LN0->getBasePtr(), EVT,
6839 LN0->getMemOperand());
6840 CombineTo(N, ExtLoad);
6841 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6842 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6845 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6846 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6847 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6848 N0.getOperand(1), false);
6849 if (BSwap.getNode())
6850 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6857 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6858 SDValue N0 = N->getOperand(0);
6859 EVT VT = N->getValueType(0);
6861 if (N0.getOpcode() == ISD::UNDEF)
6862 return DAG.getUNDEF(VT);
6864 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6866 return SDValue(Res, 0);
6871 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6872 SDValue N0 = N->getOperand(0);
6873 EVT VT = N->getValueType(0);
6874 bool isLE = DAG.getDataLayout().isLittleEndian();
6877 if (N0.getValueType() == N->getValueType(0))
6879 // fold (truncate c1) -> c1
6880 if (isConstantIntBuildVectorOrConstantInt(N0))
6881 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6882 // fold (truncate (truncate x)) -> (truncate x)
6883 if (N0.getOpcode() == ISD::TRUNCATE)
6884 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6885 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6886 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6887 N0.getOpcode() == ISD::SIGN_EXTEND ||
6888 N0.getOpcode() == ISD::ANY_EXTEND) {
6889 if (N0.getOperand(0).getValueType().bitsLT(VT))
6890 // if the source is smaller than the dest, we still need an extend
6891 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6893 if (N0.getOperand(0).getValueType().bitsGT(VT))
6894 // if the source is larger than the dest, than we just need the truncate
6895 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6896 // if the source and dest are the same type, we can drop both the extend
6897 // and the truncate.
6898 return N0.getOperand(0);
6901 // Fold extract-and-trunc into a narrow extract. For example:
6902 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6903 // i32 y = TRUNCATE(i64 x)
6905 // v16i8 b = BITCAST (v2i64 val)
6906 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6908 // Note: We only run this optimization after type legalization (which often
6909 // creates this pattern) and before operation legalization after which
6910 // we need to be more careful about the vector instructions that we generate.
6911 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6912 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6914 EVT VecTy = N0.getOperand(0).getValueType();
6915 EVT ExTy = N0.getValueType();
6916 EVT TrTy = N->getValueType(0);
6918 unsigned NumElem = VecTy.getVectorNumElements();
6919 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6921 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6922 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6924 SDValue EltNo = N0->getOperand(1);
6925 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6926 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6927 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
6928 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6930 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6931 NVT, N0.getOperand(0));
6934 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6936 DAG.getConstant(Index, DL, IndexTy));
6940 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6941 if (N0.getOpcode() == ISD::SELECT) {
6942 EVT SrcVT = N0.getValueType();
6943 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6944 TLI.isTruncateFree(SrcVT, VT)) {
6946 SDValue Cond = N0.getOperand(0);
6947 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6948 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6949 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6953 // Fold a series of buildvector, bitcast, and truncate if possible.
6955 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6956 // (2xi32 (buildvector x, y)).
6957 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6958 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6959 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6960 N0.getOperand(0).hasOneUse()) {
6962 SDValue BuildVect = N0.getOperand(0);
6963 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6964 EVT TruncVecEltTy = VT.getVectorElementType();
6966 // Check that the element types match.
6967 if (BuildVectEltTy == TruncVecEltTy) {
6968 // Now we only need to compute the offset of the truncated elements.
6969 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6970 unsigned TruncVecNumElts = VT.getVectorNumElements();
6971 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6973 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6974 "Invalid number of elements");
6976 SmallVector<SDValue, 8> Opnds;
6977 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6978 Opnds.push_back(BuildVect.getOperand(i));
6980 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6984 // See if we can simplify the input to this truncate through knowledge that
6985 // only the low bits are being used.
6986 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6987 // Currently we only perform this optimization on scalars because vectors
6988 // may have different active low bits.
6989 if (!VT.isVector()) {
6991 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6992 VT.getSizeInBits()));
6993 if (Shorter.getNode())
6994 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6996 // fold (truncate (load x)) -> (smaller load x)
6997 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6998 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6999 if (SDValue Reduced = ReduceLoadWidth(N))
7002 // Handle the case where the load remains an extending load even
7003 // after truncation.
7004 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7005 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7006 if (!LN0->isVolatile() &&
7007 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7008 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7009 VT, LN0->getChain(), LN0->getBasePtr(),
7011 LN0->getMemOperand());
7012 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7017 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7018 // where ... are all 'undef'.
7019 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7020 SmallVector<EVT, 8> VTs;
7023 unsigned NumDefs = 0;
7025 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7026 SDValue X = N0.getOperand(i);
7027 if (X.getOpcode() != ISD::UNDEF) {
7032 // Stop if more than one members are non-undef.
7035 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7036 VT.getVectorElementType(),
7037 X.getValueType().getVectorNumElements()));
7041 return DAG.getUNDEF(VT);
7044 assert(V.getNode() && "The single defined operand is empty!");
7045 SmallVector<SDValue, 8> Opnds;
7046 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7048 Opnds.push_back(DAG.getUNDEF(VTs[i]));
7051 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7052 AddToWorklist(NV.getNode());
7053 Opnds.push_back(NV);
7055 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7059 // Simplify the operands using demanded-bits information.
7060 if (!VT.isVector() &&
7061 SimplifyDemandedBits(SDValue(N, 0)))
7062 return SDValue(N, 0);
7067 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7068 SDValue Elt = N->getOperand(i);
7069 if (Elt.getOpcode() != ISD::MERGE_VALUES)
7070 return Elt.getNode();
7071 return Elt.getOperand(Elt.getResNo()).getNode();
7074 /// build_pair (load, load) -> load
7075 /// if load locations are consecutive.
7076 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7077 assert(N->getOpcode() == ISD::BUILD_PAIR);
7079 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7080 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7081 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7082 LD1->getAddressSpace() != LD2->getAddressSpace())
7084 EVT LD1VT = LD1->getValueType(0);
7086 if (ISD::isNON_EXTLoad(LD2) &&
7088 // If both are volatile this would reduce the number of volatile loads.
7089 // If one is volatile it might be ok, but play conservative and bail out.
7090 !LD1->isVolatile() &&
7091 !LD2->isVolatile() &&
7092 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7093 unsigned Align = LD1->getAlignment();
7094 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7095 VT.getTypeForEVT(*DAG.getContext()));
7097 if (NewAlign <= Align &&
7098 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7099 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7100 LD1->getBasePtr(), LD1->getPointerInfo(),
7101 false, false, false, Align);
7107 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7108 SDValue N0 = N->getOperand(0);
7109 EVT VT = N->getValueType(0);
7111 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7112 // Only do this before legalize, since afterward the target may be depending
7113 // on the bitconvert.
7114 // First check to see if this is all constant.
7116 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7118 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7120 EVT DestEltVT = N->getValueType(0).getVectorElementType();
7121 assert(!DestEltVT.isVector() &&
7122 "Element type of vector ValueType must not be vector!");
7124 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7127 // If the input is a constant, let getNode fold it.
7128 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7129 // If we can't allow illegal operations, we need to check that this is just
7130 // a fp -> int or int -> conversion and that the resulting operation will
7132 if (!LegalOperations ||
7133 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7134 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7135 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7136 TLI.isOperationLegal(ISD::Constant, VT)))
7137 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7140 // (conv (conv x, t1), t2) -> (conv x, t2)
7141 if (N0.getOpcode() == ISD::BITCAST)
7142 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7145 // fold (conv (load x)) -> (load (conv*)x)
7146 // If the resultant load doesn't need a higher alignment than the original!
7147 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7148 // Do not change the width of a volatile load.
7149 !cast<LoadSDNode>(N0)->isVolatile() &&
7150 // Do not remove the cast if the types differ in endian layout.
7151 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7152 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7153 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7154 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7155 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7156 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7157 VT.getTypeForEVT(*DAG.getContext()));
7158 unsigned OrigAlign = LN0->getAlignment();
7160 if (Align <= OrigAlign) {
7161 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7162 LN0->getBasePtr(), LN0->getPointerInfo(),
7163 LN0->isVolatile(), LN0->isNonTemporal(),
7164 LN0->isInvariant(), OrigAlign,
7166 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7171 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7172 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7173 // This often reduces constant pool loads.
7174 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7175 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7176 N0.getNode()->hasOneUse() && VT.isInteger() &&
7177 !VT.isVector() && !N0.getValueType().isVector()) {
7178 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7180 AddToWorklist(NewConv.getNode());
7183 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7184 if (N0.getOpcode() == ISD::FNEG)
7185 return DAG.getNode(ISD::XOR, DL, VT,
7186 NewConv, DAG.getConstant(SignBit, DL, VT));
7187 assert(N0.getOpcode() == ISD::FABS);
7188 return DAG.getNode(ISD::AND, DL, VT,
7189 NewConv, DAG.getConstant(~SignBit, DL, VT));
7192 // fold (bitconvert (fcopysign cst, x)) ->
7193 // (or (and (bitconvert x), sign), (and cst, (not sign)))
7194 // Note that we don't handle (copysign x, cst) because this can always be
7195 // folded to an fneg or fabs.
7196 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7197 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7198 VT.isInteger() && !VT.isVector()) {
7199 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7200 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7201 if (isTypeLegal(IntXVT)) {
7202 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7203 IntXVT, N0.getOperand(1));
7204 AddToWorklist(X.getNode());
7206 // If X has a different width than the result/lhs, sext it or truncate it.
7207 unsigned VTWidth = VT.getSizeInBits();
7208 if (OrigXWidth < VTWidth) {
7209 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7210 AddToWorklist(X.getNode());
7211 } else if (OrigXWidth > VTWidth) {
7212 // To get the sign bit in the right place, we have to shift it right
7213 // before truncating.
7215 X = DAG.getNode(ISD::SRL, DL,
7216 X.getValueType(), X,
7217 DAG.getConstant(OrigXWidth-VTWidth, DL,
7219 AddToWorklist(X.getNode());
7220 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7221 AddToWorklist(X.getNode());
7224 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7225 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7226 X, DAG.getConstant(SignBit, SDLoc(X), VT));
7227 AddToWorklist(X.getNode());
7229 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7230 VT, N0.getOperand(0));
7231 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7232 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7233 AddToWorklist(Cst.getNode());
7235 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7239 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7240 if (N0.getOpcode() == ISD::BUILD_PAIR)
7241 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7244 // Remove double bitcasts from shuffles - this is often a legacy of
7245 // XformToShuffleWithZero being used to combine bitmaskings (of
7246 // float vectors bitcast to integer vectors) into shuffles.
7247 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7248 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7249 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7250 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7251 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7252 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7254 // If operands are a bitcast, peek through if it casts the original VT.
7255 // If operands are a constant, just bitcast back to original VT.
7256 auto PeekThroughBitcast = [&](SDValue Op) {
7257 if (Op.getOpcode() == ISD::BITCAST &&
7258 Op.getOperand(0).getValueType() == VT)
7259 return SDValue(Op.getOperand(0));
7260 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7261 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7262 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7266 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7267 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7272 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7273 SmallVector<int, 8> NewMask;
7274 for (int M : SVN->getMask())
7275 for (int i = 0; i != MaskScale; ++i)
7276 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7278 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7280 std::swap(SV0, SV1);
7281 ShuffleVectorSDNode::commuteMask(NewMask);
7282 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7286 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7292 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7293 EVT VT = N->getValueType(0);
7294 return CombineConsecutiveLoads(N, VT);
7297 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7298 /// operands. DstEltVT indicates the destination element value type.
7299 SDValue DAGCombiner::
7300 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7301 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7303 // If this is already the right type, we're done.
7304 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7306 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7307 unsigned DstBitSize = DstEltVT.getSizeInBits();
7309 // If this is a conversion of N elements of one type to N elements of another
7310 // type, convert each element. This handles FP<->INT cases.
7311 if (SrcBitSize == DstBitSize) {
7312 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7313 BV->getValueType(0).getVectorNumElements());
7315 // Due to the FP element handling below calling this routine recursively,
7316 // we can end up with a scalar-to-vector node here.
7317 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7318 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7319 DAG.getNode(ISD::BITCAST, SDLoc(BV),
7320 DstEltVT, BV->getOperand(0)));
7322 SmallVector<SDValue, 8> Ops;
7323 for (SDValue Op : BV->op_values()) {
7324 // If the vector element type is not legal, the BUILD_VECTOR operands
7325 // are promoted and implicitly truncated. Make that explicit here.
7326 if (Op.getValueType() != SrcEltVT)
7327 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7328 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7330 AddToWorklist(Ops.back().getNode());
7332 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7335 // Otherwise, we're growing or shrinking the elements. To avoid having to
7336 // handle annoying details of growing/shrinking FP values, we convert them to
7338 if (SrcEltVT.isFloatingPoint()) {
7339 // Convert the input float vector to a int vector where the elements are the
7341 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7342 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7346 // Now we know the input is an integer vector. If the output is a FP type,
7347 // convert to integer first, then to FP of the right size.
7348 if (DstEltVT.isFloatingPoint()) {
7349 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7350 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7352 // Next, convert to FP elements of the same size.
7353 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7358 // Okay, we know the src/dst types are both integers of differing types.
7359 // Handling growing first.
7360 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7361 if (SrcBitSize < DstBitSize) {
7362 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7364 SmallVector<SDValue, 8> Ops;
7365 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7366 i += NumInputsPerOutput) {
7367 bool isLE = DAG.getDataLayout().isLittleEndian();
7368 APInt NewBits = APInt(DstBitSize, 0);
7369 bool EltIsUndef = true;
7370 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7371 // Shift the previously computed bits over.
7372 NewBits <<= SrcBitSize;
7373 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7374 if (Op.getOpcode() == ISD::UNDEF) continue;
7377 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7378 zextOrTrunc(SrcBitSize).zext(DstBitSize);
7382 Ops.push_back(DAG.getUNDEF(DstEltVT));
7384 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7387 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7388 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7391 // Finally, this must be the case where we are shrinking elements: each input
7392 // turns into multiple outputs.
7393 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7394 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7395 NumOutputsPerInput*BV->getNumOperands());
7396 SmallVector<SDValue, 8> Ops;
7398 for (const SDValue &Op : BV->op_values()) {
7399 if (Op.getOpcode() == ISD::UNDEF) {
7400 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7404 APInt OpVal = cast<ConstantSDNode>(Op)->
7405 getAPIntValue().zextOrTrunc(SrcBitSize);
7407 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7408 APInt ThisVal = OpVal.trunc(DstBitSize);
7409 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7410 OpVal = OpVal.lshr(DstBitSize);
7413 // For big endian targets, swap the order of the pieces of each element.
7414 if (DAG.getDataLayout().isBigEndian())
7415 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7418 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7421 /// Try to perform FMA combining on a given FADD node.
7422 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7423 SDValue N0 = N->getOperand(0);
7424 SDValue N1 = N->getOperand(1);
7425 EVT VT = N->getValueType(0);
7428 const TargetOptions &Options = DAG.getTarget().Options;
7430 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7432 // Floating-point multiply-add with intermediate rounding.
7433 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7435 // Floating-point multiply-add without intermediate rounding.
7437 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7438 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7440 // No valid opcode, do not combine.
7441 if (!HasFMAD && !HasFMA)
7444 // Always prefer FMAD to FMA for precision.
7445 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7446 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7447 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7449 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7450 // prefer to fold the multiply with fewer uses.
7451 if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7452 N1.getOpcode() == ISD::FMUL) {
7453 if (N0.getNode()->use_size() > N1.getNode()->use_size())
7457 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7458 if (N0.getOpcode() == ISD::FMUL &&
7459 (Aggressive || N0->hasOneUse())) {
7460 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7461 N0.getOperand(0), N0.getOperand(1), N1);
7464 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7465 // Note: Commutes FADD operands.
7466 if (N1.getOpcode() == ISD::FMUL &&
7467 (Aggressive || N1->hasOneUse())) {
7468 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7469 N1.getOperand(0), N1.getOperand(1), N0);
7472 // Look through FP_EXTEND nodes to do more combining.
7473 if (AllowFusion && LookThroughFPExt) {
7474 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7475 if (N0.getOpcode() == ISD::FP_EXTEND) {
7476 SDValue N00 = N0.getOperand(0);
7477 if (N00.getOpcode() == ISD::FMUL)
7478 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7479 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7481 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7482 N00.getOperand(1)), N1);
7485 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7486 // Note: Commutes FADD operands.
7487 if (N1.getOpcode() == ISD::FP_EXTEND) {
7488 SDValue N10 = N1.getOperand(0);
7489 if (N10.getOpcode() == ISD::FMUL)
7490 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7491 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7493 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7494 N10.getOperand(1)), N0);
7498 // More folding opportunities when target permits.
7499 if ((AllowFusion || HasFMAD) && Aggressive) {
7500 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7501 if (N0.getOpcode() == PreferredFusedOpcode &&
7502 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7503 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7504 N0.getOperand(0), N0.getOperand(1),
7505 DAG.getNode(PreferredFusedOpcode, SL, VT,
7506 N0.getOperand(2).getOperand(0),
7507 N0.getOperand(2).getOperand(1),
7511 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7512 if (N1->getOpcode() == PreferredFusedOpcode &&
7513 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7514 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7515 N1.getOperand(0), N1.getOperand(1),
7516 DAG.getNode(PreferredFusedOpcode, SL, VT,
7517 N1.getOperand(2).getOperand(0),
7518 N1.getOperand(2).getOperand(1),
7522 if (AllowFusion && LookThroughFPExt) {
7523 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7524 // -> (fma x, y, (fma (fpext u), (fpext v), z))
7525 auto FoldFAddFMAFPExtFMul = [&] (
7526 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7527 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7528 DAG.getNode(PreferredFusedOpcode, SL, VT,
7529 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7530 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7533 if (N0.getOpcode() == PreferredFusedOpcode) {
7534 SDValue N02 = N0.getOperand(2);
7535 if (N02.getOpcode() == ISD::FP_EXTEND) {
7536 SDValue N020 = N02.getOperand(0);
7537 if (N020.getOpcode() == ISD::FMUL)
7538 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7539 N020.getOperand(0), N020.getOperand(1),
7544 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7545 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7546 // FIXME: This turns two single-precision and one double-precision
7547 // operation into two double-precision operations, which might not be
7548 // interesting for all targets, especially GPUs.
7549 auto FoldFAddFPExtFMAFMul = [&] (
7550 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7551 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7552 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7553 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7554 DAG.getNode(PreferredFusedOpcode, SL, VT,
7555 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7556 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7559 if (N0.getOpcode() == ISD::FP_EXTEND) {
7560 SDValue N00 = N0.getOperand(0);
7561 if (N00.getOpcode() == PreferredFusedOpcode) {
7562 SDValue N002 = N00.getOperand(2);
7563 if (N002.getOpcode() == ISD::FMUL)
7564 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7565 N002.getOperand(0), N002.getOperand(1),
7570 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7571 // -> (fma y, z, (fma (fpext u), (fpext v), x))
7572 if (N1.getOpcode() == PreferredFusedOpcode) {
7573 SDValue N12 = N1.getOperand(2);
7574 if (N12.getOpcode() == ISD::FP_EXTEND) {
7575 SDValue N120 = N12.getOperand(0);
7576 if (N120.getOpcode() == ISD::FMUL)
7577 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7578 N120.getOperand(0), N120.getOperand(1),
7583 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7584 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7585 // FIXME: This turns two single-precision and one double-precision
7586 // operation into two double-precision operations, which might not be
7587 // interesting for all targets, especially GPUs.
7588 if (N1.getOpcode() == ISD::FP_EXTEND) {
7589 SDValue N10 = N1.getOperand(0);
7590 if (N10.getOpcode() == PreferredFusedOpcode) {
7591 SDValue N102 = N10.getOperand(2);
7592 if (N102.getOpcode() == ISD::FMUL)
7593 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7594 N102.getOperand(0), N102.getOperand(1),
7604 /// Try to perform FMA combining on a given FSUB node.
7605 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7606 SDValue N0 = N->getOperand(0);
7607 SDValue N1 = N->getOperand(1);
7608 EVT VT = N->getValueType(0);
7611 const TargetOptions &Options = DAG.getTarget().Options;
7613 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7615 // Floating-point multiply-add with intermediate rounding.
7616 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7618 // Floating-point multiply-add without intermediate rounding.
7620 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7621 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7623 // No valid opcode, do not combine.
7624 if (!HasFMAD && !HasFMA)
7627 // Always prefer FMAD to FMA for precision.
7628 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7629 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7630 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7632 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7633 if (N0.getOpcode() == ISD::FMUL &&
7634 (Aggressive || N0->hasOneUse())) {
7635 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7636 N0.getOperand(0), N0.getOperand(1),
7637 DAG.getNode(ISD::FNEG, SL, VT, N1));
7640 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7641 // Note: Commutes FSUB operands.
7642 if (N1.getOpcode() == ISD::FMUL &&
7643 (Aggressive || N1->hasOneUse()))
7644 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7645 DAG.getNode(ISD::FNEG, SL, VT,
7647 N1.getOperand(1), N0);
7649 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7650 if (N0.getOpcode() == ISD::FNEG &&
7651 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7652 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7653 SDValue N00 = N0.getOperand(0).getOperand(0);
7654 SDValue N01 = N0.getOperand(0).getOperand(1);
7655 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7656 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7657 DAG.getNode(ISD::FNEG, SL, VT, N1));
7660 // Look through FP_EXTEND nodes to do more combining.
7661 if (AllowFusion && LookThroughFPExt) {
7662 // fold (fsub (fpext (fmul x, y)), z)
7663 // -> (fma (fpext x), (fpext y), (fneg z))
7664 if (N0.getOpcode() == ISD::FP_EXTEND) {
7665 SDValue N00 = N0.getOperand(0);
7666 if (N00.getOpcode() == ISD::FMUL)
7667 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7668 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7670 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7672 DAG.getNode(ISD::FNEG, SL, VT, N1));
7675 // fold (fsub x, (fpext (fmul y, z)))
7676 // -> (fma (fneg (fpext y)), (fpext z), x)
7677 // Note: Commutes FSUB operands.
7678 if (N1.getOpcode() == ISD::FP_EXTEND) {
7679 SDValue N10 = N1.getOperand(0);
7680 if (N10.getOpcode() == ISD::FMUL)
7681 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7682 DAG.getNode(ISD::FNEG, SL, VT,
7683 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7684 N10.getOperand(0))),
7685 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7690 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7691 // -> (fneg (fma (fpext x), (fpext y), z))
7692 // Note: This could be removed with appropriate canonicalization of the
7693 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7694 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7695 // from implementing the canonicalization in visitFSUB.
7696 if (N0.getOpcode() == ISD::FP_EXTEND) {
7697 SDValue N00 = N0.getOperand(0);
7698 if (N00.getOpcode() == ISD::FNEG) {
7699 SDValue N000 = N00.getOperand(0);
7700 if (N000.getOpcode() == ISD::FMUL) {
7701 return DAG.getNode(ISD::FNEG, SL, VT,
7702 DAG.getNode(PreferredFusedOpcode, SL, VT,
7703 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7704 N000.getOperand(0)),
7705 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7706 N000.getOperand(1)),
7712 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7713 // -> (fneg (fma (fpext x)), (fpext y), z)
7714 // Note: This could be removed with appropriate canonicalization of the
7715 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7716 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7717 // from implementing the canonicalization in visitFSUB.
7718 if (N0.getOpcode() == ISD::FNEG) {
7719 SDValue N00 = N0.getOperand(0);
7720 if (N00.getOpcode() == ISD::FP_EXTEND) {
7721 SDValue N000 = N00.getOperand(0);
7722 if (N000.getOpcode() == ISD::FMUL) {
7723 return DAG.getNode(ISD::FNEG, SL, VT,
7724 DAG.getNode(PreferredFusedOpcode, SL, VT,
7725 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7726 N000.getOperand(0)),
7727 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7728 N000.getOperand(1)),
7736 // More folding opportunities when target permits.
7737 if ((AllowFusion || HasFMAD) && Aggressive) {
7738 // fold (fsub (fma x, y, (fmul u, v)), z)
7739 // -> (fma x, y (fma u, v, (fneg z)))
7740 if (N0.getOpcode() == PreferredFusedOpcode &&
7741 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7742 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7743 N0.getOperand(0), N0.getOperand(1),
7744 DAG.getNode(PreferredFusedOpcode, SL, VT,
7745 N0.getOperand(2).getOperand(0),
7746 N0.getOperand(2).getOperand(1),
7747 DAG.getNode(ISD::FNEG, SL, VT,
7751 // fold (fsub x, (fma y, z, (fmul u, v)))
7752 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7753 if (N1.getOpcode() == PreferredFusedOpcode &&
7754 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7755 SDValue N20 = N1.getOperand(2).getOperand(0);
7756 SDValue N21 = N1.getOperand(2).getOperand(1);
7757 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7758 DAG.getNode(ISD::FNEG, SL, VT,
7761 DAG.getNode(PreferredFusedOpcode, SL, VT,
7762 DAG.getNode(ISD::FNEG, SL, VT, N20),
7767 if (AllowFusion && LookThroughFPExt) {
7768 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7769 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7770 if (N0.getOpcode() == PreferredFusedOpcode) {
7771 SDValue N02 = N0.getOperand(2);
7772 if (N02.getOpcode() == ISD::FP_EXTEND) {
7773 SDValue N020 = N02.getOperand(0);
7774 if (N020.getOpcode() == ISD::FMUL)
7775 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7776 N0.getOperand(0), N0.getOperand(1),
7777 DAG.getNode(PreferredFusedOpcode, SL, VT,
7778 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7779 N020.getOperand(0)),
7780 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7781 N020.getOperand(1)),
7782 DAG.getNode(ISD::FNEG, SL, VT,
7787 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7788 // -> (fma (fpext x), (fpext y),
7789 // (fma (fpext u), (fpext v), (fneg z)))
7790 // FIXME: This turns two single-precision and one double-precision
7791 // operation into two double-precision operations, which might not be
7792 // interesting for all targets, especially GPUs.
7793 if (N0.getOpcode() == ISD::FP_EXTEND) {
7794 SDValue N00 = N0.getOperand(0);
7795 if (N00.getOpcode() == PreferredFusedOpcode) {
7796 SDValue N002 = N00.getOperand(2);
7797 if (N002.getOpcode() == ISD::FMUL)
7798 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7799 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7801 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7803 DAG.getNode(PreferredFusedOpcode, SL, VT,
7804 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7805 N002.getOperand(0)),
7806 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7807 N002.getOperand(1)),
7808 DAG.getNode(ISD::FNEG, SL, VT,
7813 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7814 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7815 if (N1.getOpcode() == PreferredFusedOpcode &&
7816 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7817 SDValue N120 = N1.getOperand(2).getOperand(0);
7818 if (N120.getOpcode() == ISD::FMUL) {
7819 SDValue N1200 = N120.getOperand(0);
7820 SDValue N1201 = N120.getOperand(1);
7821 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7822 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7824 DAG.getNode(PreferredFusedOpcode, SL, VT,
7825 DAG.getNode(ISD::FNEG, SL, VT,
7826 DAG.getNode(ISD::FP_EXTEND, SL,
7828 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7834 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7835 // -> (fma (fneg (fpext y)), (fpext z),
7836 // (fma (fneg (fpext u)), (fpext v), x))
7837 // FIXME: This turns two single-precision and one double-precision
7838 // operation into two double-precision operations, which might not be
7839 // interesting for all targets, especially GPUs.
7840 if (N1.getOpcode() == ISD::FP_EXTEND &&
7841 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7842 SDValue N100 = N1.getOperand(0).getOperand(0);
7843 SDValue N101 = N1.getOperand(0).getOperand(1);
7844 SDValue N102 = N1.getOperand(0).getOperand(2);
7845 if (N102.getOpcode() == ISD::FMUL) {
7846 SDValue N1020 = N102.getOperand(0);
7847 SDValue N1021 = N102.getOperand(1);
7848 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7849 DAG.getNode(ISD::FNEG, SL, VT,
7850 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7852 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7853 DAG.getNode(PreferredFusedOpcode, SL, VT,
7854 DAG.getNode(ISD::FNEG, SL, VT,
7855 DAG.getNode(ISD::FP_EXTEND, SL,
7857 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7868 /// Try to perform FMA combining on a given FMUL node.
7869 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
7870 SDValue N0 = N->getOperand(0);
7871 SDValue N1 = N->getOperand(1);
7872 EVT VT = N->getValueType(0);
7875 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
7877 const TargetOptions &Options = DAG.getTarget().Options;
7879 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7881 // Floating-point multiply-add with intermediate rounding.
7882 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7884 // Floating-point multiply-add without intermediate rounding.
7886 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7887 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7889 // No valid opcode, do not combine.
7890 if (!HasFMAD && !HasFMA)
7893 // Always prefer FMAD to FMA for precision.
7894 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7895 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7897 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
7898 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
7899 auto FuseFADD = [&](SDValue X, SDValue Y) {
7900 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
7901 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
7902 if (XC1 && XC1->isExactlyValue(+1.0))
7903 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
7904 if (XC1 && XC1->isExactlyValue(-1.0))
7905 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
7906 DAG.getNode(ISD::FNEG, SL, VT, Y));
7911 if (SDValue FMA = FuseFADD(N0, N1))
7913 if (SDValue FMA = FuseFADD(N1, N0))
7916 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
7917 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
7918 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
7919 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
7920 auto FuseFSUB = [&](SDValue X, SDValue Y) {
7921 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
7922 auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
7923 if (XC0 && XC0->isExactlyValue(+1.0))
7924 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7925 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
7927 if (XC0 && XC0->isExactlyValue(-1.0))
7928 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7929 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
7930 DAG.getNode(ISD::FNEG, SL, VT, Y));
7932 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
7933 if (XC1 && XC1->isExactlyValue(+1.0))
7934 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
7935 DAG.getNode(ISD::FNEG, SL, VT, Y));
7936 if (XC1 && XC1->isExactlyValue(-1.0))
7937 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
7942 if (SDValue FMA = FuseFSUB(N0, N1))
7944 if (SDValue FMA = FuseFSUB(N1, N0))
7950 SDValue DAGCombiner::visitFADD(SDNode *N) {
7951 SDValue N0 = N->getOperand(0);
7952 SDValue N1 = N->getOperand(1);
7953 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
7954 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
7955 EVT VT = N->getValueType(0);
7957 const TargetOptions &Options = DAG.getTarget().Options;
7958 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
7962 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7965 // fold (fadd c1, c2) -> c1 + c2
7967 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
7969 // canonicalize constant to RHS
7970 if (N0CFP && !N1CFP)
7971 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
7973 // fold (fadd A, (fneg B)) -> (fsub A, B)
7974 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7975 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7976 return DAG.getNode(ISD::FSUB, DL, VT, N0,
7977 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
7979 // fold (fadd (fneg A), B) -> (fsub B, A)
7980 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7981 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7982 return DAG.getNode(ISD::FSUB, DL, VT, N1,
7983 GetNegatedExpression(N0, DAG, LegalOperations), Flags);
7985 // If 'unsafe math' is enabled, fold lots of things.
7986 if (Options.UnsafeFPMath) {
7987 // No FP constant should be created after legalization as Instruction
7988 // Selection pass has a hard time dealing with FP constants.
7989 bool AllowNewConst = (Level < AfterLegalizeDAG);
7991 // fold (fadd A, 0) -> A
7992 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
7996 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7997 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7998 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
7999 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8000 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8004 // If allowed, fold (fadd (fneg x), x) -> 0.0
8005 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8006 return DAG.getConstantFP(0.0, DL, VT);
8008 // If allowed, fold (fadd x, (fneg x)) -> 0.0
8009 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8010 return DAG.getConstantFP(0.0, DL, VT);
8012 // We can fold chains of FADD's of the same value into multiplications.
8013 // This transform is not safe in general because we are reducing the number
8014 // of rounding steps.
8015 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8016 if (N0.getOpcode() == ISD::FMUL) {
8017 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8018 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8020 // (fadd (fmul x, c), x) -> (fmul x, c+1)
8021 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8022 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8023 DAG.getConstantFP(1.0, DL, VT), Flags);
8024 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8027 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8028 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8029 N1.getOperand(0) == N1.getOperand(1) &&
8030 N0.getOperand(0) == N1.getOperand(0)) {
8031 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8032 DAG.getConstantFP(2.0, DL, VT), Flags);
8033 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8037 if (N1.getOpcode() == ISD::FMUL) {
8038 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8039 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8041 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8042 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8043 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8044 DAG.getConstantFP(1.0, DL, VT), Flags);
8045 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8048 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8049 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8050 N0.getOperand(0) == N0.getOperand(1) &&
8051 N1.getOperand(0) == N0.getOperand(0)) {
8052 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8053 DAG.getConstantFP(2.0, DL, VT), Flags);
8054 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8058 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8059 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8060 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8061 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8062 (N0.getOperand(0) == N1)) {
8063 return DAG.getNode(ISD::FMUL, DL, VT,
8064 N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8068 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8069 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8070 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8071 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8072 N1.getOperand(0) == N0) {
8073 return DAG.getNode(ISD::FMUL, DL, VT,
8074 N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8078 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8079 if (AllowNewConst &&
8080 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8081 N0.getOperand(0) == N0.getOperand(1) &&
8082 N1.getOperand(0) == N1.getOperand(1) &&
8083 N0.getOperand(0) == N1.getOperand(0)) {
8084 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8085 DAG.getConstantFP(4.0, DL, VT), Flags);
8088 } // enable-unsafe-fp-math
8090 // FADD -> FMA combines:
8091 if (SDValue Fused = visitFADDForFMACombine(N)) {
8092 AddToWorklist(Fused.getNode());
8099 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8100 SDValue N0 = N->getOperand(0);
8101 SDValue N1 = N->getOperand(1);
8102 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8103 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8104 EVT VT = N->getValueType(0);
8106 const TargetOptions &Options = DAG.getTarget().Options;
8107 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8111 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8114 // fold (fsub c1, c2) -> c1-c2
8116 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags);
8118 // fold (fsub A, (fneg B)) -> (fadd A, B)
8119 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8120 return DAG.getNode(ISD::FADD, dl, VT, N0,
8121 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8123 // If 'unsafe math' is enabled, fold lots of things.
8124 if (Options.UnsafeFPMath) {
8126 if (N1CFP && N1CFP->isZero())
8129 // (fsub 0, B) -> -B
8130 if (N0CFP && N0CFP->isZero()) {
8131 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8132 return GetNegatedExpression(N1, DAG, LegalOperations);
8133 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8134 return DAG.getNode(ISD::FNEG, dl, VT, N1);
8137 // (fsub x, x) -> 0.0
8139 return DAG.getConstantFP(0.0f, dl, VT);
8141 // (fsub x, (fadd x, y)) -> (fneg y)
8142 // (fsub x, (fadd y, x)) -> (fneg y)
8143 if (N1.getOpcode() == ISD::FADD) {
8144 SDValue N10 = N1->getOperand(0);
8145 SDValue N11 = N1->getOperand(1);
8147 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8148 return GetNegatedExpression(N11, DAG, LegalOperations);
8150 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8151 return GetNegatedExpression(N10, DAG, LegalOperations);
8155 // FSUB -> FMA combines:
8156 if (SDValue Fused = visitFSUBForFMACombine(N)) {
8157 AddToWorklist(Fused.getNode());
8164 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8165 SDValue N0 = N->getOperand(0);
8166 SDValue N1 = N->getOperand(1);
8167 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8168 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8169 EVT VT = N->getValueType(0);
8171 const TargetOptions &Options = DAG.getTarget().Options;
8172 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8175 if (VT.isVector()) {
8176 // This just handles C1 * C2 for vectors. Other vector folds are below.
8177 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8181 // fold (fmul c1, c2) -> c1*c2
8183 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8185 // canonicalize constant to RHS
8186 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8187 !isConstantFPBuildVectorOrConstantFP(N1))
8188 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8190 // fold (fmul A, 1.0) -> A
8191 if (N1CFP && N1CFP->isExactlyValue(1.0))
8194 if (Options.UnsafeFPMath) {
8195 // fold (fmul A, 0) -> 0
8196 if (N1CFP && N1CFP->isZero())
8199 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8200 if (N0.getOpcode() == ISD::FMUL) {
8201 // Fold scalars or any vector constants (not just splats).
8202 // This fold is done in general by InstCombine, but extra fmul insts
8203 // may have been generated during lowering.
8204 SDValue N00 = N0.getOperand(0);
8205 SDValue N01 = N0.getOperand(1);
8206 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8207 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8208 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8210 // Check 1: Make sure that the first operand of the inner multiply is NOT
8211 // a constant. Otherwise, we may induce infinite looping.
8212 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8213 // Check 2: Make sure that the second operand of the inner multiply and
8214 // the second operand of the outer multiply are constants.
8215 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8216 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8217 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8218 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8223 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8224 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8225 // during an early run of DAGCombiner can prevent folding with fmuls
8226 // inserted during lowering.
8227 if (N0.getOpcode() == ISD::FADD &&
8228 (N0.getOperand(0) == N0.getOperand(1)) &&
8230 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8231 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8232 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8236 // fold (fmul X, 2.0) -> (fadd X, X)
8237 if (N1CFP && N1CFP->isExactlyValue(+2.0))
8238 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8240 // fold (fmul X, -1.0) -> (fneg X)
8241 if (N1CFP && N1CFP->isExactlyValue(-1.0))
8242 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8243 return DAG.getNode(ISD::FNEG, DL, VT, N0);
8245 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8246 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8247 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8248 // Both can be negated for free, check to see if at least one is cheaper
8250 if (LHSNeg == 2 || RHSNeg == 2)
8251 return DAG.getNode(ISD::FMUL, DL, VT,
8252 GetNegatedExpression(N0, DAG, LegalOperations),
8253 GetNegatedExpression(N1, DAG, LegalOperations),
8258 // FMUL -> FMA combines:
8259 if (SDValue Fused = visitFMULForFMACombine(N)) {
8260 AddToWorklist(Fused.getNode());
8267 SDValue DAGCombiner::visitFMA(SDNode *N) {
8268 SDValue N0 = N->getOperand(0);
8269 SDValue N1 = N->getOperand(1);
8270 SDValue N2 = N->getOperand(2);
8271 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8272 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8273 EVT VT = N->getValueType(0);
8275 const TargetOptions &Options = DAG.getTarget().Options;
8277 // Constant fold FMA.
8278 if (isa<ConstantFPSDNode>(N0) &&
8279 isa<ConstantFPSDNode>(N1) &&
8280 isa<ConstantFPSDNode>(N2)) {
8281 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8284 if (Options.UnsafeFPMath) {
8285 if (N0CFP && N0CFP->isZero())
8287 if (N1CFP && N1CFP->isZero())
8290 // TODO: The FMA node should have flags that propagate to these nodes.
8291 if (N0CFP && N0CFP->isExactlyValue(1.0))
8292 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8293 if (N1CFP && N1CFP->isExactlyValue(1.0))
8294 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8296 // Canonicalize (fma c, x, y) -> (fma x, c, y)
8297 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8298 !isConstantFPBuildVectorOrConstantFP(N1))
8299 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8301 // TODO: FMA nodes should have flags that propagate to the created nodes.
8302 // For now, create a Flags object for use with all unsafe math transforms.
8304 Flags.setUnsafeAlgebra(true);
8306 if (Options.UnsafeFPMath) {
8307 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8308 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8309 isConstantFPBuildVectorOrConstantFP(N1) &&
8310 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8311 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8312 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1),
8316 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8317 if (N0.getOpcode() == ISD::FMUL &&
8318 isConstantFPBuildVectorOrConstantFP(N1) &&
8319 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8320 return DAG.getNode(ISD::FMA, dl, VT,
8322 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1),
8328 // (fma x, 1, y) -> (fadd x, y)
8329 // (fma x, -1, y) -> (fadd (fneg x), y)
8331 if (N1CFP->isExactlyValue(1.0))
8332 // TODO: The FMA node should have flags that propagate to this node.
8333 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8335 if (N1CFP->isExactlyValue(-1.0) &&
8336 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8337 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8338 AddToWorklist(RHSNeg.getNode());
8339 // TODO: The FMA node should have flags that propagate to this node.
8340 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8344 if (Options.UnsafeFPMath) {
8345 // (fma x, c, x) -> (fmul x, (c+1))
8346 if (N1CFP && N0 == N2) {
8347 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8348 DAG.getNode(ISD::FADD, dl, VT,
8349 N1, DAG.getConstantFP(1.0, dl, VT),
8353 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8354 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8355 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8356 DAG.getNode(ISD::FADD, dl, VT,
8357 N1, DAG.getConstantFP(-1.0, dl, VT),
8365 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8367 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8368 // Notice that this is not always beneficial. One reason is different target
8369 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8370 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8371 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8372 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8373 if (!DAG.getTarget().Options.UnsafeFPMath)
8376 // Skip if current node is a reciprocal.
8377 SDValue N0 = N->getOperand(0);
8378 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8379 if (N0CFP && N0CFP->isExactlyValue(1.0))
8382 // Exit early if the target does not want this transform or if there can't
8383 // possibly be enough uses of the divisor to make the transform worthwhile.
8384 SDValue N1 = N->getOperand(1);
8385 unsigned MinUses = TLI.combineRepeatedFPDivisors();
8386 if (!MinUses || N1->use_size() < MinUses)
8389 // Find all FDIV users of the same divisor.
8390 // Use a set because duplicates may be present in the user list.
8391 SetVector<SDNode *> Users;
8392 for (auto *U : N1->uses())
8393 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8396 // Now that we have the actual number of divisor uses, make sure it meets
8397 // the minimum threshold specified by the target.
8398 if (Users.size() < MinUses)
8401 EVT VT = N->getValueType(0);
8403 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8404 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8405 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8407 // Dividend / Divisor -> Dividend * Reciprocal
8408 for (auto *U : Users) {
8409 SDValue Dividend = U->getOperand(0);
8410 if (Dividend != FPOne) {
8411 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8413 CombineTo(U, NewNode);
8414 } else if (U != Reciprocal.getNode()) {
8415 // In the absence of fast-math-flags, this user node is always the
8416 // same node as Reciprocal, but with FMF they may be different nodes.
8417 CombineTo(U, Reciprocal);
8420 return SDValue(N, 0); // N was replaced.
8423 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8424 SDValue N0 = N->getOperand(0);
8425 SDValue N1 = N->getOperand(1);
8426 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8427 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8428 EVT VT = N->getValueType(0);
8430 const TargetOptions &Options = DAG.getTarget().Options;
8431 SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8435 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8438 // fold (fdiv c1, c2) -> c1/c2
8440 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8442 if (Options.UnsafeFPMath) {
8443 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8445 // Compute the reciprocal 1.0 / c2.
8446 APFloat N1APF = N1CFP->getValueAPF();
8447 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8448 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8449 // Only do the transform if the reciprocal is a legal fp immediate that
8450 // isn't too nasty (eg NaN, denormal, ...).
8451 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8452 (!LegalOperations ||
8453 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8454 // backend)... we should handle this gracefully after Legalize.
8455 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8456 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8457 TLI.isFPImmLegal(Recip, VT)))
8458 return DAG.getNode(ISD::FMUL, DL, VT, N0,
8459 DAG.getConstantFP(Recip, DL, VT), Flags);
8462 // If this FDIV is part of a reciprocal square root, it may be folded
8463 // into a target-specific square root estimate instruction.
8464 if (N1.getOpcode() == ISD::FSQRT) {
8465 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) {
8466 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8468 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8469 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8470 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8472 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8473 AddToWorklist(RV.getNode());
8474 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8476 } else if (N1.getOpcode() == ISD::FP_ROUND &&
8477 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8478 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8480 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8481 AddToWorklist(RV.getNode());
8482 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8484 } else if (N1.getOpcode() == ISD::FMUL) {
8485 // Look through an FMUL. Even though this won't remove the FDIV directly,
8486 // it's still worthwhile to get rid of the FSQRT if possible.
8489 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8490 SqrtOp = N1.getOperand(0);
8491 OtherOp = N1.getOperand(1);
8492 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8493 SqrtOp = N1.getOperand(1);
8494 OtherOp = N1.getOperand(0);
8496 if (SqrtOp.getNode()) {
8497 // We found a FSQRT, so try to make this fold:
8498 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8499 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
8500 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
8501 AddToWorklist(RV.getNode());
8502 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8507 // Fold into a reciprocal estimate and multiply instead of a real divide.
8508 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
8509 AddToWorklist(RV.getNode());
8510 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8514 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8515 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8516 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8517 // Both can be negated for free, check to see if at least one is cheaper
8519 if (LHSNeg == 2 || RHSNeg == 2)
8520 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8521 GetNegatedExpression(N0, DAG, LegalOperations),
8522 GetNegatedExpression(N1, DAG, LegalOperations),
8527 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8528 return CombineRepeatedDivisors;
8533 SDValue DAGCombiner::visitFREM(SDNode *N) {
8534 SDValue N0 = N->getOperand(0);
8535 SDValue N1 = N->getOperand(1);
8536 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8537 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8538 EVT VT = N->getValueType(0);
8540 // fold (frem c1, c2) -> fmod(c1,c2)
8542 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
8543 &cast<BinaryWithFlagsSDNode>(N)->Flags);
8548 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8549 if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8552 // TODO: FSQRT nodes should have flags that propagate to the created nodes.
8553 // For now, create a Flags object for use with all unsafe math transforms.
8555 Flags.setUnsafeAlgebra(true);
8557 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8558 SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags);
8562 EVT VT = RV.getValueType();
8564 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags);
8565 AddToWorklist(RV.getNode());
8567 // Unfortunately, RV is now NaN if the input was exactly 0.
8568 // Select out this case and force the answer to 0.
8569 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8570 EVT CCVT = getSetCCResultType(VT);
8571 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8572 AddToWorklist(ZeroCmp.getNode());
8573 AddToWorklist(RV.getNode());
8575 return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8579 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8580 SDValue N0 = N->getOperand(0);
8581 SDValue N1 = N->getOperand(1);
8582 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8583 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8584 EVT VT = N->getValueType(0);
8586 if (N0CFP && N1CFP) // Constant fold
8587 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8590 const APFloat& V = N1CFP->getValueAPF();
8591 // copysign(x, c1) -> fabs(x) iff ispos(c1)
8592 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8593 if (!V.isNegative()) {
8594 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8595 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8597 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8598 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8599 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8603 // copysign(fabs(x), y) -> copysign(x, y)
8604 // copysign(fneg(x), y) -> copysign(x, y)
8605 // copysign(copysign(x,z), y) -> copysign(x, y)
8606 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8607 N0.getOpcode() == ISD::FCOPYSIGN)
8608 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8609 N0.getOperand(0), N1);
8611 // copysign(x, abs(y)) -> abs(x)
8612 if (N1.getOpcode() == ISD::FABS)
8613 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8615 // copysign(x, copysign(y,z)) -> copysign(x, z)
8616 if (N1.getOpcode() == ISD::FCOPYSIGN)
8617 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8618 N0, N1.getOperand(1));
8620 // copysign(x, fp_extend(y)) -> copysign(x, y)
8621 // copysign(x, fp_round(y)) -> copysign(x, y)
8622 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8623 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8624 N0, N1.getOperand(0));
8629 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8630 SDValue N0 = N->getOperand(0);
8631 EVT VT = N->getValueType(0);
8632 EVT OpVT = N0.getValueType();
8634 // fold (sint_to_fp c1) -> c1fp
8635 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8636 // ...but only if the target supports immediate floating-point values
8637 (!LegalOperations ||
8638 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8639 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8641 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8642 // but UINT_TO_FP is legal on this target, try to convert.
8643 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8644 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8645 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8646 if (DAG.SignBitIsZero(N0))
8647 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8650 // The next optimizations are desirable only if SELECT_CC can be lowered.
8651 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8652 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8653 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8655 (!LegalOperations ||
8656 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8659 { N0.getOperand(0), N0.getOperand(1),
8660 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8662 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8665 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8666 // (select_cc x, y, 1.0, 0.0,, cc)
8667 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8668 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8669 (!LegalOperations ||
8670 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8673 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8674 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8675 N0.getOperand(0).getOperand(2) };
8676 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8683 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8684 SDValue N0 = N->getOperand(0);
8685 EVT VT = N->getValueType(0);
8686 EVT OpVT = N0.getValueType();
8688 // fold (uint_to_fp c1) -> c1fp
8689 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8690 // ...but only if the target supports immediate floating-point values
8691 (!LegalOperations ||
8692 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8693 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8695 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8696 // but SINT_TO_FP is legal on this target, try to convert.
8697 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8698 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8699 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8700 if (DAG.SignBitIsZero(N0))
8701 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8704 // The next optimizations are desirable only if SELECT_CC can be lowered.
8705 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8706 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8708 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8709 (!LegalOperations ||
8710 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8713 { N0.getOperand(0), N0.getOperand(1),
8714 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8716 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8723 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8724 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8725 SDValue N0 = N->getOperand(0);
8726 EVT VT = N->getValueType(0);
8728 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8731 SDValue Src = N0.getOperand(0);
8732 EVT SrcVT = Src.getValueType();
8733 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8734 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8736 // We can safely assume the conversion won't overflow the output range,
8737 // because (for example) (uint8_t)18293.f is undefined behavior.
8739 // Since we can assume the conversion won't overflow, our decision as to
8740 // whether the input will fit in the float should depend on the minimum
8741 // of the input range and output range.
8743 // This means this is also safe for a signed input and unsigned output, since
8744 // a negative input would lead to undefined behavior.
8745 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8746 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8747 unsigned ActualSize = std::min(InputSize, OutputSize);
8748 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8750 // We can only fold away the float conversion if the input range can be
8751 // represented exactly in the float range.
8752 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8753 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8754 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8756 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8758 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8759 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8762 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8767 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8768 SDValue N0 = N->getOperand(0);
8769 EVT VT = N->getValueType(0);
8771 // fold (fp_to_sint c1fp) -> c1
8772 if (isConstantFPBuildVectorOrConstantFP(N0))
8773 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8775 return FoldIntToFPToInt(N, DAG);
8778 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8779 SDValue N0 = N->getOperand(0);
8780 EVT VT = N->getValueType(0);
8782 // fold (fp_to_uint c1fp) -> c1
8783 if (isConstantFPBuildVectorOrConstantFP(N0))
8784 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8786 return FoldIntToFPToInt(N, DAG);
8789 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8790 SDValue N0 = N->getOperand(0);
8791 SDValue N1 = N->getOperand(1);
8792 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8793 EVT VT = N->getValueType(0);
8795 // fold (fp_round c1fp) -> c1fp
8797 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8799 // fold (fp_round (fp_extend x)) -> x
8800 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8801 return N0.getOperand(0);
8803 // fold (fp_round (fp_round x)) -> (fp_round x)
8804 if (N0.getOpcode() == ISD::FP_ROUND) {
8805 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8806 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8807 // If the first fp_round isn't a value preserving truncation, it might
8808 // introduce a tie in the second fp_round, that wouldn't occur in the
8809 // single-step fp_round we want to fold to.
8810 // In other words, double rounding isn't the same as rounding.
8811 // Also, this is a value preserving truncation iff both fp_round's are.
8812 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8814 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8815 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8819 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8820 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8821 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8822 N0.getOperand(0), N1);
8823 AddToWorklist(Tmp.getNode());
8824 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8825 Tmp, N0.getOperand(1));
8831 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8832 SDValue N0 = N->getOperand(0);
8833 EVT VT = N->getValueType(0);
8834 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8835 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8837 // fold (fp_round_inreg c1fp) -> c1fp
8838 if (N0CFP && isTypeLegal(EVT)) {
8840 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8841 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8847 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8848 SDValue N0 = N->getOperand(0);
8849 EVT VT = N->getValueType(0);
8851 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8852 if (N->hasOneUse() &&
8853 N->use_begin()->getOpcode() == ISD::FP_ROUND)
8856 // fold (fp_extend c1fp) -> c1fp
8857 if (isConstantFPBuildVectorOrConstantFP(N0))
8858 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8860 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8861 if (N0.getOpcode() == ISD::FP16_TO_FP &&
8862 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8863 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8865 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8867 if (N0.getOpcode() == ISD::FP_ROUND
8868 && N0.getNode()->getConstantOperandVal(1) == 1) {
8869 SDValue In = N0.getOperand(0);
8870 if (In.getValueType() == VT) return In;
8871 if (VT.bitsLT(In.getValueType()))
8872 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8873 In, N0.getOperand(1));
8874 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8877 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8878 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8879 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8880 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8881 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8883 LN0->getBasePtr(), N0.getValueType(),
8884 LN0->getMemOperand());
8885 CombineTo(N, ExtLoad);
8886 CombineTo(N0.getNode(),
8887 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8888 N0.getValueType(), ExtLoad,
8889 DAG.getIntPtrConstant(1, SDLoc(N0))),
8890 ExtLoad.getValue(1));
8891 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8897 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8898 SDValue N0 = N->getOperand(0);
8899 EVT VT = N->getValueType(0);
8901 // fold (fceil c1) -> fceil(c1)
8902 if (isConstantFPBuildVectorOrConstantFP(N0))
8903 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8908 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8909 SDValue N0 = N->getOperand(0);
8910 EVT VT = N->getValueType(0);
8912 // fold (ftrunc c1) -> ftrunc(c1)
8913 if (isConstantFPBuildVectorOrConstantFP(N0))
8914 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8919 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8920 SDValue N0 = N->getOperand(0);
8921 EVT VT = N->getValueType(0);
8923 // fold (ffloor c1) -> ffloor(c1)
8924 if (isConstantFPBuildVectorOrConstantFP(N0))
8925 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8930 // FIXME: FNEG and FABS have a lot in common; refactor.
8931 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8932 SDValue N0 = N->getOperand(0);
8933 EVT VT = N->getValueType(0);
8935 // Constant fold FNEG.
8936 if (isConstantFPBuildVectorOrConstantFP(N0))
8937 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8939 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8940 &DAG.getTarget().Options))
8941 return GetNegatedExpression(N0, DAG, LegalOperations);
8943 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8944 // constant pool values.
8945 if (!TLI.isFNegFree(VT) &&
8946 N0.getOpcode() == ISD::BITCAST &&
8947 N0.getNode()->hasOneUse()) {
8948 SDValue Int = N0.getOperand(0);
8949 EVT IntVT = Int.getValueType();
8950 if (IntVT.isInteger() && !IntVT.isVector()) {
8952 if (N0.getValueType().isVector()) {
8953 // For a vector, get a mask such as 0x80... per scalar element
8955 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8956 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8958 // For a scalar, just generate 0x80...
8959 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8962 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8963 DAG.getConstant(SignMask, DL0, IntVT));
8964 AddToWorklist(Int.getNode());
8965 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8969 // (fneg (fmul c, x)) -> (fmul -c, x)
8970 if (N0.getOpcode() == ISD::FMUL &&
8971 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
8972 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8974 APFloat CVal = CFP1->getValueAPF();
8976 if (Level >= AfterLegalizeDAG &&
8977 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8978 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8979 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8980 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8982 &cast<BinaryWithFlagsSDNode>(N0)->Flags);
8989 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8990 SDValue N0 = N->getOperand(0);
8991 SDValue N1 = N->getOperand(1);
8992 EVT VT = N->getValueType(0);
8993 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8994 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8996 if (N0CFP && N1CFP) {
8997 const APFloat &C0 = N0CFP->getValueAPF();
8998 const APFloat &C1 = N1CFP->getValueAPF();
8999 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9002 // Canonicalize to constant on RHS.
9003 if (isConstantFPBuildVectorOrConstantFP(N0) &&
9004 !isConstantFPBuildVectorOrConstantFP(N1))
9005 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9010 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9011 SDValue N0 = N->getOperand(0);
9012 SDValue N1 = N->getOperand(1);
9013 EVT VT = N->getValueType(0);
9014 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9015 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9017 if (N0CFP && N1CFP) {
9018 const APFloat &C0 = N0CFP->getValueAPF();
9019 const APFloat &C1 = N1CFP->getValueAPF();
9020 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9023 // Canonicalize to constant on RHS.
9024 if (isConstantFPBuildVectorOrConstantFP(N0) &&
9025 !isConstantFPBuildVectorOrConstantFP(N1))
9026 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9031 SDValue DAGCombiner::visitFABS(SDNode *N) {
9032 SDValue N0 = N->getOperand(0);
9033 EVT VT = N->getValueType(0);
9035 // fold (fabs c1) -> fabs(c1)
9036 if (isConstantFPBuildVectorOrConstantFP(N0))
9037 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9039 // fold (fabs (fabs x)) -> (fabs x)
9040 if (N0.getOpcode() == ISD::FABS)
9041 return N->getOperand(0);
9043 // fold (fabs (fneg x)) -> (fabs x)
9044 // fold (fabs (fcopysign x, y)) -> (fabs x)
9045 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9046 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9048 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9049 // constant pool values.
9050 if (!TLI.isFAbsFree(VT) &&
9051 N0.getOpcode() == ISD::BITCAST &&
9052 N0.getNode()->hasOneUse()) {
9053 SDValue Int = N0.getOperand(0);
9054 EVT IntVT = Int.getValueType();
9055 if (IntVT.isInteger() && !IntVT.isVector()) {
9057 if (N0.getValueType().isVector()) {
9058 // For a vector, get a mask such as 0x7f... per scalar element
9060 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9061 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9063 // For a scalar, just generate 0x7f...
9064 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9067 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9068 DAG.getConstant(SignMask, DL, IntVT));
9069 AddToWorklist(Int.getNode());
9070 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
9077 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9078 SDValue Chain = N->getOperand(0);
9079 SDValue N1 = N->getOperand(1);
9080 SDValue N2 = N->getOperand(2);
9082 // If N is a constant we could fold this into a fallthrough or unconditional
9083 // branch. However that doesn't happen very often in normal code, because
9084 // Instcombine/SimplifyCFG should have handled the available opportunities.
9085 // If we did this folding here, it would be necessary to update the
9086 // MachineBasicBlock CFG, which is awkward.
9088 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9090 if (N1.getOpcode() == ISD::SETCC &&
9091 TLI.isOperationLegalOrCustom(ISD::BR_CC,
9092 N1.getOperand(0).getValueType())) {
9093 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9094 Chain, N1.getOperand(2),
9095 N1.getOperand(0), N1.getOperand(1), N2);
9098 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9099 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9100 (N1.getOperand(0).hasOneUse() &&
9101 N1.getOperand(0).getOpcode() == ISD::SRL))) {
9102 SDNode *Trunc = nullptr;
9103 if (N1.getOpcode() == ISD::TRUNCATE) {
9104 // Look pass the truncate.
9105 Trunc = N1.getNode();
9106 N1 = N1.getOperand(0);
9109 // Match this pattern so that we can generate simpler code:
9112 // %b = and i32 %a, 2
9113 // %c = srl i32 %b, 1
9114 // brcond i32 %c ...
9119 // %b = and i32 %a, 2
9120 // %c = setcc eq %b, 0
9123 // This applies only when the AND constant value has one bit set and the
9124 // SRL constant is equal to the log2 of the AND constant. The back-end is
9125 // smart enough to convert the result into a TEST/JMP sequence.
9126 SDValue Op0 = N1.getOperand(0);
9127 SDValue Op1 = N1.getOperand(1);
9129 if (Op0.getOpcode() == ISD::AND &&
9130 Op1.getOpcode() == ISD::Constant) {
9131 SDValue AndOp1 = Op0.getOperand(1);
9133 if (AndOp1.getOpcode() == ISD::Constant) {
9134 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9136 if (AndConst.isPowerOf2() &&
9137 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9141 getSetCCResultType(Op0.getValueType()),
9142 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9145 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9146 MVT::Other, Chain, SetCC, N2);
9147 // Don't add the new BRCond into the worklist or else SimplifySelectCC
9148 // will convert it back to (X & C1) >> C2.
9149 CombineTo(N, NewBRCond, false);
9150 // Truncate is dead.
9152 deleteAndRecombine(Trunc);
9153 // Replace the uses of SRL with SETCC
9154 WorklistRemover DeadNodes(*this);
9155 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9156 deleteAndRecombine(N1.getNode());
9157 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9163 // Restore N1 if the above transformation doesn't match.
9164 N1 = N->getOperand(1);
9167 // Transform br(xor(x, y)) -> br(x != y)
9168 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9169 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9170 SDNode *TheXor = N1.getNode();
9171 SDValue Op0 = TheXor->getOperand(0);
9172 SDValue Op1 = TheXor->getOperand(1);
9173 if (Op0.getOpcode() == Op1.getOpcode()) {
9174 // Avoid missing important xor optimizations.
9175 if (SDValue Tmp = visitXOR(TheXor)) {
9176 if (Tmp.getNode() != TheXor) {
9177 DEBUG(dbgs() << "\nReplacing.8 ";
9179 dbgs() << "\nWith: ";
9180 Tmp.getNode()->dump(&DAG);
9182 WorklistRemover DeadNodes(*this);
9183 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9184 deleteAndRecombine(TheXor);
9185 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9186 MVT::Other, Chain, Tmp, N2);
9189 // visitXOR has changed XOR's operands or replaced the XOR completely,
9191 return SDValue(N, 0);
9195 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9197 if (isOneConstant(Op0) && Op0.hasOneUse() &&
9198 Op0.getOpcode() == ISD::XOR) {
9199 TheXor = Op0.getNode();
9203 EVT SetCCVT = N1.getValueType();
9205 SetCCVT = getSetCCResultType(SetCCVT);
9206 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9209 Equal ? ISD::SETEQ : ISD::SETNE);
9210 // Replace the uses of XOR with SETCC
9211 WorklistRemover DeadNodes(*this);
9212 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9213 deleteAndRecombine(N1.getNode());
9214 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9215 MVT::Other, Chain, SetCC, N2);
9222 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9224 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9225 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9226 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9228 // If N is a constant we could fold this into a fallthrough or unconditional
9229 // branch. However that doesn't happen very often in normal code, because
9230 // Instcombine/SimplifyCFG should have handled the available opportunities.
9231 // If we did this folding here, it would be necessary to update the
9232 // MachineBasicBlock CFG, which is awkward.
9234 // Use SimplifySetCC to simplify SETCC's.
9235 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9236 CondLHS, CondRHS, CC->get(), SDLoc(N),
9238 if (Simp.getNode()) AddToWorklist(Simp.getNode());
9240 // fold to a simpler setcc
9241 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9242 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9243 N->getOperand(0), Simp.getOperand(2),
9244 Simp.getOperand(0), Simp.getOperand(1),
9250 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9251 /// and that N may be folded in the load / store addressing mode.
9252 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9254 const TargetLowering &TLI) {
9258 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
9259 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9261 VT = LD->getMemoryVT();
9262 AS = LD->getAddressSpace();
9263 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
9264 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9266 VT = ST->getMemoryVT();
9267 AS = ST->getAddressSpace();
9271 TargetLowering::AddrMode AM;
9272 if (N->getOpcode() == ISD::ADD) {
9273 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9276 AM.BaseOffs = Offset->getSExtValue();
9280 } else if (N->getOpcode() == ISD::SUB) {
9281 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9284 AM.BaseOffs = -Offset->getSExtValue();
9291 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9292 VT.getTypeForEVT(*DAG.getContext()), AS);
9295 /// Try turning a load/store into a pre-indexed load/store when the base
9296 /// pointer is an add or subtract and it has other uses besides the load/store.
9297 /// After the transformation, the new indexed load/store has effectively folded
9298 /// the add/subtract in and all of its other uses are redirected to the
9300 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9301 if (Level < AfterLegalizeDAG)
9307 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9308 if (LD->isIndexed())
9310 VT = LD->getMemoryVT();
9311 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9312 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9314 Ptr = LD->getBasePtr();
9315 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9316 if (ST->isIndexed())
9318 VT = ST->getMemoryVT();
9319 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9320 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9322 Ptr = ST->getBasePtr();
9328 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9329 // out. There is no reason to make this a preinc/predec.
9330 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9331 Ptr.getNode()->hasOneUse())
9334 // Ask the target to do addressing mode selection.
9337 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9338 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9341 // Backends without true r+i pre-indexed forms may need to pass a
9342 // constant base with a variable offset so that constant coercion
9343 // will work with the patterns in canonical form.
9344 bool Swapped = false;
9345 if (isa<ConstantSDNode>(BasePtr)) {
9346 std::swap(BasePtr, Offset);
9350 // Don't create a indexed load / store with zero offset.
9351 if (isNullConstant(Offset))
9354 // Try turning it into a pre-indexed load / store except when:
9355 // 1) The new base ptr is a frame index.
9356 // 2) If N is a store and the new base ptr is either the same as or is a
9357 // predecessor of the value being stored.
9358 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9359 // that would create a cycle.
9360 // 4) All uses are load / store ops that use it as old base ptr.
9362 // Check #1. Preinc'ing a frame index would require copying the stack pointer
9363 // (plus the implicit offset) to a register to preinc anyway.
9364 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9369 SDValue Val = cast<StoreSDNode>(N)->getValue();
9370 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9374 // If the offset is a constant, there may be other adds of constants that
9375 // can be folded with this one. We should do this to avoid having to keep
9376 // a copy of the original base pointer.
9377 SmallVector<SDNode *, 16> OtherUses;
9378 if (isa<ConstantSDNode>(Offset))
9379 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9380 UE = BasePtr.getNode()->use_end();
9382 SDUse &Use = UI.getUse();
9383 // Skip the use that is Ptr and uses of other results from BasePtr's
9384 // node (important for nodes that return multiple results).
9385 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9388 if (Use.getUser()->isPredecessorOf(N))
9391 if (Use.getUser()->getOpcode() != ISD::ADD &&
9392 Use.getUser()->getOpcode() != ISD::SUB) {
9397 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9398 if (!isa<ConstantSDNode>(Op1)) {
9403 // FIXME: In some cases, we can be smarter about this.
9404 if (Op1.getValueType() != Offset.getValueType()) {
9409 OtherUses.push_back(Use.getUser());
9413 std::swap(BasePtr, Offset);
9415 // Now check for #3 and #4.
9416 bool RealUse = false;
9418 // Caches for hasPredecessorHelper
9419 SmallPtrSet<const SDNode *, 32> Visited;
9420 SmallVector<const SDNode *, 16> Worklist;
9422 for (SDNode *Use : Ptr.getNode()->uses()) {
9425 if (N->hasPredecessorHelper(Use, Visited, Worklist))
9428 // If Ptr may be folded in addressing mode of other use, then it's
9429 // not profitable to do this transformation.
9430 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9439 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9440 BasePtr, Offset, AM);
9442 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9443 BasePtr, Offset, AM);
9446 DEBUG(dbgs() << "\nReplacing.4 ";
9448 dbgs() << "\nWith: ";
9449 Result.getNode()->dump(&DAG);
9451 WorklistRemover DeadNodes(*this);
9453 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9454 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9456 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9459 // Finally, since the node is now dead, remove it from the graph.
9460 deleteAndRecombine(N);
9463 std::swap(BasePtr, Offset);
9465 // Replace other uses of BasePtr that can be updated to use Ptr
9466 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9467 unsigned OffsetIdx = 1;
9468 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9470 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9471 BasePtr.getNode() && "Expected BasePtr operand");
9473 // We need to replace ptr0 in the following expression:
9474 // x0 * offset0 + y0 * ptr0 = t0
9476 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9478 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9479 // indexed load/store and the expresion that needs to be re-written.
9481 // Therefore, we have:
9482 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9484 ConstantSDNode *CN =
9485 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9487 APInt Offset0 = CN->getAPIntValue();
9488 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9490 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9491 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9492 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9493 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9495 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9497 APInt CNV = Offset0;
9498 if (X0 < 0) CNV = -CNV;
9499 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9500 else CNV = CNV - Offset1;
9502 SDLoc DL(OtherUses[i]);
9504 // We can now generate the new expression.
9505 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9506 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9508 SDValue NewUse = DAG.getNode(Opcode,
9510 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9511 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9512 deleteAndRecombine(OtherUses[i]);
9515 // Replace the uses of Ptr with uses of the updated base value.
9516 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9517 deleteAndRecombine(Ptr.getNode());
9522 /// Try to combine a load/store with a add/sub of the base pointer node into a
9523 /// post-indexed load/store. The transformation folded the add/subtract into the
9524 /// new indexed load/store effectively and all of its uses are redirected to the
9526 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9527 if (Level < AfterLegalizeDAG)
9533 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9534 if (LD->isIndexed())
9536 VT = LD->getMemoryVT();
9537 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9538 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9540 Ptr = LD->getBasePtr();
9541 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9542 if (ST->isIndexed())
9544 VT = ST->getMemoryVT();
9545 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9546 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9548 Ptr = ST->getBasePtr();
9554 if (Ptr.getNode()->hasOneUse())
9557 for (SDNode *Op : Ptr.getNode()->uses()) {
9559 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9564 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9565 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9566 // Don't create a indexed load / store with zero offset.
9567 if (isNullConstant(Offset))
9570 // Try turning it into a post-indexed load / store except when
9571 // 1) All uses are load / store ops that use it as base ptr (and
9572 // it may be folded as addressing mmode).
9573 // 2) Op must be independent of N, i.e. Op is neither a predecessor
9574 // nor a successor of N. Otherwise, if Op is folded that would
9577 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9581 bool TryNext = false;
9582 for (SDNode *Use : BasePtr.getNode()->uses()) {
9583 if (Use == Ptr.getNode())
9586 // If all the uses are load / store addresses, then don't do the
9588 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9589 bool RealUse = false;
9590 for (SDNode *UseUse : Use->uses()) {
9591 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9606 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9607 SDValue Result = isLoad
9608 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9609 BasePtr, Offset, AM)
9610 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9611 BasePtr, Offset, AM);
9614 DEBUG(dbgs() << "\nReplacing.5 ";
9616 dbgs() << "\nWith: ";
9617 Result.getNode()->dump(&DAG);
9619 WorklistRemover DeadNodes(*this);
9621 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9622 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9624 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9627 // Finally, since the node is now dead, remove it from the graph.
9628 deleteAndRecombine(N);
9630 // Replace the uses of Use with uses of the updated base value.
9631 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9632 Result.getValue(isLoad ? 1 : 0));
9633 deleteAndRecombine(Op);
9642 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9643 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9644 ISD::MemIndexedMode AM = LD->getAddressingMode();
9645 assert(AM != ISD::UNINDEXED);
9646 SDValue BP = LD->getOperand(1);
9647 SDValue Inc = LD->getOperand(2);
9649 // Some backends use TargetConstants for load offsets, but don't expect
9650 // TargetConstants in general ADD nodes. We can convert these constants into
9651 // regular Constants (if the constant is not opaque).
9652 assert((Inc.getOpcode() != ISD::TargetConstant ||
9653 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9654 "Cannot split out indexing using opaque target constants");
9655 if (Inc.getOpcode() == ISD::TargetConstant) {
9656 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9657 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9658 ConstInc->getValueType(0));
9662 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9663 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9666 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9667 LoadSDNode *LD = cast<LoadSDNode>(N);
9668 SDValue Chain = LD->getChain();
9669 SDValue Ptr = LD->getBasePtr();
9671 // If load is not volatile and there are no uses of the loaded value (and
9672 // the updated indexed value in case of indexed loads), change uses of the
9673 // chain value into uses of the chain input (i.e. delete the dead load).
9674 if (!LD->isVolatile()) {
9675 if (N->getValueType(1) == MVT::Other) {
9677 if (!N->hasAnyUseOfValue(0)) {
9678 // It's not safe to use the two value CombineTo variant here. e.g.
9679 // v1, chain2 = load chain1, loc
9680 // v2, chain3 = load chain2, loc
9682 // Now we replace use of chain2 with chain1. This makes the second load
9683 // isomorphic to the one we are deleting, and thus makes this load live.
9684 DEBUG(dbgs() << "\nReplacing.6 ";
9686 dbgs() << "\nWith chain: ";
9687 Chain.getNode()->dump(&DAG);
9689 WorklistRemover DeadNodes(*this);
9690 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9693 deleteAndRecombine(N);
9695 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9699 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9701 // If this load has an opaque TargetConstant offset, then we cannot split
9702 // the indexing into an add/sub directly (that TargetConstant may not be
9703 // valid for a different type of node, and we cannot convert an opaque
9704 // target constant into a regular constant).
9705 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9706 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9708 if (!N->hasAnyUseOfValue(0) &&
9709 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9710 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9712 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9713 Index = SplitIndexingFromLoad(LD);
9714 // Try to fold the base pointer arithmetic into subsequent loads and
9716 AddUsersToWorklist(N);
9718 Index = DAG.getUNDEF(N->getValueType(1));
9719 DEBUG(dbgs() << "\nReplacing.7 ";
9721 dbgs() << "\nWith: ";
9722 Undef.getNode()->dump(&DAG);
9723 dbgs() << " and 2 other values\n");
9724 WorklistRemover DeadNodes(*this);
9725 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9726 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9727 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9728 deleteAndRecombine(N);
9729 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9734 // If this load is directly stored, replace the load value with the stored
9736 // TODO: Handle store large -> read small portion.
9737 // TODO: Handle TRUNCSTORE/LOADEXT
9738 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9739 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9740 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9741 if (PrevST->getBasePtr() == Ptr &&
9742 PrevST->getValue().getValueType() == N->getValueType(0))
9743 return CombineTo(N, Chain.getOperand(1), Chain);
9747 // Try to infer better alignment information than the load already has.
9748 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9749 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9750 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9752 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9753 LD->getValueType(0),
9754 Chain, Ptr, LD->getPointerInfo(),
9756 LD->isVolatile(), LD->isNonTemporal(),
9757 LD->isInvariant(), Align, LD->getAAInfo());
9758 if (NewLoad.getNode() != N)
9759 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9764 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9765 : DAG.getSubtarget().useAA();
9767 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9768 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9771 if (UseAA && LD->isUnindexed()) {
9772 // Walk up chain skipping non-aliasing memory nodes.
9773 SDValue BetterChain = FindBetterChain(N, Chain);
9775 // If there is a better chain.
9776 if (Chain != BetterChain) {
9779 // Replace the chain to void dependency.
9780 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9781 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9782 BetterChain, Ptr, LD->getMemOperand());
9784 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9785 LD->getValueType(0),
9786 BetterChain, Ptr, LD->getMemoryVT(),
9787 LD->getMemOperand());
9790 // Create token factor to keep old chain connected.
9791 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9792 MVT::Other, Chain, ReplLoad.getValue(1));
9794 // Make sure the new and old chains are cleaned up.
9795 AddToWorklist(Token.getNode());
9797 // Replace uses with load result and token factor. Don't add users
9799 return CombineTo(N, ReplLoad.getValue(0), Token, false);
9803 // Try transforming N to an indexed load.
9804 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9805 return SDValue(N, 0);
9807 // Try to slice up N to more direct loads if the slices are mapped to
9808 // different register banks or pairing can take place.
9810 return SDValue(N, 0);
9816 /// \brief Helper structure used to slice a load in smaller loads.
9817 /// Basically a slice is obtained from the following sequence:
9818 /// Origin = load Ty1, Base
9819 /// Shift = srl Ty1 Origin, CstTy Amount
9820 /// Inst = trunc Shift to Ty2
9822 /// Then, it will be rewriten into:
9823 /// Slice = load SliceTy, Base + SliceOffset
9824 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9826 /// SliceTy is deduced from the number of bits that are actually used to
9828 struct LoadedSlice {
9829 /// \brief Helper structure used to compute the cost of a slice.
9831 /// Are we optimizing for code size.
9836 unsigned CrossRegisterBanksCopies;
9840 Cost(bool ForCodeSize = false)
9841 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9842 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9844 /// \brief Get the cost of one isolated slice.
9845 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9846 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9847 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9848 EVT TruncType = LS.Inst->getValueType(0);
9849 EVT LoadedType = LS.getLoadedType();
9850 if (TruncType != LoadedType &&
9851 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9855 /// \brief Account for slicing gain in the current cost.
9856 /// Slicing provide a few gains like removing a shift or a
9857 /// truncate. This method allows to grow the cost of the original
9858 /// load with the gain from this slice.
9859 void addSliceGain(const LoadedSlice &LS) {
9860 // Each slice saves a truncate.
9861 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9862 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
9863 LS.Inst->getValueType(0)))
9865 // If there is a shift amount, this slice gets rid of it.
9868 // If this slice can merge a cross register bank copy, account for it.
9869 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9870 ++CrossRegisterBanksCopies;
9873 Cost &operator+=(const Cost &RHS) {
9875 Truncates += RHS.Truncates;
9876 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9882 bool operator==(const Cost &RHS) const {
9883 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9884 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9885 ZExts == RHS.ZExts && Shift == RHS.Shift;
9888 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9890 bool operator<(const Cost &RHS) const {
9891 // Assume cross register banks copies are as expensive as loads.
9892 // FIXME: Do we want some more target hooks?
9893 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9894 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9895 // Unless we are optimizing for code size, consider the
9896 // expensive operation first.
9897 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9898 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9899 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9900 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9903 bool operator>(const Cost &RHS) const { return RHS < *this; }
9905 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9907 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9909 // The last instruction that represent the slice. This should be a
9910 // truncate instruction.
9912 // The original load instruction.
9914 // The right shift amount in bits from the original load.
9916 // The DAG from which Origin came from.
9917 // This is used to get some contextual information about legal types, etc.
9920 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9921 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9922 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9924 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9925 /// \return Result is \p BitWidth and has used bits set to 1 and
9926 /// not used bits set to 0.
9927 APInt getUsedBits() const {
9928 // Reproduce the trunc(lshr) sequence:
9929 // - Start from the truncated value.
9930 // - Zero extend to the desired bit width.
9932 assert(Origin && "No original load to compare against.");
9933 unsigned BitWidth = Origin->getValueSizeInBits(0);
9934 assert(Inst && "This slice is not bound to an instruction");
9935 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9936 "Extracted slice is bigger than the whole type!");
9937 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9938 UsedBits.setAllBits();
9939 UsedBits = UsedBits.zext(BitWidth);
9944 /// \brief Get the size of the slice to be loaded in bytes.
9945 unsigned getLoadedSize() const {
9946 unsigned SliceSize = getUsedBits().countPopulation();
9947 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9948 return SliceSize / 8;
9951 /// \brief Get the type that will be loaded for this slice.
9952 /// Note: This may not be the final type for the slice.
9953 EVT getLoadedType() const {
9954 assert(DAG && "Missing context");
9955 LLVMContext &Ctxt = *DAG->getContext();
9956 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9959 /// \brief Get the alignment of the load used for this slice.
9960 unsigned getAlignment() const {
9961 unsigned Alignment = Origin->getAlignment();
9962 unsigned Offset = getOffsetFromBase();
9964 Alignment = MinAlign(Alignment, Alignment + Offset);
9968 /// \brief Check if this slice can be rewritten with legal operations.
9969 bool isLegal() const {
9970 // An invalid slice is not legal.
9971 if (!Origin || !Inst || !DAG)
9974 // Offsets are for indexed load only, we do not handle that.
9975 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9978 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9980 // Check that the type is legal.
9981 EVT SliceType = getLoadedType();
9982 if (!TLI.isTypeLegal(SliceType))
9985 // Check that the load is legal for this type.
9986 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9989 // Check that the offset can be computed.
9990 // 1. Check its type.
9991 EVT PtrType = Origin->getBasePtr().getValueType();
9992 if (PtrType == MVT::Untyped || PtrType.isExtended())
9995 // 2. Check that it fits in the immediate.
9996 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9999 // 3. Check that the computation is legal.
10000 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10003 // Check that the zext is legal if it needs one.
10004 EVT TruncateType = Inst->getValueType(0);
10005 if (TruncateType != SliceType &&
10006 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10012 /// \brief Get the offset in bytes of this slice in the original chunk of
10014 /// \pre DAG != nullptr.
10015 uint64_t getOffsetFromBase() const {
10016 assert(DAG && "Missing context.");
10017 bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10018 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10019 uint64_t Offset = Shift / 8;
10020 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10021 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10022 "The size of the original loaded type is not a multiple of a"
10024 // If Offset is bigger than TySizeInBytes, it means we are loading all
10025 // zeros. This should have been optimized before in the process.
10026 assert(TySizeInBytes > Offset &&
10027 "Invalid shift amount for given loaded size");
10029 Offset = TySizeInBytes - Offset - getLoadedSize();
10033 /// \brief Generate the sequence of instructions to load the slice
10034 /// represented by this object and redirect the uses of this slice to
10035 /// this new sequence of instructions.
10036 /// \pre this->Inst && this->Origin are valid Instructions and this
10037 /// object passed the legal check: LoadedSlice::isLegal returned true.
10038 /// \return The last instruction of the sequence used to load the slice.
10039 SDValue loadSlice() const {
10040 assert(Inst && Origin && "Unable to replace a non-existing slice.");
10041 const SDValue &OldBaseAddr = Origin->getBasePtr();
10042 SDValue BaseAddr = OldBaseAddr;
10043 // Get the offset in that chunk of bytes w.r.t. the endianess.
10044 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10045 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10047 // BaseAddr = BaseAddr + Offset.
10048 EVT ArithType = BaseAddr.getValueType();
10050 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10051 DAG->getConstant(Offset, DL, ArithType));
10054 // Create the type of the loaded slice according to its size.
10055 EVT SliceType = getLoadedType();
10057 // Create the load for the slice.
10058 SDValue LastInst = DAG->getLoad(
10059 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10060 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
10061 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
10062 // If the final type is not the same as the loaded type, this means that
10063 // we have to pad with zero. Create a zero extend for that.
10064 EVT FinalType = Inst->getValueType(0);
10065 if (SliceType != FinalType)
10067 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10071 /// \brief Check if this slice can be merged with an expensive cross register
10072 /// bank copy. E.g.,
10074 /// f = bitcast i32 i to float
10075 bool canMergeExpensiveCrossRegisterBankCopy() const {
10076 if (!Inst || !Inst->hasOneUse())
10078 SDNode *Use = *Inst->use_begin();
10079 if (Use->getOpcode() != ISD::BITCAST)
10081 assert(DAG && "Missing context");
10082 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10083 EVT ResVT = Use->getValueType(0);
10084 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10085 const TargetRegisterClass *ArgRC =
10086 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10087 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10090 // At this point, we know that we perform a cross-register-bank copy.
10091 // Check if it is expensive.
10092 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10093 // Assume bitcasts are cheap, unless both register classes do not
10094 // explicitly share a common sub class.
10095 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10098 // Check if it will be merged with the load.
10099 // 1. Check the alignment constraint.
10100 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10101 ResVT.getTypeForEVT(*DAG->getContext()));
10103 if (RequiredAlignment > getAlignment())
10106 // 2. Check that the load is a legal operation for that type.
10107 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10110 // 3. Check that we do not have a zext in the way.
10111 if (Inst->getValueType(0) != getLoadedType())
10119 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10120 /// \p UsedBits looks like 0..0 1..1 0..0.
10121 static bool areUsedBitsDense(const APInt &UsedBits) {
10122 // If all the bits are one, this is dense!
10123 if (UsedBits.isAllOnesValue())
10126 // Get rid of the unused bits on the right.
10127 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10128 // Get rid of the unused bits on the left.
10129 if (NarrowedUsedBits.countLeadingZeros())
10130 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10131 // Check that the chunk of bits is completely used.
10132 return NarrowedUsedBits.isAllOnesValue();
10135 /// \brief Check whether or not \p First and \p Second are next to each other
10136 /// in memory. This means that there is no hole between the bits loaded
10137 /// by \p First and the bits loaded by \p Second.
10138 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10139 const LoadedSlice &Second) {
10140 assert(First.Origin == Second.Origin && First.Origin &&
10141 "Unable to match different memory origins.");
10142 APInt UsedBits = First.getUsedBits();
10143 assert((UsedBits & Second.getUsedBits()) == 0 &&
10144 "Slices are not supposed to overlap.");
10145 UsedBits |= Second.getUsedBits();
10146 return areUsedBitsDense(UsedBits);
10149 /// \brief Adjust the \p GlobalLSCost according to the target
10150 /// paring capabilities and the layout of the slices.
10151 /// \pre \p GlobalLSCost should account for at least as many loads as
10152 /// there is in the slices in \p LoadedSlices.
10153 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10154 LoadedSlice::Cost &GlobalLSCost) {
10155 unsigned NumberOfSlices = LoadedSlices.size();
10156 // If there is less than 2 elements, no pairing is possible.
10157 if (NumberOfSlices < 2)
10160 // Sort the slices so that elements that are likely to be next to each
10161 // other in memory are next to each other in the list.
10162 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10163 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10164 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10165 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10167 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10168 // First (resp. Second) is the first (resp. Second) potentially candidate
10169 // to be placed in a paired load.
10170 const LoadedSlice *First = nullptr;
10171 const LoadedSlice *Second = nullptr;
10172 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10173 // Set the beginning of the pair.
10176 Second = &LoadedSlices[CurrSlice];
10178 // If First is NULL, it means we start a new pair.
10179 // Get to the next slice.
10183 EVT LoadedType = First->getLoadedType();
10185 // If the types of the slices are different, we cannot pair them.
10186 if (LoadedType != Second->getLoadedType())
10189 // Check if the target supplies paired loads for this type.
10190 unsigned RequiredAlignment = 0;
10191 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10192 // move to the next pair, this type is hopeless.
10196 // Check if we meet the alignment requirement.
10197 if (RequiredAlignment > First->getAlignment())
10200 // Check that both loads are next to each other in memory.
10201 if (!areSlicesNextToEachOther(*First, *Second))
10204 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10205 --GlobalLSCost.Loads;
10206 // Move to the next pair.
10211 /// \brief Check the profitability of all involved LoadedSlice.
10212 /// Currently, it is considered profitable if there is exactly two
10213 /// involved slices (1) which are (2) next to each other in memory, and
10214 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10216 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10217 /// the elements themselves.
10219 /// FIXME: When the cost model will be mature enough, we can relax
10220 /// constraints (1) and (2).
10221 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10222 const APInt &UsedBits, bool ForCodeSize) {
10223 unsigned NumberOfSlices = LoadedSlices.size();
10224 if (StressLoadSlicing)
10225 return NumberOfSlices > 1;
10228 if (NumberOfSlices != 2)
10232 if (!areUsedBitsDense(UsedBits))
10236 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10237 // The original code has one big load.
10238 OrigCost.Loads = 1;
10239 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10240 const LoadedSlice &LS = LoadedSlices[CurrSlice];
10241 // Accumulate the cost of all the slices.
10242 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10243 GlobalSlicingCost += SliceCost;
10245 // Account as cost in the original configuration the gain obtained
10246 // with the current slices.
10247 OrigCost.addSliceGain(LS);
10250 // If the target supports paired load, adjust the cost accordingly.
10251 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10252 return OrigCost > GlobalSlicingCost;
10255 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10256 /// operations, split it in the various pieces being extracted.
10258 /// This sort of thing is introduced by SROA.
10259 /// This slicing takes care not to insert overlapping loads.
10260 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10261 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10262 if (Level < AfterLegalizeDAG)
10265 LoadSDNode *LD = cast<LoadSDNode>(N);
10266 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10267 !LD->getValueType(0).isInteger())
10270 // Keep track of already used bits to detect overlapping values.
10271 // In that case, we will just abort the transformation.
10272 APInt UsedBits(LD->getValueSizeInBits(0), 0);
10274 SmallVector<LoadedSlice, 4> LoadedSlices;
10276 // Check if this load is used as several smaller chunks of bits.
10277 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10278 // of computation for each trunc.
10279 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10280 UI != UIEnd; ++UI) {
10281 // Skip the uses of the chain.
10282 if (UI.getUse().getResNo() != 0)
10285 SDNode *User = *UI;
10286 unsigned Shift = 0;
10288 // Check if this is a trunc(lshr).
10289 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10290 isa<ConstantSDNode>(User->getOperand(1))) {
10291 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10292 User = *User->use_begin();
10295 // At this point, User is a Truncate, iff we encountered, trunc or
10297 if (User->getOpcode() != ISD::TRUNCATE)
10300 // The width of the type must be a power of 2 and greater than 8-bits.
10301 // Otherwise the load cannot be represented in LLVM IR.
10302 // Moreover, if we shifted with a non-8-bits multiple, the slice
10303 // will be across several bytes. We do not support that.
10304 unsigned Width = User->getValueSizeInBits(0);
10305 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10308 // Build the slice for this chain of computations.
10309 LoadedSlice LS(User, LD, Shift, &DAG);
10310 APInt CurrentUsedBits = LS.getUsedBits();
10312 // Check if this slice overlaps with another.
10313 if ((CurrentUsedBits & UsedBits) != 0)
10315 // Update the bits used globally.
10316 UsedBits |= CurrentUsedBits;
10318 // Check if the new slice would be legal.
10322 // Record the slice.
10323 LoadedSlices.push_back(LS);
10326 // Abort slicing if it does not seem to be profitable.
10327 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10332 // Rewrite each chain to use an independent load.
10333 // By construction, each chain can be represented by a unique load.
10335 // Prepare the argument for the new token factor for all the slices.
10336 SmallVector<SDValue, 8> ArgChains;
10337 for (SmallVectorImpl<LoadedSlice>::const_iterator
10338 LSIt = LoadedSlices.begin(),
10339 LSItEnd = LoadedSlices.end();
10340 LSIt != LSItEnd; ++LSIt) {
10341 SDValue SliceInst = LSIt->loadSlice();
10342 CombineTo(LSIt->Inst, SliceInst, true);
10343 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10344 SliceInst = SliceInst.getOperand(0);
10345 assert(SliceInst->getOpcode() == ISD::LOAD &&
10346 "It takes more than a zext to get to the loaded slice!!");
10347 ArgChains.push_back(SliceInst.getValue(1));
10350 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10352 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10356 /// Check to see if V is (and load (ptr), imm), where the load is having
10357 /// specific bytes cleared out. If so, return the byte size being masked out
10358 /// and the shift amount.
10359 static std::pair<unsigned, unsigned>
10360 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10361 std::pair<unsigned, unsigned> Result(0, 0);
10363 // Check for the structure we're looking for.
10364 if (V->getOpcode() != ISD::AND ||
10365 !isa<ConstantSDNode>(V->getOperand(1)) ||
10366 !ISD::isNormalLoad(V->getOperand(0).getNode()))
10369 // Check the chain and pointer.
10370 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10371 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
10373 // The store should be chained directly to the load or be an operand of a
10375 if (LD == Chain.getNode())
10377 else if (Chain->getOpcode() != ISD::TokenFactor)
10378 return Result; // Fail.
10381 for (const SDValue &ChainOp : Chain->op_values())
10382 if (ChainOp.getNode() == LD) {
10386 if (!isOk) return Result;
10389 // This only handles simple types.
10390 if (V.getValueType() != MVT::i16 &&
10391 V.getValueType() != MVT::i32 &&
10392 V.getValueType() != MVT::i64)
10395 // Check the constant mask. Invert it so that the bits being masked out are
10396 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
10397 // follow the sign bit for uniformity.
10398 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10399 unsigned NotMaskLZ = countLeadingZeros(NotMask);
10400 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
10401 unsigned NotMaskTZ = countTrailingZeros(NotMask);
10402 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
10403 if (NotMaskLZ == 64) return Result; // All zero mask.
10405 // See if we have a continuous run of bits. If so, we have 0*1+0*
10406 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10409 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10410 if (V.getValueType() != MVT::i64 && NotMaskLZ)
10411 NotMaskLZ -= 64-V.getValueSizeInBits();
10413 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10414 switch (MaskedBytes) {
10418 default: return Result; // All one mask, or 5-byte mask.
10421 // Verify that the first bit starts at a multiple of mask so that the access
10422 // is aligned the same as the access width.
10423 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10425 Result.first = MaskedBytes;
10426 Result.second = NotMaskTZ/8;
10431 /// Check to see if IVal is something that provides a value as specified by
10432 /// MaskInfo. If so, replace the specified store with a narrower store of
10433 /// truncated IVal.
10435 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10436 SDValue IVal, StoreSDNode *St,
10438 unsigned NumBytes = MaskInfo.first;
10439 unsigned ByteShift = MaskInfo.second;
10440 SelectionDAG &DAG = DC->getDAG();
10442 // Check to see if IVal is all zeros in the part being masked in by the 'or'
10443 // that uses this. If not, this is not a replacement.
10444 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10445 ByteShift*8, (ByteShift+NumBytes)*8);
10446 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10448 // Check that it is legal on the target to do this. It is legal if the new
10449 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10451 MVT VT = MVT::getIntegerVT(NumBytes*8);
10452 if (!DC->isTypeLegal(VT))
10455 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
10456 // shifted by ByteShift and truncated down to NumBytes.
10459 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10460 DAG.getConstant(ByteShift*8, DL,
10461 DC->getShiftAmountTy(IVal.getValueType())));
10464 // Figure out the offset for the store and the alignment of the access.
10466 unsigned NewAlign = St->getAlignment();
10468 if (DAG.getDataLayout().isLittleEndian())
10469 StOffset = ByteShift;
10471 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10473 SDValue Ptr = St->getBasePtr();
10476 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10477 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10478 NewAlign = MinAlign(NewAlign, StOffset);
10481 // Truncate down to the new size.
10482 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10485 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10486 St->getPointerInfo().getWithOffset(StOffset),
10487 false, false, NewAlign).getNode();
10491 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10492 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10493 /// narrowing the load and store if it would end up being a win for performance
10495 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10496 StoreSDNode *ST = cast<StoreSDNode>(N);
10497 if (ST->isVolatile())
10500 SDValue Chain = ST->getChain();
10501 SDValue Value = ST->getValue();
10502 SDValue Ptr = ST->getBasePtr();
10503 EVT VT = Value.getValueType();
10505 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10508 unsigned Opc = Value.getOpcode();
10510 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10511 // is a byte mask indicating a consecutive number of bytes, check to see if
10512 // Y is known to provide just those bytes. If so, we try to replace the
10513 // load + replace + store sequence with a single (narrower) store, which makes
10515 if (Opc == ISD::OR) {
10516 std::pair<unsigned, unsigned> MaskedLoad;
10517 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10518 if (MaskedLoad.first)
10519 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10520 Value.getOperand(1), ST,this))
10521 return SDValue(NewST, 0);
10523 // Or is commutative, so try swapping X and Y.
10524 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10525 if (MaskedLoad.first)
10526 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10527 Value.getOperand(0), ST,this))
10528 return SDValue(NewST, 0);
10531 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10532 Value.getOperand(1).getOpcode() != ISD::Constant)
10535 SDValue N0 = Value.getOperand(0);
10536 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10537 Chain == SDValue(N0.getNode(), 1)) {
10538 LoadSDNode *LD = cast<LoadSDNode>(N0);
10539 if (LD->getBasePtr() != Ptr ||
10540 LD->getPointerInfo().getAddrSpace() !=
10541 ST->getPointerInfo().getAddrSpace())
10544 // Find the type to narrow it the load / op / store to.
10545 SDValue N1 = Value.getOperand(1);
10546 unsigned BitWidth = N1.getValueSizeInBits();
10547 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10548 if (Opc == ISD::AND)
10549 Imm ^= APInt::getAllOnesValue(BitWidth);
10550 if (Imm == 0 || Imm.isAllOnesValue())
10552 unsigned ShAmt = Imm.countTrailingZeros();
10553 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10554 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10555 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10556 // The narrowing should be profitable, the load/store operation should be
10557 // legal (or custom) and the store size should be equal to the NewVT width.
10558 while (NewBW < BitWidth &&
10559 (NewVT.getStoreSizeInBits() != NewBW ||
10560 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10561 !TLI.isNarrowingProfitable(VT, NewVT))) {
10562 NewBW = NextPowerOf2(NewBW);
10563 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10565 if (NewBW >= BitWidth)
10568 // If the lsb changed does not start at the type bitwidth boundary,
10569 // start at the previous one.
10571 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10572 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10573 std::min(BitWidth, ShAmt + NewBW));
10574 if ((Imm & Mask) == Imm) {
10575 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10576 if (Opc == ISD::AND)
10577 NewImm ^= APInt::getAllOnesValue(NewBW);
10578 uint64_t PtrOff = ShAmt / 8;
10579 // For big endian targets, we need to adjust the offset to the pointer to
10580 // load the correct bytes.
10581 if (DAG.getDataLayout().isBigEndian())
10582 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10584 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10585 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10586 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10589 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10590 Ptr.getValueType(), Ptr,
10591 DAG.getConstant(PtrOff, SDLoc(LD),
10592 Ptr.getValueType()));
10593 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10594 LD->getChain(), NewPtr,
10595 LD->getPointerInfo().getWithOffset(PtrOff),
10596 LD->isVolatile(), LD->isNonTemporal(),
10597 LD->isInvariant(), NewAlign,
10599 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10600 DAG.getConstant(NewImm, SDLoc(Value),
10602 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10604 ST->getPointerInfo().getWithOffset(PtrOff),
10605 false, false, NewAlign);
10607 AddToWorklist(NewPtr.getNode());
10608 AddToWorklist(NewLD.getNode());
10609 AddToWorklist(NewVal.getNode());
10610 WorklistRemover DeadNodes(*this);
10611 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10620 /// For a given floating point load / store pair, if the load value isn't used
10621 /// by any other operations, then consider transforming the pair to integer
10622 /// load / store operations if the target deems the transformation profitable.
10623 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10624 StoreSDNode *ST = cast<StoreSDNode>(N);
10625 SDValue Chain = ST->getChain();
10626 SDValue Value = ST->getValue();
10627 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10628 Value.hasOneUse() &&
10629 Chain == SDValue(Value.getNode(), 1)) {
10630 LoadSDNode *LD = cast<LoadSDNode>(Value);
10631 EVT VT = LD->getMemoryVT();
10632 if (!VT.isFloatingPoint() ||
10633 VT != ST->getMemoryVT() ||
10634 LD->isNonTemporal() ||
10635 ST->isNonTemporal() ||
10636 LD->getPointerInfo().getAddrSpace() != 0 ||
10637 ST->getPointerInfo().getAddrSpace() != 0)
10640 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10641 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10642 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10643 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10644 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10647 unsigned LDAlign = LD->getAlignment();
10648 unsigned STAlign = ST->getAlignment();
10649 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10650 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10651 if (LDAlign < ABIAlign || STAlign < ABIAlign)
10654 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10655 LD->getChain(), LD->getBasePtr(),
10656 LD->getPointerInfo(),
10657 false, false, false, LDAlign);
10659 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10660 NewLD, ST->getBasePtr(),
10661 ST->getPointerInfo(),
10662 false, false, STAlign);
10664 AddToWorklist(NewLD.getNode());
10665 AddToWorklist(NewST.getNode());
10666 WorklistRemover DeadNodes(*this);
10667 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10676 /// Helper struct to parse and store a memory address as base + index + offset.
10677 /// We ignore sign extensions when it is safe to do so.
10678 /// The following two expressions are not equivalent. To differentiate we need
10679 /// to store whether there was a sign extension involved in the index
10681 /// (load (i64 add (i64 copyfromreg %c)
10682 /// (i64 signextend (add (i8 load %index)
10686 /// (load (i64 add (i64 copyfromreg %c)
10687 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
10689 struct BaseIndexOffset {
10693 bool IsIndexSignExt;
10695 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10697 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10698 bool IsIndexSignExt) :
10699 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10701 bool equalBaseIndex(const BaseIndexOffset &Other) {
10702 return Other.Base == Base && Other.Index == Index &&
10703 Other.IsIndexSignExt == IsIndexSignExt;
10706 /// Parses tree in Ptr for base, index, offset addresses.
10707 static BaseIndexOffset match(SDValue Ptr) {
10708 bool IsIndexSignExt = false;
10710 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10711 // instruction, then it could be just the BASE or everything else we don't
10712 // know how to handle. Just use Ptr as BASE and give up.
10713 if (Ptr->getOpcode() != ISD::ADD)
10714 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10716 // We know that we have at least an ADD instruction. Try to pattern match
10717 // the simple case of BASE + OFFSET.
10718 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10719 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10720 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10724 // Inside a loop the current BASE pointer is calculated using an ADD and a
10725 // MUL instruction. In this case Ptr is the actual BASE pointer.
10726 // (i64 add (i64 %array_ptr)
10727 // (i64 mul (i64 %induction_var)
10728 // (i64 %element_size)))
10729 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10730 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10732 // Look at Base + Index + Offset cases.
10733 SDValue Base = Ptr->getOperand(0);
10734 SDValue IndexOffset = Ptr->getOperand(1);
10736 // Skip signextends.
10737 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10738 IndexOffset = IndexOffset->getOperand(0);
10739 IsIndexSignExt = true;
10742 // Either the case of Base + Index (no offset) or something else.
10743 if (IndexOffset->getOpcode() != ISD::ADD)
10744 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10746 // Now we have the case of Base + Index + offset.
10747 SDValue Index = IndexOffset->getOperand(0);
10748 SDValue Offset = IndexOffset->getOperand(1);
10750 if (!isa<ConstantSDNode>(Offset))
10751 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10753 // Ignore signextends.
10754 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10755 Index = Index->getOperand(0);
10756 IsIndexSignExt = true;
10757 } else IsIndexSignExt = false;
10759 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10760 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10765 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10767 ArrayRef<MemOpLink> Stores,
10768 SmallVectorImpl<SDValue> &Chains,
10770 SmallVector<SDValue, 8> BuildVector;
10772 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
10773 StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
10774 Chains.push_back(St->getChain());
10775 BuildVector.push_back(St->getValue());
10778 return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10781 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10782 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10783 unsigned NumStores, bool IsConstantSrc, bool UseVector) {
10784 // Make sure we have something to merge.
10788 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10789 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10790 unsigned LatestNodeUsed = 0;
10792 for (unsigned i=0; i < NumStores; ++i) {
10793 // Find a chain for the new wide-store operand. Notice that some
10794 // of the store nodes that we found may not be selected for inclusion
10795 // in the wide store. The chain we use needs to be the chain of the
10796 // latest store node which is *used* and replaced by the wide store.
10797 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10798 LatestNodeUsed = i;
10801 SmallVector<SDValue, 8> Chains;
10803 // The latest Node in the DAG.
10804 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10805 SDLoc DL(StoreNodes[0].MemNode);
10809 bool IsVec = MemVT.isVector();
10810 unsigned Elts = NumStores;
10812 // When merging vector stores, get the total number of elements.
10813 Elts *= MemVT.getVectorNumElements();
10815 // Get the type for the merged vector store.
10816 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
10817 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10819 if (IsConstantSrc) {
10820 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
10822 SmallVector<SDValue, 8> Ops;
10823 for (unsigned i = 0; i < NumStores; ++i) {
10824 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10825 SDValue Val = St->getValue();
10826 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
10827 if (Val.getValueType() != MemVT)
10829 Ops.push_back(Val);
10830 Chains.push_back(St->getChain());
10833 // Build the extracted vector elements back into a vector.
10834 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
10837 // We should always use a vector store when merging extracted vector
10838 // elements, so this path implies a store of constants.
10839 assert(IsConstantSrc && "Merged vector elements should use vector store");
10841 unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
10842 APInt StoreInt(SizeInBits, 0);
10844 // Construct a single integer constant which is made of the smaller
10845 // constant inputs.
10846 bool IsLE = DAG.getDataLayout().isLittleEndian();
10847 for (unsigned i = 0; i < NumStores; ++i) {
10848 unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
10849 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10850 Chains.push_back(St->getChain());
10852 SDValue Val = St->getValue();
10853 StoreInt <<= ElementSizeBytes * 8;
10854 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10855 StoreInt |= C->getAPIntValue().zext(SizeInBits);
10856 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10857 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
10859 llvm_unreachable("Invalid constant element type");
10863 // Create the new Load and Store operations.
10864 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
10865 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10868 assert(!Chains.empty());
10870 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
10871 SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
10872 FirstInChain->getBasePtr(),
10873 FirstInChain->getPointerInfo(),
10875 FirstInChain->getAlignment());
10877 // Replace the last store with the new store
10878 CombineTo(LatestOp, NewStore);
10879 // Erase all other stores.
10880 for (unsigned i = 0; i < NumStores; ++i) {
10881 if (StoreNodes[i].MemNode == LatestOp)
10883 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10884 // ReplaceAllUsesWith will replace all uses that existed when it was
10885 // called, but graph optimizations may cause new ones to appear. For
10886 // example, the case in pr14333 looks like
10888 // St's chain -> St -> another store -> X
10890 // And the only difference from St to the other store is the chain.
10891 // When we change it's chain to be St's chain they become identical,
10892 // get CSEed and the net result is that X is now a use of St.
10893 // Since we know that St is redundant, just iterate.
10894 while (!St->use_empty())
10895 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10896 deleteAndRecombine(St);
10902 void DAGCombiner::getStoreMergeAndAliasCandidates(
10903 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
10904 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
10905 // This holds the base pointer, index, and the offset in bytes from the base
10907 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10909 // We must have a base and an offset.
10910 if (!BasePtr.Base.getNode())
10913 // Do not handle stores to undef base pointers.
10914 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10917 // Walk up the chain and look for nodes with offsets from the same
10918 // base pointer. Stop when reaching an instruction with a different kind
10919 // or instruction which has a different base pointer.
10920 EVT MemVT = St->getMemoryVT();
10922 StoreSDNode *Index = St;
10925 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10926 : DAG.getSubtarget().useAA();
10929 // Look at other users of the same chain. Stores on the same chain do not
10930 // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
10931 // to be on the same chain, so don't bother looking at adjacent chains.
10933 SDValue Chain = St->getChain();
10934 for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
10935 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
10936 if (I.getOperandNo() != 0)
10939 if (OtherST->isVolatile() || OtherST->isIndexed())
10942 if (OtherST->getMemoryVT() != MemVT)
10945 BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr());
10947 if (Ptr.equalBaseIndex(BasePtr))
10948 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
10956 // If the chain has more than one use, then we can't reorder the mem ops.
10957 if (Index != St && !SDValue(Index, 0)->hasOneUse())
10960 // Find the base pointer and offset for this memory node.
10961 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10963 // Check that the base pointer is the same as the original one.
10964 if (!Ptr.equalBaseIndex(BasePtr))
10967 // The memory operands must not be volatile.
10968 if (Index->isVolatile() || Index->isIndexed())
10972 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10973 if (St->isTruncatingStore())
10976 // The stored memory type must be the same.
10977 if (Index->getMemoryVT() != MemVT)
10980 // We found a potential memory operand to merge.
10981 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10983 // Find the next memory operand in the chain. If the next operand in the
10984 // chain is a store then move up and continue the scan with the next
10985 // memory operand. If the next operand is a load save it and use alias
10986 // information to check if it interferes with anything.
10987 SDNode *NextInChain = Index->getChain().getNode();
10989 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10990 // We found a store node. Use it for the next iteration.
10993 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10994 if (Ldn->isVolatile()) {
10999 // Save the load node for later. Continue the scan.
11000 AliasLoadNodes.push_back(Ldn);
11001 NextInChain = Ldn->getChain().getNode();
11011 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
11012 if (OptLevel == CodeGenOpt::None)
11015 EVT MemVT = St->getMemoryVT();
11016 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11017 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11018 Attribute::NoImplicitFloat);
11020 // This function cannot currently deal with non-byte-sized memory sizes.
11021 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11024 if (!MemVT.isSimple())
11027 // Perform an early exit check. Do not bother looking at stored values that
11028 // are not constants, loads, or extracted vector elements.
11029 SDValue StoredVal = St->getValue();
11030 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11031 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11032 isa<ConstantFPSDNode>(StoredVal);
11033 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11034 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11036 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11039 // Don't merge vectors into wider vectors if the source data comes from loads.
11040 // TODO: This restriction can be lifted by using logic similar to the
11041 // ExtractVecSrc case.
11042 if (MemVT.isVector() && IsLoadSrc)
11045 // Only look at ends of store sequences.
11046 SDValue Chain = SDValue(St, 0);
11047 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11050 // Save the LoadSDNodes that we find in the chain.
11051 // We need to make sure that these nodes do not interfere with
11052 // any of the store nodes.
11053 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11055 // Save the StoreSDNodes that we find in the chain.
11056 SmallVector<MemOpLink, 8> StoreNodes;
11058 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11060 // Check if there is anything to merge.
11061 if (StoreNodes.size() < 2)
11064 // Sort the memory operands according to their distance from the base pointer.
11065 std::sort(StoreNodes.begin(), StoreNodes.end(),
11066 [](MemOpLink LHS, MemOpLink RHS) {
11067 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11068 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11069 LHS.SequenceNum > RHS.SequenceNum);
11072 // Scan the memory operations on the chain and find the first non-consecutive
11073 // store memory address.
11074 unsigned LastConsecutiveStore = 0;
11075 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11076 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11078 // Check that the addresses are consecutive starting from the second
11079 // element in the list of stores.
11081 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11082 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11086 bool Alias = false;
11087 // Check if this store interferes with any of the loads that we found.
11088 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
11089 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
11093 // We found a load that alias with this store. Stop the sequence.
11097 // Mark this node as useful.
11098 LastConsecutiveStore = i;
11101 // The node with the lowest store address.
11102 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11103 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11104 unsigned FirstStoreAlign = FirstInChain->getAlignment();
11105 LLVMContext &Context = *DAG.getContext();
11106 const DataLayout &DL = DAG.getDataLayout();
11108 // Store the constants into memory as one consecutive store.
11109 if (IsConstantSrc) {
11110 unsigned LastLegalType = 0;
11111 unsigned LastLegalVectorType = 0;
11112 bool NonZero = false;
11113 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11114 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11115 SDValue StoredVal = St->getValue();
11117 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11118 NonZero |= !C->isNullValue();
11119 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11120 NonZero |= !C->getConstantFPValue()->isNullValue();
11126 // Find a legal type for the constant store.
11127 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11128 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11130 if (TLI.isTypeLegal(StoreTy) &&
11131 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11132 FirstStoreAlign, &IsFast) && IsFast) {
11133 LastLegalType = i+1;
11134 // Or check whether a truncstore is legal.
11135 } else if (TLI.getTypeAction(Context, StoreTy) ==
11136 TargetLowering::TypePromoteInteger) {
11137 EVT LegalizedStoredValueTy =
11138 TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11139 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11140 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11141 FirstStoreAS, FirstStoreAlign, &IsFast) &&
11143 LastLegalType = i + 1;
11147 // We only use vectors if the constant is known to be zero or the target
11148 // allows it and the function is not marked with the noimplicitfloat
11150 if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11153 // Find a legal type for the vector store.
11154 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11155 if (TLI.isTypeLegal(Ty) &&
11156 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11157 FirstStoreAlign, &IsFast) && IsFast)
11158 LastLegalVectorType = i + 1;
11162 // Check if we found a legal integer type to store.
11163 if (LastLegalType == 0 && LastLegalVectorType == 0)
11166 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11167 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11169 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11173 // When extracting multiple vector elements, try to store them
11174 // in one vector store rather than a sequence of scalar stores.
11175 if (IsExtractVecSrc) {
11176 unsigned NumStoresToMerge = 0;
11177 bool IsVec = MemVT.isVector();
11178 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11179 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11180 unsigned StoreValOpcode = St->getValue().getOpcode();
11181 // This restriction could be loosened.
11182 // Bail out if any stored values are not elements extracted from a vector.
11183 // It should be possible to handle mixed sources, but load sources need
11184 // more careful handling (see the block of code below that handles
11185 // consecutive loads).
11186 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11187 StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11190 // Find a legal type for the vector store.
11191 unsigned Elts = i + 1;
11193 // When merging vector stores, get the total number of elements.
11194 Elts *= MemVT.getVectorNumElements();
11196 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11198 if (TLI.isTypeLegal(Ty) &&
11199 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11200 FirstStoreAlign, &IsFast) && IsFast)
11201 NumStoresToMerge = i + 1;
11204 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11208 // Below we handle the case of multiple consecutive stores that
11209 // come from multiple consecutive loads. We merge them into a single
11210 // wide load and a single wide store.
11212 // Look for load nodes which are used by the stored values.
11213 SmallVector<MemOpLink, 8> LoadNodes;
11215 // Find acceptable loads. Loads need to have the same chain (token factor),
11216 // must not be zext, volatile, indexed, and they must be consecutive.
11217 BaseIndexOffset LdBasePtr;
11218 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11219 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11220 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11223 // Loads must only have one use.
11224 if (!Ld->hasNUsesOfValue(1, 0))
11227 // The memory operands must not be volatile.
11228 if (Ld->isVolatile() || Ld->isIndexed())
11231 // We do not accept ext loads.
11232 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11235 // The stored memory type must be the same.
11236 if (Ld->getMemoryVT() != MemVT)
11239 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11240 // If this is not the first ptr that we check.
11241 if (LdBasePtr.Base.getNode()) {
11242 // The base ptr must be the same.
11243 if (!LdPtr.equalBaseIndex(LdBasePtr))
11246 // Check that all other base pointers are the same as this one.
11250 // We found a potential memory operand to merge.
11251 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11254 if (LoadNodes.size() < 2)
11257 // If we have load/store pair instructions and we only have two values,
11259 unsigned RequiredAlignment;
11260 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11261 St->getAlignment() >= RequiredAlignment)
11264 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11265 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11266 unsigned FirstLoadAlign = FirstLoad->getAlignment();
11268 // Scan the memory operations on the chain and find the first non-consecutive
11269 // load memory address. These variables hold the index in the store node
11271 unsigned LastConsecutiveLoad = 0;
11272 // This variable refers to the size and not index in the array.
11273 unsigned LastLegalVectorType = 0;
11274 unsigned LastLegalIntegerType = 0;
11275 StartAddress = LoadNodes[0].OffsetFromBase;
11276 SDValue FirstChain = FirstLoad->getChain();
11277 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11278 // All loads much share the same chain.
11279 if (LoadNodes[i].MemNode->getChain() != FirstChain)
11282 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11283 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11285 LastConsecutiveLoad = i;
11286 // Find a legal type for the vector store.
11287 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11288 bool IsFastSt, IsFastLd;
11289 if (TLI.isTypeLegal(StoreTy) &&
11290 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11291 FirstStoreAlign, &IsFastSt) && IsFastSt &&
11292 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11293 FirstLoadAlign, &IsFastLd) && IsFastLd) {
11294 LastLegalVectorType = i + 1;
11297 // Find a legal type for the integer store.
11298 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11299 StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11300 if (TLI.isTypeLegal(StoreTy) &&
11301 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11302 FirstStoreAlign, &IsFastSt) && IsFastSt &&
11303 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11304 FirstLoadAlign, &IsFastLd) && IsFastLd)
11305 LastLegalIntegerType = i + 1;
11306 // Or check whether a truncstore and extload is legal.
11307 else if (TLI.getTypeAction(Context, StoreTy) ==
11308 TargetLowering::TypePromoteInteger) {
11309 EVT LegalizedStoredValueTy =
11310 TLI.getTypeToTransformTo(Context, StoreTy);
11311 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11312 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11313 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11314 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11315 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11316 FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11318 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11319 FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11321 LastLegalIntegerType = i+1;
11325 // Only use vector types if the vector type is larger than the integer type.
11326 // If they are the same, use integers.
11327 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11328 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11330 // We add +1 here because the LastXXX variables refer to location while
11331 // the NumElem refers to array/index size.
11332 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11333 NumElem = std::min(LastLegalType, NumElem);
11338 // Collect the chains from all merged stores.
11339 SmallVector<SDValue, 8> MergeStoreChains;
11340 MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
11342 // The latest Node in the DAG.
11343 unsigned LatestNodeUsed = 0;
11344 for (unsigned i=1; i<NumElem; ++i) {
11345 // Find a chain for the new wide-store operand. Notice that some
11346 // of the store nodes that we found may not be selected for inclusion
11347 // in the wide store. The chain we use needs to be the chain of the
11348 // latest store node which is *used* and replaced by the wide store.
11349 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11350 LatestNodeUsed = i;
11352 MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
11355 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11357 // Find if it is better to use vectors or integers to load and store
11361 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11363 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11364 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11367 SDLoc LoadDL(LoadNodes[0].MemNode);
11368 SDLoc StoreDL(StoreNodes[0].MemNode);
11370 // The merged loads are required to have the same chain, so using the first's
11371 // chain is acceptable.
11372 SDValue NewLoad = DAG.getLoad(
11373 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11374 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11376 SDValue NewStoreChain =
11377 DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
11379 SDValue NewStore = DAG.getStore(
11380 NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
11381 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11383 // Replace one of the loads with the new load.
11384 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11385 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11386 SDValue(NewLoad.getNode(), 1));
11388 // Remove the rest of the load chains.
11389 for (unsigned i = 1; i < NumElem ; ++i) {
11390 // Replace all chain users of the old load nodes with the chain of the new
11392 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11393 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11396 // Replace the last store with the new store.
11397 CombineTo(LatestOp, NewStore);
11398 // Erase all other stores.
11399 for (unsigned i = 0; i < NumElem ; ++i) {
11400 // Remove all Store nodes.
11401 if (StoreNodes[i].MemNode == LatestOp)
11403 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11404 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11405 deleteAndRecombine(St);
11411 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11415 // Replace the chain to avoid dependency.
11416 if (ST->isTruncatingStore()) {
11417 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11418 ST->getBasePtr(), ST->getMemoryVT(),
11419 ST->getMemOperand());
11421 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11422 ST->getMemOperand());
11425 // Create token to keep both nodes around.
11426 SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11427 MVT::Other, ST->getChain(), ReplStore);
11429 // Make sure the new and old chains are cleaned up.
11430 AddToWorklist(Token.getNode());
11432 // Don't add users to work list.
11433 return CombineTo(ST, Token, false);
11436 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
11437 SDValue Value = ST->getValue();
11438 if (Value.getOpcode() == ISD::TargetConstantFP)
11443 SDValue Chain = ST->getChain();
11444 SDValue Ptr = ST->getBasePtr();
11446 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
11448 // NOTE: If the original store is volatile, this transform must not increase
11449 // the number of stores. For example, on x86-32 an f64 can be stored in one
11450 // processor operation but an i64 (which is not legal) requires two. So the
11451 // transform should not be done in this case.
11454 switch (CFP->getSimpleValueType(0).SimpleTy) {
11456 llvm_unreachable("Unknown FP type");
11457 case MVT::f16: // We don't do this for these yet.
11463 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11464 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11466 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11467 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11469 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
11474 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11475 !ST->isVolatile()) ||
11476 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11478 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11479 getZExtValue(), SDLoc(CFP), MVT::i64);
11480 return DAG.getStore(Chain, DL, Tmp,
11481 Ptr, ST->getMemOperand());
11484 if (!ST->isVolatile() &&
11485 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11486 // Many FP stores are not made apparent until after legalize, e.g. for
11487 // argument passing. Since this is so common, custom legalize the
11488 // 64-bit integer store into two 32-bit stores.
11489 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11490 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11491 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11492 if (DAG.getDataLayout().isBigEndian())
11495 unsigned Alignment = ST->getAlignment();
11496 bool isVolatile = ST->isVolatile();
11497 bool isNonTemporal = ST->isNonTemporal();
11498 AAMDNodes AAInfo = ST->getAAInfo();
11500 SDValue St0 = DAG.getStore(Chain, DL, Lo,
11501 Ptr, ST->getPointerInfo(),
11502 isVolatile, isNonTemporal,
11503 ST->getAlignment(), AAInfo);
11504 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11505 DAG.getConstant(4, DL, Ptr.getValueType()));
11506 Alignment = MinAlign(Alignment, 4U);
11507 SDValue St1 = DAG.getStore(Chain, DL, Hi,
11508 Ptr, ST->getPointerInfo().getWithOffset(4),
11509 isVolatile, isNonTemporal,
11510 Alignment, AAInfo);
11511 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11519 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11520 StoreSDNode *ST = cast<StoreSDNode>(N);
11521 SDValue Chain = ST->getChain();
11522 SDValue Value = ST->getValue();
11523 SDValue Ptr = ST->getBasePtr();
11525 // If this is a store of a bit convert, store the input value if the
11526 // resultant store does not need a higher alignment than the original.
11527 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11528 ST->isUnindexed()) {
11529 unsigned OrigAlign = ST->getAlignment();
11530 EVT SVT = Value.getOperand(0).getValueType();
11531 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11532 SVT.getTypeForEVT(*DAG.getContext()));
11533 if (Align <= OrigAlign &&
11534 ((!LegalOperations && !ST->isVolatile()) ||
11535 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11536 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11537 Ptr, ST->getPointerInfo(), ST->isVolatile(),
11538 ST->isNonTemporal(), OrigAlign,
11542 // Turn 'store undef, Ptr' -> nothing.
11543 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11546 // Try to infer better alignment information than the store already has.
11547 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11548 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11549 if (Align > ST->getAlignment()) {
11551 DAG.getTruncStore(Chain, SDLoc(N), Value,
11552 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11553 ST->isVolatile(), ST->isNonTemporal(), Align,
11555 if (NewStore.getNode() != N)
11556 return CombineTo(ST, NewStore, true);
11561 // Try transforming a pair floating point load / store ops to integer
11562 // load / store ops.
11563 if (SDValue NewST = TransformFPLoadStorePair(N))
11566 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11567 : DAG.getSubtarget().useAA();
11569 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11570 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11573 if (UseAA && ST->isUnindexed()) {
11574 // FIXME: We should do this even without AA enabled. AA will just allow
11575 // FindBetterChain to work in more situations. The problem with this is that
11576 // any combine that expects memory operations to be on consecutive chains
11577 // first needs to be updated to look for users of the same chain.
11579 // Walk up chain skipping non-aliasing memory nodes, on this store and any
11580 // adjacent stores.
11581 if (findBetterNeighborChains(ST)) {
11582 // replaceStoreChain uses CombineTo, which handled all of the worklist
11583 // manipulation. Return the original node to not do anything else.
11584 return SDValue(ST, 0);
11588 // Try transforming N to an indexed store.
11589 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11590 return SDValue(N, 0);
11592 // FIXME: is there such a thing as a truncating indexed store?
11593 if (ST->isTruncatingStore() && ST->isUnindexed() &&
11594 Value.getValueType().isInteger()) {
11595 // See if we can simplify the input to this truncstore with knowledge that
11596 // only the low bits are being used. For example:
11597 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
11599 GetDemandedBits(Value,
11600 APInt::getLowBitsSet(
11601 Value.getValueType().getScalarType().getSizeInBits(),
11602 ST->getMemoryVT().getScalarType().getSizeInBits()));
11603 AddToWorklist(Value.getNode());
11604 if (Shorter.getNode())
11605 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11606 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11608 // Otherwise, see if we can simplify the operation with
11609 // SimplifyDemandedBits, which only works if the value has a single use.
11610 if (SimplifyDemandedBits(Value,
11611 APInt::getLowBitsSet(
11612 Value.getValueType().getScalarType().getSizeInBits(),
11613 ST->getMemoryVT().getScalarType().getSizeInBits())))
11614 return SDValue(N, 0);
11617 // If this is a load followed by a store to the same location, then the store
11619 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11620 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11621 ST->isUnindexed() && !ST->isVolatile() &&
11622 // There can't be any side effects between the load and store, such as
11623 // a call or store.
11624 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11625 // The store is dead, remove it.
11630 // If this is a store followed by a store with the same value to the same
11631 // location, then the store is dead/noop.
11632 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11633 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11634 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11635 ST1->isUnindexed() && !ST1->isVolatile()) {
11636 // The store is dead, remove it.
11641 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11642 // truncating store. We can do this even if this is already a truncstore.
11643 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11644 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11645 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11646 ST->getMemoryVT())) {
11647 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11648 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11651 // Only perform this optimization before the types are legal, because we
11652 // don't want to perform this optimization on every DAGCombine invocation.
11654 bool EverChanged = false;
11657 // There can be multiple store sequences on the same chain.
11658 // Keep trying to merge store sequences until we are unable to do so
11659 // or until we merge the last store on the chain.
11660 bool Changed = MergeConsecutiveStores(ST);
11661 EverChanged |= Changed;
11662 if (!Changed) break;
11663 } while (ST->getOpcode() != ISD::DELETED_NODE);
11666 return SDValue(N, 0);
11669 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11671 // Make sure to do this only after attempting to merge stores in order to
11672 // avoid changing the types of some subset of stores due to visit order,
11673 // preventing their merging.
11674 if (isa<ConstantFPSDNode>(Value)) {
11675 if (SDValue NewSt = replaceStoreOfFPConstant(ST))
11679 return ReduceLoadOpStoreWidth(N);
11682 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11683 SDValue InVec = N->getOperand(0);
11684 SDValue InVal = N->getOperand(1);
11685 SDValue EltNo = N->getOperand(2);
11688 // If the inserted element is an UNDEF, just use the input vector.
11689 if (InVal.getOpcode() == ISD::UNDEF)
11692 EVT VT = InVec.getValueType();
11694 // If we can't generate a legal BUILD_VECTOR, exit
11695 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11698 // Check that we know which element is being inserted
11699 if (!isa<ConstantSDNode>(EltNo))
11701 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11703 // Canonicalize insert_vector_elt dag nodes.
11705 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11706 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11708 // Do this only if the child insert_vector node has one use; also
11709 // do this only if indices are both constants and Idx1 < Idx0.
11710 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11711 && isa<ConstantSDNode>(InVec.getOperand(2))) {
11712 unsigned OtherElt =
11713 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11714 if (Elt < OtherElt) {
11716 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11717 InVec.getOperand(0), InVal, EltNo);
11718 AddToWorklist(NewOp.getNode());
11719 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11720 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11724 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11725 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
11726 // vector elements.
11727 SmallVector<SDValue, 8> Ops;
11728 // Do not combine these two vectors if the output vector will not replace
11729 // the input vector.
11730 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11731 Ops.append(InVec.getNode()->op_begin(),
11732 InVec.getNode()->op_end());
11733 } else if (InVec.getOpcode() == ISD::UNDEF) {
11734 unsigned NElts = VT.getVectorNumElements();
11735 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11740 // Insert the element
11741 if (Elt < Ops.size()) {
11742 // All the operands of BUILD_VECTOR must have the same type;
11743 // we enforce that here.
11744 EVT OpVT = Ops[0].getValueType();
11745 if (InVal.getValueType() != OpVT)
11746 InVal = OpVT.bitsGT(InVal.getValueType()) ?
11747 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11748 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11752 // Return the new vector
11753 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11756 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11757 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11758 EVT ResultVT = EVE->getValueType(0);
11759 EVT VecEltVT = InVecVT.getVectorElementType();
11760 unsigned Align = OriginalLoad->getAlignment();
11761 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
11762 VecEltVT.getTypeForEVT(*DAG.getContext()));
11764 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11769 SDValue NewPtr = OriginalLoad->getBasePtr();
11771 EVT PtrType = NewPtr.getValueType();
11772 MachinePointerInfo MPI;
11774 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11775 int Elt = ConstEltNo->getZExtValue();
11776 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11777 Offset = DAG.getConstant(PtrOff, DL, PtrType);
11778 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11780 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11781 Offset = DAG.getNode(
11782 ISD::MUL, DL, PtrType, Offset,
11783 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11784 MPI = OriginalLoad->getPointerInfo();
11786 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11788 // The replacement we need to do here is a little tricky: we need to
11789 // replace an extractelement of a load with a load.
11790 // Use ReplaceAllUsesOfValuesWith to do the replacement.
11791 // Note that this replacement assumes that the extractvalue is the only
11792 // use of the load; that's okay because we don't want to perform this
11793 // transformation in other cases anyway.
11796 if (ResultVT.bitsGT(VecEltVT)) {
11797 // If the result type of vextract is wider than the load, then issue an
11798 // extending load instead.
11799 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11803 Load = DAG.getExtLoad(
11804 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11805 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11806 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11807 Chain = Load.getValue(1);
11809 Load = DAG.getLoad(
11810 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11811 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11812 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11813 Chain = Load.getValue(1);
11814 if (ResultVT.bitsLT(VecEltVT))
11815 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11817 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11819 WorklistRemover DeadNodes(*this);
11820 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11821 SDValue To[] = { Load, Chain };
11822 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11823 // Since we're explicitly calling ReplaceAllUses, add the new node to the
11824 // worklist explicitly as well.
11825 AddToWorklist(Load.getNode());
11826 AddUsersToWorklist(Load.getNode()); // Add users too
11827 // Make sure to revisit this node to clean it up; it will usually be dead.
11828 AddToWorklist(EVE);
11830 return SDValue(EVE, 0);
11833 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11834 // (vextract (scalar_to_vector val, 0) -> val
11835 SDValue InVec = N->getOperand(0);
11836 EVT VT = InVec.getValueType();
11837 EVT NVT = N->getValueType(0);
11839 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11840 // Check if the result type doesn't match the inserted element type. A
11841 // SCALAR_TO_VECTOR may truncate the inserted element and the
11842 // EXTRACT_VECTOR_ELT may widen the extracted vector.
11843 SDValue InOp = InVec.getOperand(0);
11844 if (InOp.getValueType() != NVT) {
11845 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11846 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11851 SDValue EltNo = N->getOperand(1);
11852 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
11854 // extract_vector_elt (build_vector x, y), 1 -> y
11856 InVec.getOpcode() == ISD::BUILD_VECTOR &&
11857 TLI.isTypeLegal(VT) &&
11858 (InVec.hasOneUse() ||
11859 TLI.aggressivelyPreferBuildVectorSources(VT))) {
11860 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
11861 EVT InEltVT = Elt.getValueType();
11863 // Sometimes build_vector's scalar input types do not match result type.
11864 if (NVT == InEltVT)
11867 // TODO: It may be useful to truncate if free if the build_vector implicitly
11871 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11872 // We only perform this optimization before the op legalization phase because
11873 // we may introduce new vector instructions which are not backed by TD
11874 // patterns. For example on AVX, extracting elements from a wide vector
11875 // without using extract_subvector. However, if we can find an underlying
11876 // scalar value, then we can always use that.
11877 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
11878 int NumElem = VT.getVectorNumElements();
11879 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11880 // Find the new index to extract from.
11881 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
11883 // Extracting an undef index is undef.
11885 return DAG.getUNDEF(NVT);
11887 // Select the right vector half to extract from.
11889 if (OrigElt < NumElem) {
11890 SVInVec = InVec->getOperand(0);
11892 SVInVec = InVec->getOperand(1);
11893 OrigElt -= NumElem;
11896 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11897 SDValue InOp = SVInVec.getOperand(OrigElt);
11898 if (InOp.getValueType() != NVT) {
11899 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11900 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11906 // FIXME: We should handle recursing on other vector shuffles and
11907 // scalar_to_vector here as well.
11909 if (!LegalOperations) {
11910 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
11911 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11912 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11916 bool BCNumEltsChanged = false;
11917 EVT ExtVT = VT.getVectorElementType();
11920 // If the result of load has to be truncated, then it's not necessarily
11922 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11925 if (InVec.getOpcode() == ISD::BITCAST) {
11926 // Don't duplicate a load with other uses.
11927 if (!InVec.hasOneUse())
11930 EVT BCVT = InVec.getOperand(0).getValueType();
11931 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11933 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11934 BCNumEltsChanged = true;
11935 InVec = InVec.getOperand(0);
11936 ExtVT = BCVT.getVectorElementType();
11939 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11940 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11941 ISD::isNormalLoad(InVec.getNode()) &&
11942 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11943 SDValue Index = N->getOperand(1);
11944 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11945 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11949 // Perform only after legalization to ensure build_vector / vector_shuffle
11950 // optimizations have already been done.
11951 if (!LegalOperations) return SDValue();
11953 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11954 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11955 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11958 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11960 LoadSDNode *LN0 = nullptr;
11961 const ShuffleVectorSDNode *SVN = nullptr;
11962 if (ISD::isNormalLoad(InVec.getNode())) {
11963 LN0 = cast<LoadSDNode>(InVec);
11964 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11965 InVec.getOperand(0).getValueType() == ExtVT &&
11966 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11967 // Don't duplicate a load with other uses.
11968 if (!InVec.hasOneUse())
11971 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11972 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11973 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11975 // (load $addr+1*size)
11977 // Don't duplicate a load with other uses.
11978 if (!InVec.hasOneUse())
11981 // If the bit convert changed the number of elements, it is unsafe
11982 // to examine the mask.
11983 if (BCNumEltsChanged)
11986 // Select the input vector, guarding against out of range extract vector.
11987 unsigned NumElems = VT.getVectorNumElements();
11988 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11989 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11991 if (InVec.getOpcode() == ISD::BITCAST) {
11992 // Don't duplicate a load with other uses.
11993 if (!InVec.hasOneUse())
11996 InVec = InVec.getOperand(0);
11998 if (ISD::isNormalLoad(InVec.getNode())) {
11999 LN0 = cast<LoadSDNode>(InVec);
12000 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12001 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12005 // Make sure we found a non-volatile load and the extractelement is
12007 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12010 // If Idx was -1 above, Elt is going to be -1, so just return undef.
12012 return DAG.getUNDEF(LVT);
12014 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12020 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12021 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12022 // We perform this optimization post type-legalization because
12023 // the type-legalizer often scalarizes integer-promoted vectors.
12024 // Performing this optimization before may create bit-casts which
12025 // will be type-legalized to complex code sequences.
12026 // We perform this optimization only before the operation legalizer because we
12027 // may introduce illegal operations.
12028 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12031 unsigned NumInScalars = N->getNumOperands();
12033 EVT VT = N->getValueType(0);
12035 // Check to see if this is a BUILD_VECTOR of a bunch of values
12036 // which come from any_extend or zero_extend nodes. If so, we can create
12037 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12038 // optimizations. We do not handle sign-extend because we can't fill the sign
12040 EVT SourceType = MVT::Other;
12041 bool AllAnyExt = true;
12043 for (unsigned i = 0; i != NumInScalars; ++i) {
12044 SDValue In = N->getOperand(i);
12045 // Ignore undef inputs.
12046 if (In.getOpcode() == ISD::UNDEF) continue;
12048 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
12049 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12051 // Abort if the element is not an extension.
12052 if (!ZeroExt && !AnyExt) {
12053 SourceType = MVT::Other;
12057 // The input is a ZeroExt or AnyExt. Check the original type.
12058 EVT InTy = In.getOperand(0).getValueType();
12060 // Check that all of the widened source types are the same.
12061 if (SourceType == MVT::Other)
12064 else if (InTy != SourceType) {
12065 // Multiple income types. Abort.
12066 SourceType = MVT::Other;
12070 // Check if all of the extends are ANY_EXTENDs.
12071 AllAnyExt &= AnyExt;
12074 // In order to have valid types, all of the inputs must be extended from the
12075 // same source type and all of the inputs must be any or zero extend.
12076 // Scalar sizes must be a power of two.
12077 EVT OutScalarTy = VT.getScalarType();
12078 bool ValidTypes = SourceType != MVT::Other &&
12079 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12080 isPowerOf2_32(SourceType.getSizeInBits());
12082 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12083 // turn into a single shuffle instruction.
12087 bool isLE = DAG.getDataLayout().isLittleEndian();
12088 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12089 assert(ElemRatio > 1 && "Invalid element size ratio");
12090 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12091 DAG.getConstant(0, SDLoc(N), SourceType);
12093 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12094 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12096 // Populate the new build_vector
12097 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12098 SDValue Cast = N->getOperand(i);
12099 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12100 Cast.getOpcode() == ISD::ZERO_EXTEND ||
12101 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
12103 if (Cast.getOpcode() == ISD::UNDEF)
12104 In = DAG.getUNDEF(SourceType);
12106 In = Cast->getOperand(0);
12107 unsigned Index = isLE ? (i * ElemRatio) :
12108 (i * ElemRatio + (ElemRatio - 1));
12110 assert(Index < Ops.size() && "Invalid index");
12114 // The type of the new BUILD_VECTOR node.
12115 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12116 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12117 "Invalid vector size");
12118 // Check if the new vector type is legal.
12119 if (!isTypeLegal(VecVT)) return SDValue();
12121 // Make the new BUILD_VECTOR.
12122 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
12124 // The new BUILD_VECTOR node has the potential to be further optimized.
12125 AddToWorklist(BV.getNode());
12126 // Bitcast to the desired type.
12127 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12130 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12131 EVT VT = N->getValueType(0);
12133 unsigned NumInScalars = N->getNumOperands();
12136 EVT SrcVT = MVT::Other;
12137 unsigned Opcode = ISD::DELETED_NODE;
12138 unsigned NumDefs = 0;
12140 for (unsigned i = 0; i != NumInScalars; ++i) {
12141 SDValue In = N->getOperand(i);
12142 unsigned Opc = In.getOpcode();
12144 if (Opc == ISD::UNDEF)
12147 // If all scalar values are floats and converted from integers.
12148 if (Opcode == ISD::DELETED_NODE &&
12149 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12156 EVT InVT = In.getOperand(0).getValueType();
12158 // If all scalar values are typed differently, bail out. It's chosen to
12159 // simplify BUILD_VECTOR of integer types.
12160 if (SrcVT == MVT::Other)
12167 // If the vector has just one element defined, it's not worth to fold it into
12168 // a vectorized one.
12172 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12173 && "Should only handle conversion from integer to float.");
12174 assert(SrcVT != MVT::Other && "Cannot determine source type!");
12176 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12178 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12181 // Just because the floating-point vector type is legal does not necessarily
12182 // mean that the corresponding integer vector type is.
12183 if (!isTypeLegal(NVT))
12186 SmallVector<SDValue, 8> Opnds;
12187 for (unsigned i = 0; i != NumInScalars; ++i) {
12188 SDValue In = N->getOperand(i);
12190 if (In.getOpcode() == ISD::UNDEF)
12191 Opnds.push_back(DAG.getUNDEF(SrcVT));
12193 Opnds.push_back(In.getOperand(0));
12195 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
12196 AddToWorklist(BV.getNode());
12198 return DAG.getNode(Opcode, dl, VT, BV);
12201 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12202 unsigned NumInScalars = N->getNumOperands();
12204 EVT VT = N->getValueType(0);
12206 // A vector built entirely of undefs is undef.
12207 if (ISD::allOperandsUndef(N))
12208 return DAG.getUNDEF(VT);
12210 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12213 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12216 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12217 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12218 // at most two distinct vectors, turn this into a shuffle node.
12220 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12221 if (!isTypeLegal(VT))
12224 // May only combine to shuffle after legalize if shuffle is legal.
12225 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12228 SDValue VecIn1, VecIn2;
12229 bool UsesZeroVector = false;
12230 for (unsigned i = 0; i != NumInScalars; ++i) {
12231 SDValue Op = N->getOperand(i);
12232 // Ignore undef inputs.
12233 if (Op.getOpcode() == ISD::UNDEF) continue;
12235 // See if we can combine this build_vector into a blend with a zero vector.
12236 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12237 UsesZeroVector = true;
12241 // If this input is something other than a EXTRACT_VECTOR_ELT with a
12242 // constant index, bail out.
12243 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12244 !isa<ConstantSDNode>(Op.getOperand(1))) {
12245 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12249 // We allow up to two distinct input vectors.
12250 SDValue ExtractedFromVec = Op.getOperand(0);
12251 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12254 if (!VecIn1.getNode()) {
12255 VecIn1 = ExtractedFromVec;
12256 } else if (!VecIn2.getNode() && !UsesZeroVector) {
12257 VecIn2 = ExtractedFromVec;
12259 // Too many inputs.
12260 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12265 // If everything is good, we can make a shuffle operation.
12266 if (VecIn1.getNode()) {
12267 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12268 SmallVector<int, 8> Mask;
12269 for (unsigned i = 0; i != NumInScalars; ++i) {
12270 unsigned Opcode = N->getOperand(i).getOpcode();
12271 if (Opcode == ISD::UNDEF) {
12272 Mask.push_back(-1);
12276 // Operands can also be zero.
12277 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12278 assert(UsesZeroVector &&
12279 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12280 "Unexpected node found!");
12281 Mask.push_back(NumInScalars+i);
12285 // If extracting from the first vector, just use the index directly.
12286 SDValue Extract = N->getOperand(i);
12287 SDValue ExtVal = Extract.getOperand(1);
12288 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12289 if (Extract.getOperand(0) == VecIn1) {
12290 Mask.push_back(ExtIndex);
12294 // Otherwise, use InIdx + InputVecSize
12295 Mask.push_back(InNumElements + ExtIndex);
12298 // Avoid introducing illegal shuffles with zero.
12299 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12302 // We can't generate a shuffle node with mismatched input and output types.
12303 // Attempt to transform a single input vector to the correct type.
12304 if ((VT != VecIn1.getValueType())) {
12305 // If the input vector type has a different base type to the output
12306 // vector type, bail out.
12307 EVT VTElemType = VT.getVectorElementType();
12308 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12309 (VecIn2.getNode() &&
12310 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12313 // If the input vector is too small, widen it.
12314 // We only support widening of vectors which are half the size of the
12315 // output registers. For example XMM->YMM widening on X86 with AVX.
12316 EVT VecInT = VecIn1.getValueType();
12317 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12318 // If we only have one small input, widen it by adding undef values.
12319 if (!VecIn2.getNode())
12320 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12321 DAG.getUNDEF(VecIn1.getValueType()));
12322 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12323 // If we have two small inputs of the same type, try to concat them.
12324 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12325 VecIn2 = SDValue(nullptr, 0);
12328 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12329 // If the input vector is too large, try to split it.
12330 // We don't support having two input vectors that are too large.
12331 // If the zero vector was used, we can not split the vector,
12332 // since we'd need 3 inputs.
12333 if (UsesZeroVector || VecIn2.getNode())
12336 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12339 // Try to replace VecIn1 with two extract_subvectors
12340 // No need to update the masks, they should still be correct.
12341 VecIn2 = DAG.getNode(
12342 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12343 DAG.getConstant(VT.getVectorNumElements(), dl,
12344 TLI.getVectorIdxTy(DAG.getDataLayout())));
12345 VecIn1 = DAG.getNode(
12346 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12347 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12352 if (UsesZeroVector)
12353 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12354 DAG.getConstantFP(0.0, dl, VT);
12356 // If VecIn2 is unused then change it to undef.
12357 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12359 // Check that we were able to transform all incoming values to the same
12361 if (VecIn2.getValueType() != VecIn1.getValueType() ||
12362 VecIn1.getValueType() != VT)
12365 // Return the new VECTOR_SHUFFLE node.
12369 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12375 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12376 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12377 EVT OpVT = N->getOperand(0).getValueType();
12379 // If the operands are legal vectors, leave them alone.
12380 if (TLI.isTypeLegal(OpVT))
12384 EVT VT = N->getValueType(0);
12385 SmallVector<SDValue, 8> Ops;
12387 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12388 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12390 // Keep track of what we encounter.
12391 bool AnyInteger = false;
12392 bool AnyFP = false;
12393 for (const SDValue &Op : N->ops()) {
12394 if (ISD::BITCAST == Op.getOpcode() &&
12395 !Op.getOperand(0).getValueType().isVector())
12396 Ops.push_back(Op.getOperand(0));
12397 else if (ISD::UNDEF == Op.getOpcode())
12398 Ops.push_back(ScalarUndef);
12402 // Note whether we encounter an integer or floating point scalar.
12403 // If it's neither, bail out, it could be something weird like x86mmx.
12404 EVT LastOpVT = Ops.back().getValueType();
12405 if (LastOpVT.isFloatingPoint())
12407 else if (LastOpVT.isInteger())
12413 // If any of the operands is a floating point scalar bitcast to a vector,
12414 // use floating point types throughout, and bitcast everything.
12415 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12417 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12418 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12420 for (SDValue &Op : Ops) {
12421 if (Op.getValueType() == SVT)
12423 if (Op.getOpcode() == ISD::UNDEF)
12426 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12431 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12432 VT.getSizeInBits() / SVT.getSizeInBits());
12433 return DAG.getNode(ISD::BITCAST, DL, VT,
12434 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12437 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12438 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12439 // most two distinct vectors the same size as the result, attempt to turn this
12440 // into a legal shuffle.
12441 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12442 EVT VT = N->getValueType(0);
12443 EVT OpVT = N->getOperand(0).getValueType();
12444 int NumElts = VT.getVectorNumElements();
12445 int NumOpElts = OpVT.getVectorNumElements();
12447 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12448 SmallVector<int, 8> Mask;
12450 for (SDValue Op : N->ops()) {
12451 // Peek through any bitcast.
12452 while (Op.getOpcode() == ISD::BITCAST)
12453 Op = Op.getOperand(0);
12455 // UNDEF nodes convert to UNDEF shuffle mask values.
12456 if (Op.getOpcode() == ISD::UNDEF) {
12457 Mask.append((unsigned)NumOpElts, -1);
12461 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12464 // What vector are we extracting the subvector from and at what index?
12465 SDValue ExtVec = Op.getOperand(0);
12467 // We want the EVT of the original extraction to correctly scale the
12468 // extraction index.
12469 EVT ExtVT = ExtVec.getValueType();
12471 // Peek through any bitcast.
12472 while (ExtVec.getOpcode() == ISD::BITCAST)
12473 ExtVec = ExtVec.getOperand(0);
12475 // UNDEF nodes convert to UNDEF shuffle mask values.
12476 if (ExtVec.getOpcode() == ISD::UNDEF) {
12477 Mask.append((unsigned)NumOpElts, -1);
12481 if (!isa<ConstantSDNode>(Op.getOperand(1)))
12483 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12485 // Ensure that we are extracting a subvector from a vector the same
12486 // size as the result.
12487 if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12490 // Scale the subvector index to account for any bitcast.
12491 int NumExtElts = ExtVT.getVectorNumElements();
12492 if (0 == (NumExtElts % NumElts))
12493 ExtIdx /= (NumExtElts / NumElts);
12494 else if (0 == (NumElts % NumExtElts))
12495 ExtIdx *= (NumElts / NumExtElts);
12499 // At most we can reference 2 inputs in the final shuffle.
12500 if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) {
12502 for (int i = 0; i != NumOpElts; ++i)
12503 Mask.push_back(i + ExtIdx);
12504 } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) {
12506 for (int i = 0; i != NumOpElts; ++i)
12507 Mask.push_back(i + ExtIdx + NumElts);
12513 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
12516 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
12517 DAG.getBitcast(VT, SV1), Mask);
12520 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12521 // If we only have one input vector, we don't need to do any concatenation.
12522 if (N->getNumOperands() == 1)
12523 return N->getOperand(0);
12525 // Check if all of the operands are undefs.
12526 EVT VT = N->getValueType(0);
12527 if (ISD::allOperandsUndef(N))
12528 return DAG.getUNDEF(VT);
12530 // Optimize concat_vectors where all but the first of the vectors are undef.
12531 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12532 return Op.getOpcode() == ISD::UNDEF;
12534 SDValue In = N->getOperand(0);
12535 assert(In.getValueType().isVector() && "Must concat vectors");
12537 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12538 if (In->getOpcode() == ISD::BITCAST &&
12539 !In->getOperand(0)->getValueType(0).isVector()) {
12540 SDValue Scalar = In->getOperand(0);
12542 // If the bitcast type isn't legal, it might be a trunc of a legal type;
12543 // look through the trunc so we can still do the transform:
12544 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12545 if (Scalar->getOpcode() == ISD::TRUNCATE &&
12546 !TLI.isTypeLegal(Scalar.getValueType()) &&
12547 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12548 Scalar = Scalar->getOperand(0);
12550 EVT SclTy = Scalar->getValueType(0);
12552 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12555 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12556 VT.getSizeInBits() / SclTy.getSizeInBits());
12557 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12560 SDLoc dl = SDLoc(N);
12561 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12562 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12566 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12567 // We have already tested above for an UNDEF only concatenation.
12568 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12569 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12570 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12571 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12573 bool AllBuildVectorsOrUndefs =
12574 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12575 if (AllBuildVectorsOrUndefs) {
12576 SmallVector<SDValue, 8> Opnds;
12577 EVT SVT = VT.getScalarType();
12580 if (!SVT.isFloatingPoint()) {
12581 // If BUILD_VECTOR are from built from integer, they may have different
12582 // operand types. Get the smallest type and truncate all operands to it.
12583 bool FoundMinVT = false;
12584 for (const SDValue &Op : N->ops())
12585 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12586 EVT OpSVT = Op.getOperand(0)->getValueType(0);
12587 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12590 assert(FoundMinVT && "Concat vector type mismatch");
12593 for (const SDValue &Op : N->ops()) {
12594 EVT OpVT = Op.getValueType();
12595 unsigned NumElts = OpVT.getVectorNumElements();
12597 if (ISD::UNDEF == Op.getOpcode())
12598 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12600 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12601 if (SVT.isFloatingPoint()) {
12602 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12603 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12605 for (unsigned i = 0; i != NumElts; ++i)
12607 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12612 assert(VT.getVectorNumElements() == Opnds.size() &&
12613 "Concat vector type mismatch");
12614 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12617 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12618 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12621 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
12622 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
12623 if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
12626 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12627 // nodes often generate nop CONCAT_VECTOR nodes.
12628 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12629 // place the incoming vectors at the exact same location.
12630 SDValue SingleSource = SDValue();
12631 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12633 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12634 SDValue Op = N->getOperand(i);
12636 if (Op.getOpcode() == ISD::UNDEF)
12639 // Check if this is the identity extract:
12640 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12643 // Find the single incoming vector for the extract_subvector.
12644 if (SingleSource.getNode()) {
12645 if (Op.getOperand(0) != SingleSource)
12648 SingleSource = Op.getOperand(0);
12650 // Check the source type is the same as the type of the result.
12651 // If not, this concat may extend the vector, so we can not
12652 // optimize it away.
12653 if (SingleSource.getValueType() != N->getValueType(0))
12657 unsigned IdentityIndex = i * PartNumElem;
12658 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12659 // The extract index must be constant.
12663 // Check that we are reading from the identity index.
12664 if (CS->getZExtValue() != IdentityIndex)
12668 if (SingleSource.getNode())
12669 return SingleSource;
12674 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12675 EVT NVT = N->getValueType(0);
12676 SDValue V = N->getOperand(0);
12678 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12680 // (extract_subvec (concat V1, V2, ...), i)
12683 // Only operand 0 is checked as 'concat' assumes all inputs of the same
12685 if (V->getOperand(0).getValueType() != NVT)
12687 unsigned Idx = N->getConstantOperandVal(1);
12688 unsigned NumElems = NVT.getVectorNumElements();
12689 assert((Idx % NumElems) == 0 &&
12690 "IDX in concat is not a multiple of the result vector length.");
12691 return V->getOperand(Idx / NumElems);
12695 if (V->getOpcode() == ISD::BITCAST)
12696 V = V.getOperand(0);
12698 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12700 // Handle only simple case where vector being inserted and vector
12701 // being extracted are of same type, and are half size of larger vectors.
12702 EVT BigVT = V->getOperand(0).getValueType();
12703 EVT SmallVT = V->getOperand(1).getValueType();
12704 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12707 // Only handle cases where both indexes are constants with the same type.
12708 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12709 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12711 if (InsIdx && ExtIdx &&
12712 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12713 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12715 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12717 // indices are equal or bit offsets are equal => V1
12718 // otherwise => (extract_subvec V1, ExtIdx)
12719 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12720 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12721 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12722 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12723 DAG.getNode(ISD::BITCAST, dl,
12724 N->getOperand(0).getValueType(),
12725 V->getOperand(0)), N->getOperand(1));
12732 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12733 SDValue V, SelectionDAG &DAG) {
12735 EVT VT = V.getValueType();
12737 switch (V.getOpcode()) {
12741 case ISD::CONCAT_VECTORS: {
12742 EVT OpVT = V->getOperand(0).getValueType();
12743 int OpSize = OpVT.getVectorNumElements();
12744 SmallBitVector OpUsedElements(OpSize, false);
12745 bool FoundSimplification = false;
12746 SmallVector<SDValue, 4> NewOps;
12747 NewOps.reserve(V->getNumOperands());
12748 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12749 SDValue Op = V->getOperand(i);
12750 bool OpUsed = false;
12751 for (int j = 0; j < OpSize; ++j)
12752 if (UsedElements[i * OpSize + j]) {
12753 OpUsedElements[j] = true;
12757 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12758 : DAG.getUNDEF(OpVT));
12759 FoundSimplification |= Op == NewOps.back();
12760 OpUsedElements.reset();
12762 if (FoundSimplification)
12763 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12767 case ISD::INSERT_SUBVECTOR: {
12768 SDValue BaseV = V->getOperand(0);
12769 SDValue SubV = V->getOperand(1);
12770 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12774 int SubSize = SubV.getValueType().getVectorNumElements();
12775 int Idx = IdxN->getZExtValue();
12776 bool SubVectorUsed = false;
12777 SmallBitVector SubUsedElements(SubSize, false);
12778 for (int i = 0; i < SubSize; ++i)
12779 if (UsedElements[i + Idx]) {
12780 SubVectorUsed = true;
12781 SubUsedElements[i] = true;
12782 UsedElements[i + Idx] = false;
12785 // Now recurse on both the base and sub vectors.
12786 SDValue SimplifiedSubV =
12788 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12789 : DAG.getUNDEF(SubV.getValueType());
12790 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12791 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12792 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12793 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12799 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12800 SDValue N1, SelectionDAG &DAG) {
12801 EVT VT = SVN->getValueType(0);
12802 int NumElts = VT.getVectorNumElements();
12803 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12804 for (int M : SVN->getMask())
12805 if (M >= 0 && M < NumElts)
12806 N0UsedElements[M] = true;
12807 else if (M >= NumElts)
12808 N1UsedElements[M - NumElts] = true;
12810 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12811 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12812 if (S0 == N0 && S1 == N1)
12815 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12818 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12819 // or turn a shuffle of a single concat into simpler shuffle then concat.
12820 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12821 EVT VT = N->getValueType(0);
12822 unsigned NumElts = VT.getVectorNumElements();
12824 SDValue N0 = N->getOperand(0);
12825 SDValue N1 = N->getOperand(1);
12826 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12828 SmallVector<SDValue, 4> Ops;
12829 EVT ConcatVT = N0.getOperand(0).getValueType();
12830 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12831 unsigned NumConcats = NumElts / NumElemsPerConcat;
12833 // Special case: shuffle(concat(A,B)) can be more efficiently represented
12834 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12835 // half vector elements.
12836 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12837 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12838 SVN->getMask().end(), [](int i) { return i == -1; })) {
12839 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12840 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
12841 N1 = DAG.getUNDEF(ConcatVT);
12842 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12845 // Look at every vector that's inserted. We're looking for exact
12846 // subvector-sized copies from a concatenated vector
12847 for (unsigned I = 0; I != NumConcats; ++I) {
12848 // Make sure we're dealing with a copy.
12849 unsigned Begin = I * NumElemsPerConcat;
12850 bool AllUndef = true, NoUndef = true;
12851 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12852 if (SVN->getMaskElt(J) >= 0)
12859 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12862 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12863 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12866 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12867 if (FirstElt < N0.getNumOperands())
12868 Ops.push_back(N0.getOperand(FirstElt));
12870 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12872 } else if (AllUndef) {
12873 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12874 } else { // Mixed with general masks and undefs, can't do optimization.
12879 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12882 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12883 EVT VT = N->getValueType(0);
12884 unsigned NumElts = VT.getVectorNumElements();
12886 SDValue N0 = N->getOperand(0);
12887 SDValue N1 = N->getOperand(1);
12889 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12891 // Canonicalize shuffle undef, undef -> undef
12892 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12893 return DAG.getUNDEF(VT);
12895 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12897 // Canonicalize shuffle v, v -> v, undef
12899 SmallVector<int, 8> NewMask;
12900 for (unsigned i = 0; i != NumElts; ++i) {
12901 int Idx = SVN->getMaskElt(i);
12902 if (Idx >= (int)NumElts) Idx -= NumElts;
12903 NewMask.push_back(Idx);
12905 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12909 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
12910 if (N0.getOpcode() == ISD::UNDEF) {
12911 SmallVector<int, 8> NewMask;
12912 for (unsigned i = 0; i != NumElts; ++i) {
12913 int Idx = SVN->getMaskElt(i);
12915 if (Idx >= (int)NumElts)
12918 Idx = -1; // remove reference to lhs
12920 NewMask.push_back(Idx);
12922 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12926 // Remove references to rhs if it is undef
12927 if (N1.getOpcode() == ISD::UNDEF) {
12928 bool Changed = false;
12929 SmallVector<int, 8> NewMask;
12930 for (unsigned i = 0; i != NumElts; ++i) {
12931 int Idx = SVN->getMaskElt(i);
12932 if (Idx >= (int)NumElts) {
12936 NewMask.push_back(Idx);
12939 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12942 // If it is a splat, check if the argument vector is another splat or a
12944 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12945 SDNode *V = N0.getNode();
12947 // If this is a bit convert that changes the element type of the vector but
12948 // not the number of vector elements, look through it. Be careful not to
12949 // look though conversions that change things like v4f32 to v2f64.
12950 if (V->getOpcode() == ISD::BITCAST) {
12951 SDValue ConvInput = V->getOperand(0);
12952 if (ConvInput.getValueType().isVector() &&
12953 ConvInput.getValueType().getVectorNumElements() == NumElts)
12954 V = ConvInput.getNode();
12957 if (V->getOpcode() == ISD::BUILD_VECTOR) {
12958 assert(V->getNumOperands() == NumElts &&
12959 "BUILD_VECTOR has wrong number of operands");
12961 bool AllSame = true;
12962 for (unsigned i = 0; i != NumElts; ++i) {
12963 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12964 Base = V->getOperand(i);
12968 // Splat of <u, u, u, u>, return <u, u, u, u>
12969 if (!Base.getNode())
12971 for (unsigned i = 0; i != NumElts; ++i) {
12972 if (V->getOperand(i) != Base) {
12977 // Splat of <x, x, x, x>, return <x, x, x, x>
12981 // Canonicalize any other splat as a build_vector.
12982 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12983 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12984 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12985 V->getValueType(0), Ops);
12987 // We may have jumped through bitcasts, so the type of the
12988 // BUILD_VECTOR may not match the type of the shuffle.
12989 if (V->getValueType(0) != VT)
12990 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12995 // There are various patterns used to build up a vector from smaller vectors,
12996 // subvectors, or elements. Scan chains of these and replace unused insertions
12997 // or components with undef.
12998 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13001 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13002 Level < AfterLegalizeVectorOps &&
13003 (N1.getOpcode() == ISD::UNDEF ||
13004 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13005 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13006 SDValue V = partitionShuffleOfConcats(N, DAG);
13012 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13013 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13014 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
13015 SmallVector<SDValue, 8> Ops;
13016 for (int M : SVN->getMask()) {
13017 SDValue Op = DAG.getUNDEF(VT.getScalarType());
13019 int Idx = M % NumElts;
13020 SDValue &S = (M < (int)NumElts ? N0 : N1);
13021 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
13022 Op = S.getOperand(Idx);
13023 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
13025 Op = S.getOperand(0);
13027 // Operand can't be combined - bail out.
13033 if (Ops.size() == VT.getVectorNumElements()) {
13034 // BUILD_VECTOR requires all inputs to be of the same type, find the
13035 // maximum type and extend them all.
13036 EVT SVT = VT.getScalarType();
13037 if (SVT.isInteger())
13038 for (SDValue &Op : Ops)
13039 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13040 if (SVT != VT.getScalarType())
13041 for (SDValue &Op : Ops)
13042 Op = TLI.isZExtFree(Op.getValueType(), SVT)
13043 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
13044 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
13045 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
13049 // If this shuffle only has a single input that is a bitcasted shuffle,
13050 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13051 // back to their original types.
13052 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13053 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
13054 TLI.isTypeLegal(VT)) {
13056 // Peek through the bitcast only if there is one user.
13058 while (BC0.getOpcode() == ISD::BITCAST) {
13059 if (!BC0.hasOneUse())
13061 BC0 = BC0.getOperand(0);
13064 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13066 return SmallVector<int, 8>(Mask.begin(), Mask.end());
13068 SmallVector<int, 8> NewMask;
13070 for (int s = 0; s != Scale; ++s)
13071 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13075 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13076 EVT SVT = VT.getScalarType();
13077 EVT InnerVT = BC0->getValueType(0);
13078 EVT InnerSVT = InnerVT.getScalarType();
13080 // Determine which shuffle works with the smaller scalar type.
13081 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13082 EVT ScaleSVT = ScaleVT.getScalarType();
13084 if (TLI.isTypeLegal(ScaleVT) &&
13085 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13086 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13088 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13089 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13091 // Scale the shuffle masks to the smaller scalar type.
13092 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13093 SmallVector<int, 8> InnerMask =
13094 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13095 SmallVector<int, 8> OuterMask =
13096 ScaleShuffleMask(SVN->getMask(), OuterScale);
13098 // Merge the shuffle masks.
13099 SmallVector<int, 8> NewMask;
13100 for (int M : OuterMask)
13101 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13103 // Test for shuffle mask legality over both commutations.
13104 SDValue SV0 = BC0->getOperand(0);
13105 SDValue SV1 = BC0->getOperand(1);
13106 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13108 std::swap(SV0, SV1);
13109 ShuffleVectorSDNode::commuteMask(NewMask);
13110 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13114 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
13115 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
13116 return DAG.getNode(
13117 ISD::BITCAST, SDLoc(N), VT,
13118 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13124 // Canonicalize shuffles according to rules:
13125 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13126 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13127 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13128 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13129 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
13130 TLI.isTypeLegal(VT)) {
13131 // The incoming shuffle must be of the same type as the result of the
13132 // current shuffle.
13133 assert(N1->getOperand(0).getValueType() == VT &&
13134 "Shuffle types don't match");
13136 SDValue SV0 = N1->getOperand(0);
13137 SDValue SV1 = N1->getOperand(1);
13138 bool HasSameOp0 = N0 == SV0;
13139 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
13140 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13141 // Commute the operands of this shuffle so that next rule
13143 return DAG.getCommutedVectorShuffle(*SVN);
13146 // Try to fold according to rules:
13147 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13148 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13149 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13150 // Don't try to fold shuffles with illegal type.
13151 // Only fold if this shuffle is the only user of the other shuffle.
13152 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13153 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13154 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13156 // The incoming shuffle must be of the same type as the result of the
13157 // current shuffle.
13158 assert(OtherSV->getOperand(0).getValueType() == VT &&
13159 "Shuffle types don't match");
13162 SmallVector<int, 4> Mask;
13163 // Compute the combined shuffle mask for a shuffle with SV0 as the first
13164 // operand, and SV1 as the second operand.
13165 for (unsigned i = 0; i != NumElts; ++i) {
13166 int Idx = SVN->getMaskElt(i);
13168 // Propagate Undef.
13169 Mask.push_back(Idx);
13173 SDValue CurrentVec;
13174 if (Idx < (int)NumElts) {
13175 // This shuffle index refers to the inner shuffle N0. Lookup the inner
13176 // shuffle mask to identify which vector is actually referenced.
13177 Idx = OtherSV->getMaskElt(Idx);
13179 // Propagate Undef.
13180 Mask.push_back(Idx);
13184 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13185 : OtherSV->getOperand(1);
13187 // This shuffle index references an element within N1.
13191 // Simple case where 'CurrentVec' is UNDEF.
13192 if (CurrentVec.getOpcode() == ISD::UNDEF) {
13193 Mask.push_back(-1);
13197 // Canonicalize the shuffle index. We don't know yet if CurrentVec
13198 // will be the first or second operand of the combined shuffle.
13199 Idx = Idx % NumElts;
13200 if (!SV0.getNode() || SV0 == CurrentVec) {
13201 // Ok. CurrentVec is the left hand side.
13202 // Update the mask accordingly.
13204 Mask.push_back(Idx);
13208 // Bail out if we cannot convert the shuffle pair into a single shuffle.
13209 if (SV1.getNode() && SV1 != CurrentVec)
13212 // Ok. CurrentVec is the right hand side.
13213 // Update the mask accordingly.
13215 Mask.push_back(Idx + NumElts);
13218 // Check if all indices in Mask are Undef. In case, propagate Undef.
13219 bool isUndefMask = true;
13220 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13221 isUndefMask &= Mask[i] < 0;
13224 return DAG.getUNDEF(VT);
13226 if (!SV0.getNode())
13227 SV0 = DAG.getUNDEF(VT);
13228 if (!SV1.getNode())
13229 SV1 = DAG.getUNDEF(VT);
13231 // Avoid introducing shuffles with illegal mask.
13232 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13233 ShuffleVectorSDNode::commuteMask(Mask);
13235 if (!TLI.isShuffleMaskLegal(Mask, VT))
13238 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13239 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13240 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13241 std::swap(SV0, SV1);
13244 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13245 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13246 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13247 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13253 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13254 SDValue InVal = N->getOperand(0);
13255 EVT VT = N->getValueType(0);
13257 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13258 // with a VECTOR_SHUFFLE.
13259 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13260 SDValue InVec = InVal->getOperand(0);
13261 SDValue EltNo = InVal->getOperand(1);
13263 // FIXME: We could support implicit truncation if the shuffle can be
13264 // scaled to a smaller vector scalar type.
13265 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13266 if (C0 && VT == InVec.getValueType() &&
13267 VT.getScalarType() == InVal.getValueType()) {
13268 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13269 int Elt = C0->getZExtValue();
13272 if (TLI.isShuffleMaskLegal(NewMask, VT))
13273 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13281 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13282 SDValue N0 = N->getOperand(0);
13283 SDValue N2 = N->getOperand(2);
13285 // If the input vector is a concatenation, and the insert replaces
13286 // one of the halves, we can optimize into a single concat_vectors.
13287 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13288 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13289 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13290 EVT VT = N->getValueType(0);
13292 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13293 // (concat_vectors Z, Y)
13295 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13296 N->getOperand(1), N0.getOperand(1));
13298 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13299 // (concat_vectors X, Z)
13300 if (InsIdx == VT.getVectorNumElements()/2)
13301 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13302 N0.getOperand(0), N->getOperand(1));
13308 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13309 SDValue N0 = N->getOperand(0);
13311 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13312 if (N0->getOpcode() == ISD::FP16_TO_FP)
13313 return N0->getOperand(0);
13318 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13319 SDValue N0 = N->getOperand(0);
13321 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13322 if (N0->getOpcode() == ISD::AND) {
13323 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13324 if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13325 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13333 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13334 /// with the destination vector and a zero vector.
13335 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13336 /// vector_shuffle V, Zero, <0, 4, 2, 4>
13337 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13338 EVT VT = N->getValueType(0);
13339 SDValue LHS = N->getOperand(0);
13340 SDValue RHS = N->getOperand(1);
13343 // Make sure we're not running after operation legalization where it
13344 // may have custom lowered the vector shuffles.
13345 if (LegalOperations)
13348 if (N->getOpcode() != ISD::AND)
13351 if (RHS.getOpcode() == ISD::BITCAST)
13352 RHS = RHS.getOperand(0);
13354 if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13357 EVT RVT = RHS.getValueType();
13358 unsigned NumElts = RHS.getNumOperands();
13360 // Attempt to create a valid clear mask, splitting the mask into
13361 // sub elements and checking to see if each is
13362 // all zeros or all ones - suitable for shuffle masking.
13363 auto BuildClearMask = [&](int Split) {
13364 int NumSubElts = NumElts * Split;
13365 int NumSubBits = RVT.getScalarSizeInBits() / Split;
13367 SmallVector<int, 8> Indices;
13368 for (int i = 0; i != NumSubElts; ++i) {
13369 int EltIdx = i / Split;
13370 int SubIdx = i % Split;
13371 SDValue Elt = RHS.getOperand(EltIdx);
13372 if (Elt.getOpcode() == ISD::UNDEF) {
13373 Indices.push_back(-1);
13378 if (isa<ConstantSDNode>(Elt))
13379 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13380 else if (isa<ConstantFPSDNode>(Elt))
13381 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13385 // Extract the sub element from the constant bit mask.
13386 if (DAG.getDataLayout().isBigEndian()) {
13387 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13389 Bits = Bits.lshr(SubIdx * NumSubBits);
13393 Bits = Bits.trunc(NumSubBits);
13395 if (Bits.isAllOnesValue())
13396 Indices.push_back(i);
13397 else if (Bits == 0)
13398 Indices.push_back(i + NumSubElts);
13403 // Let's see if the target supports this vector_shuffle.
13404 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13405 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13406 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13409 SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13410 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13411 DAG.getBitcast(ClearVT, LHS),
13412 Zero, &Indices[0]));
13415 // Determine maximum split level (byte level masking).
13417 if (RVT.getScalarSizeInBits() % 8 == 0)
13418 MaxSplit = RVT.getScalarSizeInBits() / 8;
13420 for (int Split = 1; Split <= MaxSplit; ++Split)
13421 if (RVT.getScalarSizeInBits() % Split == 0)
13422 if (SDValue S = BuildClearMask(Split))
13428 /// Visit a binary vector operation, like ADD.
13429 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13430 assert(N->getValueType(0).isVector() &&
13431 "SimplifyVBinOp only works on vectors!");
13433 SDValue LHS = N->getOperand(0);
13434 SDValue RHS = N->getOperand(1);
13435 SDValue Ops[] = {LHS, RHS};
13437 // See if we can constant fold the vector operation.
13438 if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
13439 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
13442 // Try to convert a constant mask AND into a shuffle clear mask.
13443 if (SDValue Shuffle = XformToShuffleWithZero(N))
13446 // Type legalization might introduce new shuffles in the DAG.
13447 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13448 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
13449 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13450 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13451 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13452 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13453 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13454 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13456 if (SVN0->getMask().equals(SVN1->getMask())) {
13457 EVT VT = N->getValueType(0);
13458 SDValue UndefVector = LHS.getOperand(1);
13459 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13460 LHS.getOperand(0), RHS.getOperand(0),
13462 AddUsersToWorklist(N);
13463 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13464 &SVN0->getMask()[0]);
13471 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13472 SDValue N1, SDValue N2){
13473 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13475 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13476 cast<CondCodeSDNode>(N0.getOperand(2))->get());
13478 // If we got a simplified select_cc node back from SimplifySelectCC, then
13479 // break it down into a new SETCC node, and a new SELECT node, and then return
13480 // the SELECT node, since we were called with a SELECT node.
13481 if (SCC.getNode()) {
13482 // Check to see if we got a select_cc back (to turn into setcc/select).
13483 // Otherwise, just return whatever node we got back, like fabs.
13484 if (SCC.getOpcode() == ISD::SELECT_CC) {
13485 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13487 SCC.getOperand(0), SCC.getOperand(1),
13488 SCC.getOperand(4));
13489 AddToWorklist(SETCC.getNode());
13490 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13491 SCC.getOperand(2), SCC.getOperand(3));
13499 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13500 /// being selected between, see if we can simplify the select. Callers of this
13501 /// should assume that TheSelect is deleted if this returns true. As such, they
13502 /// should return the appropriate thing (e.g. the node) back to the top-level of
13503 /// the DAG combiner loop to avoid it being looked at.
13504 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13507 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13508 // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13509 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13510 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13511 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13512 SDValue Sqrt = RHS;
13515 const ConstantFPSDNode *NegZero = nullptr;
13517 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13518 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13519 CmpLHS = TheSelect->getOperand(0);
13520 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13522 // SELECT or VSELECT
13523 SDValue Cmp = TheSelect->getOperand(0);
13524 if (Cmp.getOpcode() == ISD::SETCC) {
13525 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13526 CmpLHS = Cmp.getOperand(0);
13527 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13530 if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13531 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13532 CC == ISD::SETULT || CC == ISD::SETLT)) {
13533 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13534 CombineTo(TheSelect, Sqrt);
13539 // Cannot simplify select with vector condition
13540 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13542 // If this is a select from two identical things, try to pull the operation
13543 // through the select.
13544 if (LHS.getOpcode() != RHS.getOpcode() ||
13545 !LHS.hasOneUse() || !RHS.hasOneUse())
13548 // If this is a load and the token chain is identical, replace the select
13549 // of two loads with a load through a select of the address to load from.
13550 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13551 // constants have been dropped into the constant pool.
13552 if (LHS.getOpcode() == ISD::LOAD) {
13553 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13554 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13556 // Token chains must be identical.
13557 if (LHS.getOperand(0) != RHS.getOperand(0) ||
13558 // Do not let this transformation reduce the number of volatile loads.
13559 LLD->isVolatile() || RLD->isVolatile() ||
13560 // FIXME: If either is a pre/post inc/dec load,
13561 // we'd need to split out the address adjustment.
13562 LLD->isIndexed() || RLD->isIndexed() ||
13563 // If this is an EXTLOAD, the VT's must match.
13564 LLD->getMemoryVT() != RLD->getMemoryVT() ||
13565 // If this is an EXTLOAD, the kind of extension must match.
13566 (LLD->getExtensionType() != RLD->getExtensionType() &&
13567 // The only exception is if one of the extensions is anyext.
13568 LLD->getExtensionType() != ISD::EXTLOAD &&
13569 RLD->getExtensionType() != ISD::EXTLOAD) ||
13570 // FIXME: this discards src value information. This is
13571 // over-conservative. It would be beneficial to be able to remember
13572 // both potential memory locations. Since we are discarding
13573 // src value info, don't do the transformation if the memory
13574 // locations are not in the default address space.
13575 LLD->getPointerInfo().getAddrSpace() != 0 ||
13576 RLD->getPointerInfo().getAddrSpace() != 0 ||
13577 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13578 LLD->getBasePtr().getValueType()))
13581 // Check that the select condition doesn't reach either load. If so,
13582 // folding this will induce a cycle into the DAG. If not, this is safe to
13583 // xform, so create a select of the addresses.
13585 if (TheSelect->getOpcode() == ISD::SELECT) {
13586 SDNode *CondNode = TheSelect->getOperand(0).getNode();
13587 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13588 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13590 // The loads must not depend on one another.
13591 if (LLD->isPredecessorOf(RLD) ||
13592 RLD->isPredecessorOf(LLD))
13594 Addr = DAG.getSelect(SDLoc(TheSelect),
13595 LLD->getBasePtr().getValueType(),
13596 TheSelect->getOperand(0), LLD->getBasePtr(),
13597 RLD->getBasePtr());
13598 } else { // Otherwise SELECT_CC
13599 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13600 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13602 if ((LLD->hasAnyUseOfValue(1) &&
13603 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13604 (RLD->hasAnyUseOfValue(1) &&
13605 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13608 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13609 LLD->getBasePtr().getValueType(),
13610 TheSelect->getOperand(0),
13611 TheSelect->getOperand(1),
13612 LLD->getBasePtr(), RLD->getBasePtr(),
13613 TheSelect->getOperand(4));
13617 // It is safe to replace the two loads if they have different alignments,
13618 // but the new load must be the minimum (most restrictive) alignment of the
13620 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13621 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13622 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13623 Load = DAG.getLoad(TheSelect->getValueType(0),
13625 // FIXME: Discards pointer and AA info.
13626 LLD->getChain(), Addr, MachinePointerInfo(),
13627 LLD->isVolatile(), LLD->isNonTemporal(),
13628 isInvariant, Alignment);
13630 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13631 RLD->getExtensionType() : LLD->getExtensionType(),
13633 TheSelect->getValueType(0),
13634 // FIXME: Discards pointer and AA info.
13635 LLD->getChain(), Addr, MachinePointerInfo(),
13636 LLD->getMemoryVT(), LLD->isVolatile(),
13637 LLD->isNonTemporal(), isInvariant, Alignment);
13640 // Users of the select now use the result of the load.
13641 CombineTo(TheSelect, Load);
13643 // Users of the old loads now use the new load's chain. We know the
13644 // old-load value is dead now.
13645 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13646 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13653 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13654 /// where 'cond' is the comparison specified by CC.
13655 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13656 SDValue N2, SDValue N3,
13657 ISD::CondCode CC, bool NotExtCompare) {
13658 // (x ? y : y) -> y.
13659 if (N2 == N3) return N2;
13661 EVT VT = N2.getValueType();
13662 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13663 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13665 // Determine if the condition we're dealing with is constant
13666 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13667 N0, N1, CC, DL, false);
13668 if (SCC.getNode()) AddToWorklist(SCC.getNode());
13670 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13671 // fold select_cc true, x, y -> x
13672 // fold select_cc false, x, y -> y
13673 return !SCCC->isNullValue() ? N2 : N3;
13676 // Check to see if we can simplify the select into an fabs node
13677 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13678 // Allow either -0.0 or 0.0
13679 if (CFP->isZero()) {
13680 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13681 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13682 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13683 N2 == N3.getOperand(0))
13684 return DAG.getNode(ISD::FABS, DL, VT, N0);
13686 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13687 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13688 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13689 N2.getOperand(0) == N3)
13690 return DAG.getNode(ISD::FABS, DL, VT, N3);
13694 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13695 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13696 // in it. This is a win when the constant is not otherwise available because
13697 // it replaces two constant pool loads with one. We only do this if the FP
13698 // type is known to be legal, because if it isn't, then we are before legalize
13699 // types an we want the other legalization to happen first (e.g. to avoid
13700 // messing with soft float) and if the ConstantFP is not legal, because if
13701 // it is legal, we may not need to store the FP constant in a constant pool.
13702 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13703 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13704 if (TLI.isTypeLegal(N2.getValueType()) &&
13705 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13706 TargetLowering::Legal &&
13707 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13708 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13709 // If both constants have multiple uses, then we won't need to do an
13710 // extra load, they are likely around in registers for other users.
13711 (TV->hasOneUse() || FV->hasOneUse())) {
13712 Constant *Elts[] = {
13713 const_cast<ConstantFP*>(FV->getConstantFPValue()),
13714 const_cast<ConstantFP*>(TV->getConstantFPValue())
13716 Type *FPTy = Elts[0]->getType();
13717 const DataLayout &TD = DAG.getDataLayout();
13719 // Create a ConstantArray of the two constants.
13720 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13722 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
13723 TD.getPrefTypeAlignment(FPTy));
13724 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13726 // Get the offsets to the 0 and 1 element of the array so that we can
13727 // select between them.
13728 SDValue Zero = DAG.getIntPtrConstant(0, DL);
13729 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13730 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13732 SDValue Cond = DAG.getSetCC(DL,
13733 getSetCCResultType(N0.getValueType()),
13735 AddToWorklist(Cond.getNode());
13736 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13738 AddToWorklist(CstOffset.getNode());
13739 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13741 AddToWorklist(CPIdx.getNode());
13742 return DAG.getLoad(
13743 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13744 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13745 false, false, false, Alignment);
13749 // Check to see if we can perform the "gzip trick", transforming
13750 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13751 if (isNullConstant(N3) && CC == ISD::SETLT &&
13752 (isNullConstant(N1) || // (a < 0) ? b : 0
13753 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0
13754 EVT XType = N0.getValueType();
13755 EVT AType = N2.getValueType();
13756 if (XType.bitsGE(AType)) {
13757 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13758 // single-bit constant.
13759 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13760 unsigned ShCtV = N2C->getAPIntValue().logBase2();
13761 ShCtV = XType.getSizeInBits() - ShCtV - 1;
13762 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13763 getShiftAmountTy(N0.getValueType()));
13764 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13766 AddToWorklist(Shift.getNode());
13768 if (XType.bitsGT(AType)) {
13769 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13770 AddToWorklist(Shift.getNode());
13773 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13776 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13778 DAG.getConstant(XType.getSizeInBits() - 1,
13780 getShiftAmountTy(N0.getValueType())));
13781 AddToWorklist(Shift.getNode());
13783 if (XType.bitsGT(AType)) {
13784 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13785 AddToWorklist(Shift.getNode());
13788 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13792 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13793 // where y is has a single bit set.
13794 // A plaintext description would be, we can turn the SELECT_CC into an AND
13795 // when the condition can be materialized as an all-ones register. Any
13796 // single bit-test can be materialized as an all-ones register with
13797 // shift-left and shift-right-arith.
13798 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13799 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13800 SDValue AndLHS = N0->getOperand(0);
13801 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13802 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13803 // Shift the tested bit over the sign bit.
13804 APInt AndMask = ConstAndRHS->getAPIntValue();
13806 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13807 getShiftAmountTy(AndLHS.getValueType()));
13808 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13810 // Now arithmetic right shift it all the way over, so the result is either
13811 // all-ones, or zero.
13813 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13814 getShiftAmountTy(Shl.getValueType()));
13815 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13817 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13821 // fold select C, 16, 0 -> shl C, 4
13822 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13823 TLI.getBooleanContents(N0.getValueType()) ==
13824 TargetLowering::ZeroOrOneBooleanContent) {
13826 // If the caller doesn't want us to simplify this into a zext of a compare,
13828 if (NotExtCompare && N2C->isOne())
13831 // Get a SetCC of the condition
13832 // NOTE: Don't create a SETCC if it's not legal on this target.
13833 if (!LegalOperations ||
13834 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
13836 // cast from setcc result type to select result type
13838 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13840 if (N2.getValueType().bitsLT(SCC.getValueType()))
13841 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13842 N2.getValueType());
13844 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13845 N2.getValueType(), SCC);
13847 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13848 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13849 N2.getValueType(), SCC);
13852 AddToWorklist(SCC.getNode());
13853 AddToWorklist(Temp.getNode());
13858 // shl setcc result by log2 n2c
13859 return DAG.getNode(
13860 ISD::SHL, DL, N2.getValueType(), Temp,
13861 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13862 getShiftAmountTy(Temp.getValueType())));
13866 // Check to see if this is an integer abs.
13867 // select_cc setg[te] X, 0, X, -X ->
13868 // select_cc setgt X, -1, X, -X ->
13869 // select_cc setl[te] X, 0, -X, X ->
13870 // select_cc setlt X, 1, -X, X ->
13871 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13873 ConstantSDNode *SubC = nullptr;
13874 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13875 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13876 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13877 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13878 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13879 (N1C->isOne() && CC == ISD::SETLT)) &&
13880 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13881 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13883 EVT XType = N0.getValueType();
13884 if (SubC && SubC->isNullValue() && XType.isInteger()) {
13886 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13888 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13889 getShiftAmountTy(N0.getValueType())));
13890 SDValue Add = DAG.getNode(ISD::ADD, DL,
13892 AddToWorklist(Shift.getNode());
13893 AddToWorklist(Add.getNode());
13894 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13901 /// This is a stub for TargetLowering::SimplifySetCC.
13902 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13903 SDValue N1, ISD::CondCode Cond,
13904 SDLoc DL, bool foldBooleans) {
13905 TargetLowering::DAGCombinerInfo
13906 DagCombineInfo(DAG, Level, false, this);
13907 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13910 /// Given an ISD::SDIV node expressing a divide by constant, return
13911 /// a DAG expression to select that will generate the same value by multiplying
13912 /// by a magic number.
13913 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13914 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13915 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13919 // Avoid division by zero.
13920 if (C->isNullValue())
13923 std::vector<SDNode*> Built;
13925 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13927 for (SDNode *N : Built)
13932 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13933 /// DAG expression that will generate the same value by right shifting.
13934 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13935 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13939 // Avoid division by zero.
13940 if (C->isNullValue())
13943 std::vector<SDNode *> Built;
13944 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13946 for (SDNode *N : Built)
13951 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13952 /// expression that will generate the same value by multiplying by a magic
13954 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13955 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13956 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13960 // Avoid division by zero.
13961 if (C->isNullValue())
13964 std::vector<SDNode*> Built;
13966 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13968 for (SDNode *N : Built)
13973 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
13974 if (Level >= AfterLegalizeDAG)
13977 // Expose the DAG combiner to the target combiner implementations.
13978 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13980 unsigned Iterations = 0;
13981 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13983 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13984 // For the reciprocal, we need to find the zero of the function:
13985 // F(X) = A X - 1 [which has a zero at X = 1/A]
13987 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13988 // does not require additional intermediate precision]
13989 EVT VT = Op.getValueType();
13991 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13993 AddToWorklist(Est.getNode());
13995 // Newton iterations: Est = Est + Est (1 - Arg * Est)
13996 for (unsigned i = 0; i < Iterations; ++i) {
13997 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
13998 AddToWorklist(NewEst.getNode());
14000 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14001 AddToWorklist(NewEst.getNode());
14003 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14004 AddToWorklist(NewEst.getNode());
14006 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14007 AddToWorklist(Est.getNode());
14016 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14017 /// For the reciprocal sqrt, we need to find the zero of the function:
14018 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14020 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14021 /// As a result, we precompute A/2 prior to the iteration loop.
14022 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
14023 unsigned Iterations,
14024 SDNodeFlags *Flags) {
14025 EVT VT = Arg.getValueType();
14027 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14029 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14030 // this entire sequence requires only one FP constant.
14031 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14032 AddToWorklist(HalfArg.getNode());
14034 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14035 AddToWorklist(HalfArg.getNode());
14037 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14038 for (unsigned i = 0; i < Iterations; ++i) {
14039 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14040 AddToWorklist(NewEst.getNode());
14042 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14043 AddToWorklist(NewEst.getNode());
14045 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14046 AddToWorklist(NewEst.getNode());
14048 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14049 AddToWorklist(Est.getNode());
14054 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14055 /// For the reciprocal sqrt, we need to find the zero of the function:
14056 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14058 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14059 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
14060 unsigned Iterations,
14061 SDNodeFlags *Flags) {
14062 EVT VT = Arg.getValueType();
14064 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
14065 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
14067 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
14068 for (unsigned i = 0; i < Iterations; ++i) {
14069 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
14070 AddToWorklist(HalfEst.getNode());
14072 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14073 AddToWorklist(Est.getNode());
14075 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14076 AddToWorklist(Est.getNode());
14078 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags);
14079 AddToWorklist(Est.getNode());
14081 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags);
14082 AddToWorklist(Est.getNode());
14087 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14088 if (Level >= AfterLegalizeDAG)
14091 // Expose the DAG combiner to the target combiner implementations.
14092 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14093 unsigned Iterations = 0;
14094 bool UseOneConstNR = false;
14095 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
14096 AddToWorklist(Est.getNode());
14098 Est = UseOneConstNR ?
14099 BuildRsqrtNROneConst(Op, Est, Iterations, Flags) :
14100 BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags);
14108 /// Return true if base is a frame index, which is known not to alias with
14109 /// anything but itself. Provides base object and offset as results.
14110 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14111 const GlobalValue *&GV, const void *&CV) {
14112 // Assume it is a primitive operation.
14113 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14115 // If it's an adding a simple constant then integrate the offset.
14116 if (Base.getOpcode() == ISD::ADD) {
14117 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14118 Base = Base.getOperand(0);
14119 Offset += C->getZExtValue();
14123 // Return the underlying GlobalValue, and update the Offset. Return false
14124 // for GlobalAddressSDNode since the same GlobalAddress may be represented
14125 // by multiple nodes with different offsets.
14126 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14127 GV = G->getGlobal();
14128 Offset += G->getOffset();
14132 // Return the underlying Constant value, and update the Offset. Return false
14133 // for ConstantSDNodes since the same constant pool entry may be represented
14134 // by multiple nodes with different offsets.
14135 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14136 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14137 : (const void *)C->getConstVal();
14138 Offset += C->getOffset();
14141 // If it's any of the following then it can't alias with anything but itself.
14142 return isa<FrameIndexSDNode>(Base);
14145 /// Return true if there is any possibility that the two addresses overlap.
14146 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14147 // If they are the same then they must be aliases.
14148 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14150 // If they are both volatile then they cannot be reordered.
14151 if (Op0->isVolatile() && Op1->isVolatile()) return true;
14153 // If one operation reads from invariant memory, and the other may store, they
14154 // cannot alias. These should really be checking the equivalent of mayWrite,
14155 // but it only matters for memory nodes other than load /store.
14156 if (Op0->isInvariant() && Op1->writeMem())
14159 if (Op1->isInvariant() && Op0->writeMem())
14162 // Gather base node and offset information.
14163 SDValue Base1, Base2;
14164 int64_t Offset1, Offset2;
14165 const GlobalValue *GV1, *GV2;
14166 const void *CV1, *CV2;
14167 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14168 Base1, Offset1, GV1, CV1);
14169 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14170 Base2, Offset2, GV2, CV2);
14172 // If they have a same base address then check to see if they overlap.
14173 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14174 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14175 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14177 // It is possible for different frame indices to alias each other, mostly
14178 // when tail call optimization reuses return address slots for arguments.
14179 // To catch this case, look up the actual index of frame indices to compute
14180 // the real alias relationship.
14181 if (isFrameIndex1 && isFrameIndex2) {
14182 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14183 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14184 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14185 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14186 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14189 // Otherwise, if we know what the bases are, and they aren't identical, then
14190 // we know they cannot alias.
14191 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14194 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14195 // compared to the size and offset of the access, we may be able to prove they
14196 // do not alias. This check is conservative for now to catch cases created by
14197 // splitting vector types.
14198 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14199 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14200 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14201 Op1->getMemoryVT().getSizeInBits() >> 3) &&
14202 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14203 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14204 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14206 // There is no overlap between these relatively aligned accesses of similar
14207 // size, return no alias.
14208 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14209 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14213 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14215 : DAG.getSubtarget().useAA();
14217 if (CombinerAAOnlyFunc.getNumOccurrences() &&
14218 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14222 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14223 // Use alias analysis information.
14224 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14225 Op1->getSrcValueOffset());
14226 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14227 Op0->getSrcValueOffset() - MinOffset;
14228 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14229 Op1->getSrcValueOffset() - MinOffset;
14230 AliasResult AAResult =
14231 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14232 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14233 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14234 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14235 if (AAResult == NoAlias)
14239 // Otherwise we have to assume they alias.
14243 /// Walk up chain skipping non-aliasing memory nodes,
14244 /// looking for aliasing nodes and adding them to the Aliases vector.
14245 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14246 SmallVectorImpl<SDValue> &Aliases) {
14247 SmallVector<SDValue, 8> Chains; // List of chains to visit.
14248 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
14250 // Get alias information for node.
14251 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14254 Chains.push_back(OriginalChain);
14255 unsigned Depth = 0;
14257 // Look at each chain and determine if it is an alias. If so, add it to the
14258 // aliases list. If not, then continue up the chain looking for the next
14260 while (!Chains.empty()) {
14261 SDValue Chain = Chains.pop_back_val();
14263 // For TokenFactor nodes, look at each operand and only continue up the
14264 // chain until we reach the depth limit.
14266 // FIXME: The depth check could be made to return the last non-aliasing
14267 // chain we found before we hit a tokenfactor rather than the original
14271 Aliases.push_back(OriginalChain);
14275 // Don't bother if we've been before.
14276 if (!Visited.insert(Chain.getNode()).second)
14279 switch (Chain.getOpcode()) {
14280 case ISD::EntryToken:
14281 // Entry token is ideal chain operand, but handled in FindBetterChain.
14286 // Get alias information for Chain.
14287 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14288 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14290 // If chain is alias then stop here.
14291 if (!(IsLoad && IsOpLoad) &&
14292 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14293 Aliases.push_back(Chain);
14295 // Look further up the chain.
14296 Chains.push_back(Chain.getOperand(0));
14302 case ISD::TokenFactor:
14303 // We have to check each of the operands of the token factor for "small"
14304 // token factors, so we queue them up. Adding the operands to the queue
14305 // (stack) in reverse order maintains the original order and increases the
14306 // likelihood that getNode will find a matching token factor (CSE.)
14307 if (Chain.getNumOperands() > 16) {
14308 Aliases.push_back(Chain);
14311 for (unsigned n = Chain.getNumOperands(); n;)
14312 Chains.push_back(Chain.getOperand(--n));
14317 // For all other instructions we will just have to take what we can get.
14318 Aliases.push_back(Chain);
14323 // We need to be careful here to also search for aliases through the
14324 // value operand of a store, etc. Consider the following situation:
14326 // L1 = load Token1, %52
14327 // S1 = store Token1, L1, %51
14328 // L2 = load Token1, %52+8
14329 // S2 = store Token1, L2, %51+8
14330 // Token2 = Token(S1, S2)
14331 // L3 = load Token2, %53
14332 // S3 = store Token2, L3, %52
14333 // L4 = load Token2, %53+8
14334 // S4 = store Token2, L4, %52+8
14335 // If we search for aliases of S3 (which loads address %52), and we look
14336 // only through the chain, then we'll miss the trivial dependence on L1
14337 // (which also loads from %52). We then might change all loads and
14338 // stores to use Token1 as their chain operand, which could result in
14339 // copying %53 into %52 before copying %52 into %51 (which should
14342 // The problem is, however, that searching for such data dependencies
14343 // can become expensive, and the cost is not directly related to the
14344 // chain depth. Instead, we'll rule out such configurations here by
14345 // insisting that we've visited all chain users (except for users
14346 // of the original chain, which is not necessary). When doing this,
14347 // we need to look through nodes we don't care about (otherwise, things
14348 // like register copies will interfere with trivial cases).
14350 SmallVector<const SDNode *, 16> Worklist;
14351 for (const SDNode *N : Visited)
14352 if (N != OriginalChain.getNode())
14353 Worklist.push_back(N);
14355 while (!Worklist.empty()) {
14356 const SDNode *M = Worklist.pop_back_val();
14358 // We have already visited M, and want to make sure we've visited any uses
14359 // of M that we care about. For uses that we've not visisted, and don't
14360 // care about, queue them to the worklist.
14362 for (SDNode::use_iterator UI = M->use_begin(),
14363 UIE = M->use_end(); UI != UIE; ++UI)
14364 if (UI.getUse().getValueType() == MVT::Other &&
14365 Visited.insert(*UI).second) {
14366 if (isa<MemSDNode>(*UI)) {
14367 // We've not visited this use, and we care about it (it could have an
14368 // ordering dependency with the original node).
14370 Aliases.push_back(OriginalChain);
14374 // We've not visited this use, but we don't care about it. Mark it as
14375 // visited and enqueue it to the worklist.
14376 Worklist.push_back(*UI);
14381 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14382 /// (aliasing node.)
14383 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14384 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
14386 // Accumulate all the aliases to this node.
14387 GatherAllAliases(N, OldChain, Aliases);
14389 // If no operands then chain to entry token.
14390 if (Aliases.size() == 0)
14391 return DAG.getEntryNode();
14393 // If a single operand then chain to it. We don't need to revisit it.
14394 if (Aliases.size() == 1)
14397 // Construct a custom tailored token factor.
14398 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14401 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) {
14402 // This holds the base pointer, index, and the offset in bytes from the base
14404 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
14406 // We must have a base and an offset.
14407 if (!BasePtr.Base.getNode())
14410 // Do not handle stores to undef base pointers.
14411 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
14414 SmallVector<StoreSDNode *, 8> ChainedStores;
14415 ChainedStores.push_back(St);
14417 // Walk up the chain and look for nodes with offsets from the same
14418 // base pointer. Stop when reaching an instruction with a different kind
14419 // or instruction which has a different base pointer.
14420 StoreSDNode *Index = St;
14422 // If the chain has more than one use, then we can't reorder the mem ops.
14423 if (Index != St && !SDValue(Index, 0)->hasOneUse())
14426 if (Index->isVolatile() || Index->isIndexed())
14429 // Find the base pointer and offset for this memory node.
14430 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
14432 // Check that the base pointer is the same as the original one.
14433 if (!Ptr.equalBaseIndex(BasePtr))
14436 // Find the next memory operand in the chain. If the next operand in the
14437 // chain is a store then move up and continue the scan with the next
14438 // memory operand. If the next operand is a load save it and use alias
14439 // information to check if it interferes with anything.
14440 SDNode *NextInChain = Index->getChain().getNode();
14442 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
14443 // We found a store node. Use it for the next iteration.
14444 ChainedStores.push_back(STn);
14447 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
14448 NextInChain = Ldn->getChain().getNode();
14457 bool MadeChange = false;
14458 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
14460 for (StoreSDNode *ChainedStore : ChainedStores) {
14461 SDValue Chain = ChainedStore->getChain();
14462 SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
14464 if (Chain != BetterChain) {
14466 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
14470 // Do all replacements after finding the replacements to make to avoid making
14471 // the chains more complicated by introducing new TokenFactors.
14472 for (auto Replacement : BetterChains)
14473 replaceStoreChain(Replacement.first, Replacement.second);
14478 /// This is the entry point for the file.
14479 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14480 CodeGenOpt::Level OptLevel) {
14481 /// This is the main entry point to this class.
14482 DAGCombiner(*this, AA, OptLevel).Run(Level);