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 useDivRem(SDNode *N);
240 SDValue visitSDIV(SDNode *N);
241 SDValue visitUDIV(SDNode *N);
242 SDValue visitREM(SDNode *N);
243 SDValue visitMULHU(SDNode *N);
244 SDValue visitMULHS(SDNode *N);
245 SDValue visitSMUL_LOHI(SDNode *N);
246 SDValue visitUMUL_LOHI(SDNode *N);
247 SDValue visitSMULO(SDNode *N);
248 SDValue visitUMULO(SDNode *N);
249 SDValue visitIMINMAX(SDNode *N);
250 SDValue visitAND(SDNode *N);
251 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
252 SDValue visitOR(SDNode *N);
253 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
254 SDValue visitXOR(SDNode *N);
255 SDValue SimplifyVBinOp(SDNode *N);
256 SDValue visitSHL(SDNode *N);
257 SDValue visitSRA(SDNode *N);
258 SDValue visitSRL(SDNode *N);
259 SDValue visitRotate(SDNode *N);
260 SDValue visitBSWAP(SDNode *N);
261 SDValue visitCTLZ(SDNode *N);
262 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
263 SDValue visitCTTZ(SDNode *N);
264 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
265 SDValue visitCTPOP(SDNode *N);
266 SDValue visitSELECT(SDNode *N);
267 SDValue visitVSELECT(SDNode *N);
268 SDValue visitSELECT_CC(SDNode *N);
269 SDValue visitSETCC(SDNode *N);
270 SDValue visitSETCCE(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 visitMUL to check the profitability
408 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
409 /// MulNode is the original multiply, AddNode is (add x, c1),
410 /// and ConstNode is c2.
411 bool isMulAddWithConstProfitable(SDNode *MulNode,
415 /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
416 /// constant build_vector of the stored constant values in Stores.
417 SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
419 ArrayRef<MemOpLink> Stores,
420 SmallVectorImpl<SDValue> &Chains,
423 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns
424 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns
425 /// the type of the loaded value to be extended. LoadedVT returns the type
426 /// of the original loaded value. NarrowLoad returns whether the load would
427 /// need to be narrowed in order to match.
428 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
429 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
432 /// This is a helper function for MergeConsecutiveStores. When the source
433 /// elements of the consecutive stores are all constants or all extracted
434 /// vector elements, try to merge them into one larger store.
435 /// \return True if a merged store was created.
436 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
437 EVT MemVT, unsigned NumStores,
438 bool IsConstantSrc, bool UseVector);
440 /// This is a helper function for MergeConsecutiveStores.
441 /// Stores that may be merged are placed in StoreNodes.
442 /// Loads that may alias with those stores are placed in AliasLoadNodes.
443 void getStoreMergeAndAliasCandidates(
444 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
445 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
447 /// Merge consecutive store operations into a wide store.
448 /// This optimization uses wide integers or vectors when possible.
449 /// \return True if some memory operations were changed.
450 bool MergeConsecutiveStores(StoreSDNode *N);
452 /// \brief Try to transform a truncation where C is a constant:
453 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
455 /// \p N needs to be a truncation and its first operand an AND. Other
456 /// requirements are checked by the function (e.g. that trunc is
457 /// single-use) and if missed an empty SDValue is returned.
458 SDValue distributeTruncateThroughAnd(SDNode *N);
461 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
462 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
463 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
464 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
467 /// Runs the dag combiner on all nodes in the work list
468 void Run(CombineLevel AtLevel);
470 SelectionDAG &getDAG() const { return DAG; }
472 /// Returns a type large enough to hold any valid shift amount - before type
473 /// legalization these can be huge.
474 EVT getShiftAmountTy(EVT LHSTy) {
475 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
476 if (LHSTy.isVector())
478 auto &DL = DAG.getDataLayout();
479 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
480 : TLI.getPointerTy(DL);
483 /// This method returns true if we are running before type legalization or
484 /// if the specified VT is legal.
485 bool isTypeLegal(const EVT &VT) {
486 if (!LegalTypes) return true;
487 return TLI.isTypeLegal(VT);
490 /// Convenience wrapper around TargetLowering::getSetCCResultType
491 EVT getSetCCResultType(EVT VT) const {
492 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
499 /// This class is a DAGUpdateListener that removes any deleted
500 /// nodes from the worklist.
501 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
504 explicit WorklistRemover(DAGCombiner &dc)
505 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
507 void NodeDeleted(SDNode *N, SDNode *E) override {
508 DC.removeFromWorklist(N);
513 //===----------------------------------------------------------------------===//
514 // TargetLowering::DAGCombinerInfo implementation
515 //===----------------------------------------------------------------------===//
517 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
518 ((DAGCombiner*)DC)->AddToWorklist(N);
521 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
522 ((DAGCombiner*)DC)->removeFromWorklist(N);
525 SDValue TargetLowering::DAGCombinerInfo::
526 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
527 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
530 SDValue TargetLowering::DAGCombinerInfo::
531 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
532 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
536 SDValue TargetLowering::DAGCombinerInfo::
537 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
538 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
541 void TargetLowering::DAGCombinerInfo::
542 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
543 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
546 //===----------------------------------------------------------------------===//
548 //===----------------------------------------------------------------------===//
550 void DAGCombiner::deleteAndRecombine(SDNode *N) {
551 removeFromWorklist(N);
553 // If the operands of this node are only used by the node, they will now be
554 // dead. Make sure to re-visit them and recursively delete dead nodes.
555 for (const SDValue &Op : N->ops())
556 // For an operand generating multiple values, one of the values may
557 // become dead allowing further simplification (e.g. split index
558 // arithmetic from an indexed load).
559 if (Op->hasOneUse() || Op->getNumValues() > 1)
560 AddToWorklist(Op.getNode());
565 /// Return 1 if we can compute the negated form of the specified expression for
566 /// the same cost as the expression itself, or 2 if we can compute the negated
567 /// form more cheaply than the expression itself.
568 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
569 const TargetLowering &TLI,
570 const TargetOptions *Options,
571 unsigned Depth = 0) {
572 // fneg is removable even if it has multiple uses.
573 if (Op.getOpcode() == ISD::FNEG) return 2;
575 // Don't allow anything with multiple uses.
576 if (!Op.hasOneUse()) return 0;
578 // Don't recurse exponentially.
579 if (Depth > 6) return 0;
581 switch (Op.getOpcode()) {
582 default: return false;
583 case ISD::ConstantFP:
584 // Don't invert constant FP values after legalize. The negated constant
585 // isn't necessarily legal.
586 return LegalOperations ? 0 : 1;
588 // FIXME: determine better conditions for this xform.
589 if (!Options->UnsafeFPMath) return 0;
591 // After operation legalization, it might not be legal to create new FSUBs.
592 if (LegalOperations &&
593 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
596 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
597 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
600 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
601 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
604 // We can't turn -(A-B) into B-A when we honor signed zeros.
605 if (!Options->UnsafeFPMath) return 0;
607 // fold (fneg (fsub A, B)) -> (fsub B, A)
612 if (Options->HonorSignDependentRoundingFPMath()) return 0;
614 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
615 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
619 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
625 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
630 /// If isNegatibleForFree returns true, return the newly negated expression.
631 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
632 bool LegalOperations, unsigned Depth = 0) {
633 const TargetOptions &Options = DAG.getTarget().Options;
634 // fneg is removable even if it has multiple uses.
635 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
637 // Don't allow anything with multiple uses.
638 assert(Op.hasOneUse() && "Unknown reuse!");
640 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
642 const SDNodeFlags *Flags = Op.getNode()->getFlags();
644 switch (Op.getOpcode()) {
645 default: llvm_unreachable("Unknown code");
646 case ISD::ConstantFP: {
647 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
649 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
652 // FIXME: determine better conditions for this xform.
653 assert(Options.UnsafeFPMath);
655 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
656 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
657 DAG.getTargetLoweringInfo(), &Options, Depth+1))
658 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
659 GetNegatedExpression(Op.getOperand(0), DAG,
660 LegalOperations, Depth+1),
661 Op.getOperand(1), Flags);
662 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
663 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
664 GetNegatedExpression(Op.getOperand(1), DAG,
665 LegalOperations, Depth+1),
666 Op.getOperand(0), Flags);
668 // We can't turn -(A-B) into B-A when we honor signed zeros.
669 assert(Options.UnsafeFPMath);
671 // fold (fneg (fsub 0, B)) -> B
672 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
674 return Op.getOperand(1);
676 // fold (fneg (fsub A, B)) -> (fsub B, A)
677 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
678 Op.getOperand(1), Op.getOperand(0), Flags);
682 assert(!Options.HonorSignDependentRoundingFPMath());
684 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
685 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
686 DAG.getTargetLoweringInfo(), &Options, Depth+1))
687 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
688 GetNegatedExpression(Op.getOperand(0), DAG,
689 LegalOperations, Depth+1),
690 Op.getOperand(1), Flags);
692 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
693 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
695 GetNegatedExpression(Op.getOperand(1), DAG,
696 LegalOperations, Depth+1), Flags);
700 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
701 GetNegatedExpression(Op.getOperand(0), DAG,
702 LegalOperations, Depth+1));
704 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
705 GetNegatedExpression(Op.getOperand(0), DAG,
706 LegalOperations, Depth+1),
711 // Return true if this node is a setcc, or is a select_cc
712 // that selects between the target values used for true and false, making it
713 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
714 // the appropriate nodes based on the type of node we are checking. This
715 // simplifies life a bit for the callers.
716 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
718 if (N.getOpcode() == ISD::SETCC) {
719 LHS = N.getOperand(0);
720 RHS = N.getOperand(1);
721 CC = N.getOperand(2);
725 if (N.getOpcode() != ISD::SELECT_CC ||
726 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
727 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
730 if (TLI.getBooleanContents(N.getValueType()) ==
731 TargetLowering::UndefinedBooleanContent)
734 LHS = N.getOperand(0);
735 RHS = N.getOperand(1);
736 CC = N.getOperand(4);
740 /// Return true if this is a SetCC-equivalent operation with only one use.
741 /// If this is true, it allows the users to invert the operation for free when
742 /// it is profitable to do so.
743 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
745 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
750 /// Returns true if N is a BUILD_VECTOR node whose
751 /// elements are all the same constant or undefined.
752 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
753 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
758 unsigned SplatBitSize;
760 EVT EltVT = N->getValueType(0).getVectorElementType();
761 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
763 EltVT.getSizeInBits() >= SplatBitSize);
766 // \brief Returns the SDNode if it is a constant integer BuildVector
767 // or constant integer.
768 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
769 if (isa<ConstantSDNode>(N))
771 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
776 // \brief Returns the SDNode if it is a constant float BuildVector
777 // or constant float.
778 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
779 if (isa<ConstantFPSDNode>(N))
781 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
786 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
788 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
789 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
792 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
793 BitVector UndefElements;
794 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
796 // BuildVectors can truncate their operands. Ignore that case here.
797 // FIXME: We blindly ignore splats which include undef which is overly
799 if (CN && UndefElements.none() &&
800 CN->getValueType(0) == N.getValueType().getScalarType())
807 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
809 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
810 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
813 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
814 BitVector UndefElements;
815 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
817 if (CN && UndefElements.none())
824 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
825 SDValue N0, SDValue N1) {
826 EVT VT = N0.getValueType();
827 if (N0.getOpcode() == Opc) {
828 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
829 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
830 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
831 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
832 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
835 if (N0.hasOneUse()) {
836 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
838 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
839 if (!OpNode.getNode())
841 AddToWorklist(OpNode.getNode());
842 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
847 if (N1.getOpcode() == Opc) {
848 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
849 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
850 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
851 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
852 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
855 if (N1.hasOneUse()) {
856 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
858 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
859 if (!OpNode.getNode())
861 AddToWorklist(OpNode.getNode());
862 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
870 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
872 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
874 DEBUG(dbgs() << "\nReplacing.1 ";
876 dbgs() << "\nWith: ";
877 To[0].getNode()->dump(&DAG);
878 dbgs() << " and " << NumTo-1 << " other values\n");
879 for (unsigned i = 0, e = NumTo; i != e; ++i)
880 assert((!To[i].getNode() ||
881 N->getValueType(i) == To[i].getValueType()) &&
882 "Cannot combine value to value of different type!");
884 WorklistRemover DeadNodes(*this);
885 DAG.ReplaceAllUsesWith(N, To);
887 // Push the new nodes and any users onto the worklist
888 for (unsigned i = 0, e = NumTo; i != e; ++i) {
889 if (To[i].getNode()) {
890 AddToWorklist(To[i].getNode());
891 AddUsersToWorklist(To[i].getNode());
896 // Finally, if the node is now dead, remove it from the graph. The node
897 // may not be dead if the replacement process recursively simplified to
898 // something else needing this node.
900 deleteAndRecombine(N);
901 return SDValue(N, 0);
905 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
906 // Replace all uses. If any nodes become isomorphic to other nodes and
907 // are deleted, make sure to remove them from our worklist.
908 WorklistRemover DeadNodes(*this);
909 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
911 // Push the new node and any (possibly new) users onto the worklist.
912 AddToWorklist(TLO.New.getNode());
913 AddUsersToWorklist(TLO.New.getNode());
915 // Finally, if the node is now dead, remove it from the graph. The node
916 // may not be dead if the replacement process recursively simplified to
917 // something else needing this node.
918 if (TLO.Old.getNode()->use_empty())
919 deleteAndRecombine(TLO.Old.getNode());
922 /// Check the specified integer node value to see if it can be simplified or if
923 /// things it uses can be simplified by bit propagation. If so, return true.
924 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
925 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
926 APInt KnownZero, KnownOne;
929 auto Opcode = Op.getOpcode();
930 if (Opcode == ISD::AND || Opcode == ISD::OR) {
931 auto* Op1 = Op.getOperand(0).getNode();
932 auto* Op2 = Op.getOperand(1).getNode();
933 auto* Op1C = dyn_cast<ConstantSDNode>(Op1);
934 auto* Op2C = dyn_cast<ConstantSDNode>(Op2);
937 if (Opcode == ISD::AND && !Op1C && Op2C && Op2C->isNullValue()) {
942 if (Opcode == ISD::OR) {
943 if (Op1->getOpcode() == ISD::AND) {
944 auto* Op11 = Op1->getOperand(0).getNode();
945 auto* Op12 = Op1->getOperand(1).getNode();
946 auto* Op11C = dyn_cast<ConstantSDNode>(Op11);
947 auto* Op12C = dyn_cast<ConstantSDNode>(Op12);
948 if (!Op11C && Op12C && Op12C->isNullValue()) {
952 if (Op1->getOpcode() == ISD::TRUNCATE) {
953 // or (trunc (and %0, 0)), Y
954 auto* Op11 = Op1->getOperand(0).getNode();
955 if (Op11->getOpcode() == ISD::AND) {
956 auto* Op111 = Op11->getOperand(0).getNode();
957 auto* Op112 = Op11->getOperand(1).getNode();
958 auto* Op111C = dyn_cast<ConstantSDNode>(Op111);
959 auto* Op112C = dyn_cast<ConstantSDNode>(Op112);
960 if (!Op111C && Op112C && Op112C->isNullValue()) {
970 if (Opcode == ISD::TRUNCATE) {
971 auto* Op1 = Op.getOperand(0).getNode();
972 if (Op1->getOpcode() == ISD::AND) {
973 auto* Op11 = Op1->getOperand(0).getNode();
974 auto* Op12 = Op1->getOperand(1).getNode();
975 auto* Op11C = dyn_cast<ConstantSDNode>(Op11);
976 auto* Op12C = dyn_cast<ConstantSDNode>(Op12);
977 if (!Op11C && Op12C && Op12C->isNullValue()) {
983 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
987 AddToWorklist(Op.getNode());
989 // Replace the old value with the new one.
991 DEBUG(dbgs() << "\nReplacing.2 ";
992 TLO.Old.getNode()->dump(&DAG);
993 dbgs() << "\nWith: ";
994 TLO.New.getNode()->dump(&DAG);
997 CommitTargetLoweringOpt(TLO);
1001 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
1003 EVT VT = Load->getValueType(0);
1004 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
1006 DEBUG(dbgs() << "\nReplacing.9 ";
1008 dbgs() << "\nWith: ";
1009 Trunc.getNode()->dump(&DAG);
1011 WorklistRemover DeadNodes(*this);
1012 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
1013 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
1014 deleteAndRecombine(Load);
1015 AddToWorklist(Trunc.getNode());
1018 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
1021 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
1022 EVT MemVT = LD->getMemoryVT();
1023 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1024 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1026 : LD->getExtensionType();
1028 return DAG.getExtLoad(ExtType, dl, PVT,
1029 LD->getChain(), LD->getBasePtr(),
1030 MemVT, LD->getMemOperand());
1033 unsigned Opc = Op.getOpcode();
1036 case ISD::AssertSext:
1037 return DAG.getNode(ISD::AssertSext, dl, PVT,
1038 SExtPromoteOperand(Op.getOperand(0), PVT),
1040 case ISD::AssertZext:
1041 return DAG.getNode(ISD::AssertZext, dl, PVT,
1042 ZExtPromoteOperand(Op.getOperand(0), PVT),
1044 case ISD::Constant: {
1046 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1047 return DAG.getNode(ExtOpc, dl, PVT, Op);
1051 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1053 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
1056 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1057 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1059 EVT OldVT = Op.getValueType();
1061 bool Replace = false;
1062 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1063 if (!NewOp.getNode())
1065 AddToWorklist(NewOp.getNode());
1068 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1069 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
1070 DAG.getValueType(OldVT));
1073 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1074 EVT OldVT = Op.getValueType();
1076 bool Replace = false;
1077 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1078 if (!NewOp.getNode())
1080 AddToWorklist(NewOp.getNode());
1083 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1084 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
1087 /// Promote the specified integer binary operation if the target indicates it is
1088 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1089 /// i32 since i16 instructions are longer.
1090 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1091 if (!LegalOperations)
1094 EVT VT = Op.getValueType();
1095 if (VT.isVector() || !VT.isInteger())
1098 // If operation type is 'undesirable', e.g. i16 on x86, consider
1100 unsigned Opc = Op.getOpcode();
1101 if (TLI.isTypeDesirableForOp(Opc, VT))
1105 // Consult target whether it is a good idea to promote this operation and
1106 // what's the right type to promote it to.
1107 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1108 assert(PVT != VT && "Don't know what type to promote to!");
1110 bool Replace0 = false;
1111 SDValue N0 = Op.getOperand(0);
1112 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1116 bool Replace1 = false;
1117 SDValue N1 = Op.getOperand(1);
1122 NN1 = PromoteOperand(N1, PVT, Replace1);
1127 AddToWorklist(NN0.getNode());
1129 AddToWorklist(NN1.getNode());
1132 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1134 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1136 DEBUG(dbgs() << "\nPromoting ";
1137 Op.getNode()->dump(&DAG));
1139 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1140 DAG.getNode(Opc, dl, PVT, NN0, NN1));
1145 /// Promote the specified integer shift operation if the target indicates it is
1146 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1147 /// i32 since i16 instructions are longer.
1148 SDValue DAGCombiner::PromoteIntShiftOp(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!");
1168 bool Replace = false;
1169 SDValue N0 = Op.getOperand(0);
1170 if (Opc == ISD::SRA)
1171 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1172 else if (Opc == ISD::SRL)
1173 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1175 N0 = PromoteOperand(N0, PVT, Replace);
1179 AddToWorklist(N0.getNode());
1181 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1183 DEBUG(dbgs() << "\nPromoting ";
1184 Op.getNode()->dump(&DAG));
1186 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1187 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1192 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1193 if (!LegalOperations)
1196 EVT VT = Op.getValueType();
1197 if (VT.isVector() || !VT.isInteger())
1200 // If operation type is 'undesirable', e.g. i16 on x86, consider
1202 unsigned Opc = Op.getOpcode();
1203 if (TLI.isTypeDesirableForOp(Opc, VT))
1207 // Consult target whether it is a good idea to promote this operation and
1208 // what's the right type to promote it to.
1209 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1210 assert(PVT != VT && "Don't know what type to promote to!");
1211 // fold (aext (aext x)) -> (aext x)
1212 // fold (aext (zext x)) -> (zext x)
1213 // fold (aext (sext x)) -> (sext x)
1214 DEBUG(dbgs() << "\nPromoting ";
1215 Op.getNode()->dump(&DAG));
1216 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1221 bool DAGCombiner::PromoteLoad(SDValue Op) {
1222 if (!LegalOperations)
1225 EVT VT = Op.getValueType();
1226 if (VT.isVector() || !VT.isInteger())
1229 // If operation type is 'undesirable', e.g. i16 on x86, consider
1231 unsigned Opc = Op.getOpcode();
1232 if (TLI.isTypeDesirableForOp(Opc, VT))
1236 // Consult target whether it is a good idea to promote this operation and
1237 // what's the right type to promote it to.
1238 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1239 assert(PVT != VT && "Don't know what type to promote to!");
1242 SDNode *N = Op.getNode();
1243 LoadSDNode *LD = cast<LoadSDNode>(N);
1244 EVT MemVT = LD->getMemoryVT();
1245 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1246 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1248 : LD->getExtensionType();
1249 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1250 LD->getChain(), LD->getBasePtr(),
1251 MemVT, LD->getMemOperand());
1252 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1254 DEBUG(dbgs() << "\nPromoting ";
1257 Result.getNode()->dump(&DAG);
1259 WorklistRemover DeadNodes(*this);
1260 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1261 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1262 deleteAndRecombine(N);
1263 AddToWorklist(Result.getNode());
1269 /// \brief Recursively delete a node which has no uses and any operands for
1270 /// which it is the only use.
1272 /// Note that this both deletes the nodes and removes them from the worklist.
1273 /// It also adds any nodes who have had a user deleted to the worklist as they
1274 /// may now have only one use and subject to other combines.
1275 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1276 if (!N->use_empty())
1279 SmallSetVector<SDNode *, 16> Nodes;
1282 N = Nodes.pop_back_val();
1286 if (N->use_empty()) {
1287 for (const SDValue &ChildN : N->op_values())
1288 Nodes.insert(ChildN.getNode());
1290 removeFromWorklist(N);
1295 } while (!Nodes.empty());
1299 //===----------------------------------------------------------------------===//
1300 // Main DAG Combiner implementation
1301 //===----------------------------------------------------------------------===//
1303 void DAGCombiner::Run(CombineLevel AtLevel) {
1304 // set the instance variables, so that the various visit routines may use it.
1306 LegalOperations = Level >= AfterLegalizeVectorOps;
1307 LegalTypes = Level >= AfterLegalizeTypes;
1309 // Add all the dag nodes to the worklist.
1310 for (SDNode &Node : DAG.allnodes())
1311 AddToWorklist(&Node);
1313 // Create a dummy node (which is not added to allnodes), that adds a reference
1314 // to the root node, preventing it from being deleted, and tracking any
1315 // changes of the root.
1316 HandleSDNode Dummy(DAG.getRoot());
1318 // while the worklist isn't empty, find a node and
1319 // try and combine it.
1320 while (!WorklistMap.empty()) {
1322 // The Worklist holds the SDNodes in order, but it may contain null entries.
1324 N = Worklist.pop_back_val();
1327 bool GoodWorklistEntry = WorklistMap.erase(N);
1328 (void)GoodWorklistEntry;
1329 assert(GoodWorklistEntry &&
1330 "Found a worklist entry without a corresponding map entry!");
1332 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1333 // N is deleted from the DAG, since they too may now be dead or may have a
1334 // reduced number of uses, allowing other xforms.
1335 if (recursivelyDeleteUnusedNodes(N))
1338 WorklistRemover DeadNodes(*this);
1340 // If this combine is running after legalizing the DAG, re-legalize any
1341 // nodes pulled off the worklist.
1342 if (Level == AfterLegalizeDAG) {
1343 SmallSetVector<SDNode *, 16> UpdatedNodes;
1344 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1346 for (SDNode *LN : UpdatedNodes) {
1348 AddUsersToWorklist(LN);
1354 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1356 // Add any operands of the new node which have not yet been combined to the
1357 // worklist as well. Because the worklist uniques things already, this
1358 // won't repeatedly process the same operand.
1359 CombinedNodes.insert(N);
1360 for (const SDValue &ChildN : N->op_values())
1361 if (!CombinedNodes.count(ChildN.getNode()))
1362 AddToWorklist(ChildN.getNode());
1364 SDValue RV = combine(N);
1371 // If we get back the same node we passed in, rather than a new node or
1372 // zero, we know that the node must have defined multiple values and
1373 // CombineTo was used. Since CombineTo takes care of the worklist
1374 // mechanics for us, we have no work to do in this case.
1375 if (RV.getNode() == N)
1378 assert(N->getOpcode() != ISD::DELETED_NODE &&
1379 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1380 "Node was deleted but visit returned new node!");
1382 DEBUG(dbgs() << " ... into: ";
1383 RV.getNode()->dump(&DAG));
1385 // Transfer debug value.
1386 DAG.TransferDbgValues(SDValue(N, 0), RV);
1387 if (N->getNumValues() == RV.getNode()->getNumValues())
1388 DAG.ReplaceAllUsesWith(N, RV.getNode());
1390 assert(N->getValueType(0) == RV.getValueType() &&
1391 N->getNumValues() == 1 && "Type mismatch");
1393 DAG.ReplaceAllUsesWith(N, &OpV);
1396 // Push the new node and any users onto the worklist
1397 AddToWorklist(RV.getNode());
1398 AddUsersToWorklist(RV.getNode());
1400 // Finally, if the node is now dead, remove it from the graph. The node
1401 // may not be dead if the replacement process recursively simplified to
1402 // something else needing this node. This will also take care of adding any
1403 // operands which have lost a user to the worklist.
1404 recursivelyDeleteUnusedNodes(N);
1407 // If the root changed (e.g. it was a dead load, update the root).
1408 DAG.setRoot(Dummy.getValue());
1409 DAG.RemoveDeadNodes();
1412 SDValue DAGCombiner::visit(SDNode *N) {
1413 switch (N->getOpcode()) {
1415 case ISD::TokenFactor: return visitTokenFactor(N);
1416 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1417 case ISD::ADD: return visitADD(N);
1418 case ISD::SUB: return visitSUB(N);
1419 case ISD::ADDC: return visitADDC(N);
1420 case ISD::SUBC: return visitSUBC(N);
1421 case ISD::ADDE: return visitADDE(N);
1422 case ISD::SUBE: return visitSUBE(N);
1423 case ISD::MUL: return visitMUL(N);
1424 case ISD::SDIV: return visitSDIV(N);
1425 case ISD::UDIV: return visitUDIV(N);
1427 case ISD::UREM: return visitREM(N);
1428 case ISD::MULHU: return visitMULHU(N);
1429 case ISD::MULHS: return visitMULHS(N);
1430 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1431 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1432 case ISD::SMULO: return visitSMULO(N);
1433 case ISD::UMULO: return visitUMULO(N);
1437 case ISD::UMAX: return visitIMINMAX(N);
1438 case ISD::AND: return visitAND(N);
1439 case ISD::OR: return visitOR(N);
1440 case ISD::XOR: return visitXOR(N);
1441 case ISD::SHL: return visitSHL(N);
1442 case ISD::SRA: return visitSRA(N);
1443 case ISD::SRL: return visitSRL(N);
1445 case ISD::ROTL: return visitRotate(N);
1446 case ISD::BSWAP: return visitBSWAP(N);
1447 case ISD::CTLZ: return visitCTLZ(N);
1448 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1449 case ISD::CTTZ: return visitCTTZ(N);
1450 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1451 case ISD::CTPOP: return visitCTPOP(N);
1452 case ISD::SELECT: return visitSELECT(N);
1453 case ISD::VSELECT: return visitVSELECT(N);
1454 case ISD::SELECT_CC: return visitSELECT_CC(N);
1455 case ISD::SETCC: return visitSETCC(N);
1456 case ISD::SETCCE: return visitSETCCE(N);
1457 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1458 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1459 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1460 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1461 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1462 case ISD::TRUNCATE: return visitTRUNCATE(N);
1463 case ISD::BITCAST: return visitBITCAST(N);
1464 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1465 case ISD::FADD: return visitFADD(N);
1466 case ISD::FSUB: return visitFSUB(N);
1467 case ISD::FMUL: return visitFMUL(N);
1468 case ISD::FMA: return visitFMA(N);
1469 case ISD::FDIV: return visitFDIV(N);
1470 case ISD::FREM: return visitFREM(N);
1471 case ISD::FSQRT: return visitFSQRT(N);
1472 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1473 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1474 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1475 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1476 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1477 case ISD::FP_ROUND: return visitFP_ROUND(N);
1478 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1479 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1480 case ISD::FNEG: return visitFNEG(N);
1481 case ISD::FABS: return visitFABS(N);
1482 case ISD::FFLOOR: return visitFFLOOR(N);
1483 case ISD::FMINNUM: return visitFMINNUM(N);
1484 case ISD::FMAXNUM: return visitFMAXNUM(N);
1485 case ISD::FCEIL: return visitFCEIL(N);
1486 case ISD::FTRUNC: return visitFTRUNC(N);
1487 case ISD::BRCOND: return visitBRCOND(N);
1488 case ISD::BR_CC: return visitBR_CC(N);
1489 case ISD::LOAD: return visitLOAD(N);
1490 case ISD::STORE: return visitSTORE(N);
1491 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1492 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1493 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1494 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1495 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1496 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1497 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1498 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1499 case ISD::MGATHER: return visitMGATHER(N);
1500 case ISD::MLOAD: return visitMLOAD(N);
1501 case ISD::MSCATTER: return visitMSCATTER(N);
1502 case ISD::MSTORE: return visitMSTORE(N);
1503 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
1504 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N);
1509 SDValue DAGCombiner::combine(SDNode *N) {
1510 SDValue RV = visit(N);
1512 // If nothing happened, try a target-specific DAG combine.
1513 if (!RV.getNode()) {
1514 assert(N->getOpcode() != ISD::DELETED_NODE &&
1515 "Node was deleted but visit returned NULL!");
1517 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1518 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1520 // Expose the DAG combiner to the target combiner impls.
1521 TargetLowering::DAGCombinerInfo
1522 DagCombineInfo(DAG, Level, false, this);
1524 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1528 // If nothing happened still, try promoting the operation.
1529 if (!RV.getNode()) {
1530 switch (N->getOpcode()) {
1538 RV = PromoteIntBinOp(SDValue(N, 0));
1543 RV = PromoteIntShiftOp(SDValue(N, 0));
1545 case ISD::SIGN_EXTEND:
1546 case ISD::ZERO_EXTEND:
1547 case ISD::ANY_EXTEND:
1548 RV = PromoteExtend(SDValue(N, 0));
1551 if (PromoteLoad(SDValue(N, 0)))
1557 // If N is a commutative binary node, try commuting it to enable more
1559 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1560 N->getNumValues() == 1) {
1561 SDValue N0 = N->getOperand(0);
1562 SDValue N1 = N->getOperand(1);
1564 // Constant operands are canonicalized to RHS.
1565 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1566 SDValue Ops[] = {N1, N0};
1567 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1570 return SDValue(CSENode, 0);
1577 /// Given a node, return its input chain if it has one, otherwise return a null
1579 static SDValue getInputChainForNode(SDNode *N) {
1580 if (unsigned NumOps = N->getNumOperands()) {
1581 if (N->getOperand(0).getValueType() == MVT::Other)
1582 return N->getOperand(0);
1583 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1584 return N->getOperand(NumOps-1);
1585 for (unsigned i = 1; i < NumOps-1; ++i)
1586 if (N->getOperand(i).getValueType() == MVT::Other)
1587 return N->getOperand(i);
1592 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1593 // If N has two operands, where one has an input chain equal to the other,
1594 // the 'other' chain is redundant.
1595 if (N->getNumOperands() == 2) {
1596 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1597 return N->getOperand(0);
1598 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1599 return N->getOperand(1);
1602 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1603 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1604 SmallPtrSet<SDNode*, 16> SeenOps;
1605 bool Changed = false; // If we should replace this token factor.
1607 // Start out with this token factor.
1610 // Iterate through token factors. The TFs grows when new token factors are
1612 for (unsigned i = 0; i < TFs.size(); ++i) {
1613 SDNode *TF = TFs[i];
1615 // Check each of the operands.
1616 for (const SDValue &Op : TF->op_values()) {
1618 switch (Op.getOpcode()) {
1619 case ISD::EntryToken:
1620 // Entry tokens don't need to be added to the list. They are
1625 case ISD::TokenFactor:
1626 if (Op.hasOneUse() &&
1627 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1628 // Queue up for processing.
1629 TFs.push_back(Op.getNode());
1630 // Clean up in case the token factor is removed.
1631 AddToWorklist(Op.getNode());
1638 // Only add if it isn't already in the list.
1639 if (SeenOps.insert(Op.getNode()).second)
1650 // If we've changed things around then replace token factor.
1653 // The entry token is the only possible outcome.
1654 Result = DAG.getEntryNode();
1656 // New and improved token factor.
1657 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1660 // Add users to worklist if AA is enabled, since it may introduce
1661 // a lot of new chained token factors while removing memory deps.
1662 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1663 : DAG.getSubtarget().useAA();
1664 return CombineTo(N, Result, UseAA /*add to worklist*/);
1670 /// MERGE_VALUES can always be eliminated.
1671 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1672 WorklistRemover DeadNodes(*this);
1673 // Replacing results may cause a different MERGE_VALUES to suddenly
1674 // be CSE'd with N, and carry its uses with it. Iterate until no
1675 // uses remain, to ensure that the node can be safely deleted.
1676 // First add the users of this node to the work list so that they
1677 // can be tried again once they have new operands.
1678 AddUsersToWorklist(N);
1680 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1681 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1682 } while (!N->use_empty());
1683 deleteAndRecombine(N);
1684 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1687 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1688 /// ContantSDNode pointer else nullptr.
1689 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1690 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1691 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1694 SDValue DAGCombiner::visitADD(SDNode *N) {
1695 SDValue N0 = N->getOperand(0);
1696 SDValue N1 = N->getOperand(1);
1697 EVT VT = N0.getValueType();
1700 if (VT.isVector()) {
1701 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1704 // fold (add x, 0) -> x, vector edition
1705 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1707 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1711 // fold (add x, undef) -> undef
1712 if (N0.getOpcode() == ISD::UNDEF)
1714 if (N1.getOpcode() == ISD::UNDEF)
1716 // fold (add c1, c2) -> c1+c2
1717 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1718 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1720 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1721 // canonicalize constant to RHS
1722 if (isConstantIntBuildVectorOrConstantInt(N0) &&
1723 !isConstantIntBuildVectorOrConstantInt(N1))
1724 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1725 // fold (add x, 0) -> x
1726 if (isNullConstant(N1))
1728 // fold (add Sym, c) -> Sym+c
1729 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1730 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1731 GA->getOpcode() == ISD::GlobalAddress)
1732 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1734 (uint64_t)N1C->getSExtValue());
1735 // fold ((c1-A)+c2) -> (c1+c2)-A
1736 if (N1C && N0.getOpcode() == ISD::SUB)
1737 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1739 return DAG.getNode(ISD::SUB, DL, VT,
1740 DAG.getConstant(N1C->getAPIntValue()+
1741 N0C->getAPIntValue(), DL, VT),
1745 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1747 // fold ((0-A) + B) -> B-A
1748 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1749 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1750 // fold (A + (0-B)) -> A-B
1751 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1752 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1753 // fold (A+(B-A)) -> B
1754 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1755 return N1.getOperand(0);
1756 // fold ((B-A)+A) -> B
1757 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1758 return N0.getOperand(0);
1759 // fold (A+(B-(A+C))) to (B-C)
1760 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1761 N0 == N1.getOperand(1).getOperand(0))
1762 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1763 N1.getOperand(1).getOperand(1));
1764 // fold (A+(B-(C+A))) to (B-C)
1765 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1766 N0 == N1.getOperand(1).getOperand(1))
1767 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1768 N1.getOperand(1).getOperand(0));
1769 // fold (A+((B-A)+or-C)) to (B+or-C)
1770 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1771 N1.getOperand(0).getOpcode() == ISD::SUB &&
1772 N0 == N1.getOperand(0).getOperand(1))
1773 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1774 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1776 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1777 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1778 SDValue N00 = N0.getOperand(0);
1779 SDValue N01 = N0.getOperand(1);
1780 SDValue N10 = N1.getOperand(0);
1781 SDValue N11 = N1.getOperand(1);
1783 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1784 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1785 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1786 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1789 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1790 return SDValue(N, 0);
1792 // fold (a+b) -> (a|b) iff a and b share no bits.
1793 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
1794 VT.isInteger() && !VT.isVector() && DAG.haveNoCommonBitsSet(N0, N1))
1795 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1797 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1798 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1799 isNullConstant(N1.getOperand(0).getOperand(0)))
1800 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1801 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1802 N1.getOperand(0).getOperand(1),
1804 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1805 isNullConstant(N0.getOperand(0).getOperand(0)))
1806 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1807 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1808 N0.getOperand(0).getOperand(1),
1811 if (N1.getOpcode() == ISD::AND) {
1812 SDValue AndOp0 = N1.getOperand(0);
1813 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1814 unsigned DestBits = VT.getScalarType().getSizeInBits();
1816 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1817 // and similar xforms where the inner op is either ~0 or 0.
1818 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1820 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1824 // add (sext i1), X -> sub X, (zext i1)
1825 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1826 N0.getOperand(0).getValueType() == MVT::i1 &&
1827 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1829 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1830 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1833 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1834 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1835 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1836 if (TN->getVT() == MVT::i1) {
1838 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1839 DAG.getConstant(1, DL, VT));
1840 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1847 SDValue DAGCombiner::visitADDC(SDNode *N) {
1848 SDValue N0 = N->getOperand(0);
1849 SDValue N1 = N->getOperand(1);
1850 EVT VT = N0.getValueType();
1852 // If the flag result is dead, turn this into an ADD.
1853 if (!N->hasAnyUseOfValue(1))
1854 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1855 DAG.getNode(ISD::CARRY_FALSE,
1856 SDLoc(N), MVT::Glue));
1858 // canonicalize constant to RHS.
1859 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1860 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1862 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1864 // fold (addc x, 0) -> x + no carry out
1865 if (isNullConstant(N1))
1866 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1867 SDLoc(N), MVT::Glue));
1869 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1870 APInt LHSZero, LHSOne;
1871 APInt RHSZero, RHSOne;
1872 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1874 if (LHSZero.getBoolValue()) {
1875 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1877 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1878 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1879 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1880 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1881 DAG.getNode(ISD::CARRY_FALSE,
1882 SDLoc(N), MVT::Glue));
1888 SDValue DAGCombiner::visitADDE(SDNode *N) {
1889 SDValue N0 = N->getOperand(0);
1890 SDValue N1 = N->getOperand(1);
1891 SDValue CarryIn = N->getOperand(2);
1893 // canonicalize constant to RHS
1894 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1895 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1897 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1900 // fold (adde x, y, false) -> (addc x, y)
1901 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1902 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1907 // Since it may not be valid to emit a fold to zero for vector initializers
1908 // check if we can before folding.
1909 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1911 bool LegalOperations, bool LegalTypes) {
1913 return DAG.getConstant(0, DL, VT);
1914 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1915 return DAG.getConstant(0, DL, VT);
1919 SDValue DAGCombiner::visitSUB(SDNode *N) {
1920 SDValue N0 = N->getOperand(0);
1921 SDValue N1 = N->getOperand(1);
1922 EVT VT = N0.getValueType();
1925 if (VT.isVector()) {
1926 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1929 // fold (sub x, 0) -> x, vector edition
1930 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1934 // fold (sub x, x) -> 0
1935 // FIXME: Refactor this and xor and other similar operations together.
1937 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1938 // fold (sub c1, c2) -> c1-c2
1939 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1940 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1942 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1943 // fold (sub x, c) -> (add x, -c)
1946 return DAG.getNode(ISD::ADD, DL, VT, N0,
1947 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1949 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1950 if (isAllOnesConstant(N0))
1951 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1952 // fold A-(A-B) -> B
1953 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1954 return N1.getOperand(1);
1955 // fold (A+B)-A -> B
1956 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1957 return N0.getOperand(1);
1958 // fold (A+B)-B -> A
1959 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1960 return N0.getOperand(0);
1961 // fold C2-(A+C1) -> (C2-C1)-A
1962 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1963 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1964 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1966 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1968 return DAG.getNode(ISD::SUB, DL, VT, NewC,
1971 // fold ((A+(B+or-C))-B) -> A+or-C
1972 if (N0.getOpcode() == ISD::ADD &&
1973 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1974 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1975 N0.getOperand(1).getOperand(0) == N1)
1976 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1977 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1978 // fold ((A+(C+B))-B) -> A+C
1979 if (N0.getOpcode() == ISD::ADD &&
1980 N0.getOperand(1).getOpcode() == ISD::ADD &&
1981 N0.getOperand(1).getOperand(1) == N1)
1982 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1983 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1984 // fold ((A-(B-C))-C) -> A-B
1985 if (N0.getOpcode() == ISD::SUB &&
1986 N0.getOperand(1).getOpcode() == ISD::SUB &&
1987 N0.getOperand(1).getOperand(1) == N1)
1988 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1989 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1991 // If either operand of a sub is undef, the result is undef
1992 if (N0.getOpcode() == ISD::UNDEF)
1994 if (N1.getOpcode() == ISD::UNDEF)
1997 // If the relocation model supports it, consider symbol offsets.
1998 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1999 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2000 // fold (sub Sym, c) -> Sym-c
2001 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2002 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2004 (uint64_t)N1C->getSExtValue());
2005 // fold (sub Sym+c1, Sym+c2) -> c1-c2
2006 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2007 if (GA->getGlobal() == GB->getGlobal())
2008 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2012 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2013 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2014 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2015 if (TN->getVT() == MVT::i1) {
2017 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2018 DAG.getConstant(1, DL, VT));
2019 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2026 SDValue DAGCombiner::visitSUBC(SDNode *N) {
2027 SDValue N0 = N->getOperand(0);
2028 SDValue N1 = N->getOperand(1);
2029 EVT VT = N0.getValueType();
2032 // If the flag result is dead, turn this into an SUB.
2033 if (!N->hasAnyUseOfValue(1))
2034 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2035 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2037 // fold (subc x, x) -> 0 + no borrow
2039 return CombineTo(N, DAG.getConstant(0, DL, VT),
2040 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2042 // fold (subc x, 0) -> x + no borrow
2043 if (isNullConstant(N1))
2044 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2046 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2047 if (isAllOnesConstant(N0))
2048 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2049 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2054 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2055 SDValue N0 = N->getOperand(0);
2056 SDValue N1 = N->getOperand(1);
2057 SDValue CarryIn = N->getOperand(2);
2059 // fold (sube x, y, false) -> (subc x, y)
2060 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2061 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2066 SDValue DAGCombiner::visitMUL(SDNode *N) {
2067 SDValue N0 = N->getOperand(0);
2068 SDValue N1 = N->getOperand(1);
2069 EVT VT = N0.getValueType();
2071 // fold (mul x, undef) -> 0
2072 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2073 return DAG.getConstant(0, SDLoc(N), VT);
2075 bool N0IsConst = false;
2076 bool N1IsConst = false;
2077 bool N1IsOpaqueConst = false;
2078 bool N0IsOpaqueConst = false;
2079 APInt ConstValue0, ConstValue1;
2081 if (VT.isVector()) {
2082 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2085 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2086 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2088 N0IsConst = isa<ConstantSDNode>(N0);
2090 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2091 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2093 N1IsConst = isa<ConstantSDNode>(N1);
2095 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2096 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2100 // fold (mul c1, c2) -> c1*c2
2101 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2102 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2103 N0.getNode(), N1.getNode());
2105 // canonicalize constant to RHS (vector doesn't have to splat)
2106 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2107 !isConstantIntBuildVectorOrConstantInt(N1))
2108 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2109 // fold (mul x, 0) -> 0
2110 if (N1IsConst && ConstValue1 == 0)
2112 // We require a splat of the entire scalar bit width for non-contiguous
2115 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2116 // fold (mul x, 1) -> x
2117 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2119 // fold (mul x, -1) -> 0-x
2120 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2122 return DAG.getNode(ISD::SUB, DL, VT,
2123 DAG.getConstant(0, DL, VT), N0);
2125 // fold (mul x, (1 << c)) -> x << c
2126 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2129 return DAG.getNode(ISD::SHL, DL, VT, N0,
2130 DAG.getConstant(ConstValue1.logBase2(), DL,
2131 getShiftAmountTy(N0.getValueType())));
2133 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2134 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2136 unsigned Log2Val = (-ConstValue1).logBase2();
2138 // FIXME: If the input is something that is easily negated (e.g. a
2139 // single-use add), we should put the negate there.
2140 return DAG.getNode(ISD::SUB, DL, VT,
2141 DAG.getConstant(0, DL, VT),
2142 DAG.getNode(ISD::SHL, DL, VT, N0,
2143 DAG.getConstant(Log2Val, DL,
2144 getShiftAmountTy(N0.getValueType()))));
2148 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2149 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2150 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2151 isa<ConstantSDNode>(N0.getOperand(1)))) {
2152 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2153 N1, N0.getOperand(1));
2154 AddToWorklist(C3.getNode());
2155 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2156 N0.getOperand(0), C3);
2159 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2162 SDValue Sh(nullptr,0), Y(nullptr,0);
2163 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2164 if (N0.getOpcode() == ISD::SHL &&
2165 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2166 isa<ConstantSDNode>(N0.getOperand(1))) &&
2167 N0.getNode()->hasOneUse()) {
2169 } else if (N1.getOpcode() == ISD::SHL &&
2170 isa<ConstantSDNode>(N1.getOperand(1)) &&
2171 N1.getNode()->hasOneUse()) {
2176 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2177 Sh.getOperand(0), Y);
2178 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2179 Mul, Sh.getOperand(1));
2183 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2184 if (isConstantIntBuildVectorOrConstantInt(N1) &&
2185 N0.getOpcode() == ISD::ADD &&
2186 isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2187 isMulAddWithConstProfitable(N, N0, N1))
2188 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2189 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2190 N0.getOperand(0), N1),
2191 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2192 N0.getOperand(1), N1));
2195 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2201 /// Return true if divmod libcall is available.
2202 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2203 const TargetLowering &TLI) {
2205 switch (Node->getSimpleValueType(0).SimpleTy) {
2206 default: return false; // No libcall for vector types.
2207 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
2208 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2209 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2210 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2211 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2214 return TLI.getLibcallName(LC) != nullptr;
2217 /// Issue divrem if both quotient and remainder are needed.
2218 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2219 if (Node->use_empty())
2220 return SDValue(); // This is a dead node, leave it alone.
2222 EVT VT = Node->getValueType(0);
2223 if (!TLI.isTypeLegal(VT))
2226 unsigned Opcode = Node->getOpcode();
2227 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2229 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2230 // If DIVREM is going to get expanded into a libcall,
2231 // but there is no libcall available, then don't combine.
2232 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2233 !isDivRemLibcallAvailable(Node, isSigned, TLI))
2236 // If div is legal, it's better to do the normal expansion
2237 unsigned OtherOpcode = 0;
2238 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2239 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2240 if (TLI.isOperationLegalOrCustom(Opcode, VT))
2243 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2244 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2248 SDValue Op0 = Node->getOperand(0);
2249 SDValue Op1 = Node->getOperand(1);
2251 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2252 UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2254 if (User == Node || User->use_empty())
2256 // Convert the other matching node(s), too;
2257 // otherwise, the DIVREM may get target-legalized into something
2258 // target-specific that we won't be able to recognize.
2259 unsigned UserOpc = User->getOpcode();
2260 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2261 User->getOperand(0) == Op0 &&
2262 User->getOperand(1) == Op1) {
2264 if (UserOpc == OtherOpcode) {
2265 SDVTList VTs = DAG.getVTList(VT, VT);
2266 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2267 } else if (UserOpc == DivRemOpc) {
2268 combined = SDValue(User, 0);
2270 assert(UserOpc == Opcode);
2274 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2275 CombineTo(User, combined);
2276 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2277 CombineTo(User, combined.getValue(1));
2283 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2284 SDValue N0 = N->getOperand(0);
2285 SDValue N1 = N->getOperand(1);
2286 EVT VT = N->getValueType(0);
2290 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2295 // fold (sdiv c1, c2) -> c1/c2
2296 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2297 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2298 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2299 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2300 // fold (sdiv X, 1) -> X
2301 if (N1C && N1C->isOne())
2303 // fold (sdiv X, -1) -> 0-X
2304 if (N1C && N1C->isAllOnesValue())
2305 return DAG.getNode(ISD::SUB, DL, VT,
2306 DAG.getConstant(0, DL, VT), N0);
2308 // If we know the sign bits of both operands are zero, strength reduce to a
2309 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2310 if (!VT.isVector()) {
2311 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2312 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2315 // fold (sdiv X, pow2) -> simple ops after legalize
2316 // FIXME: We check for the exact bit here because the generic lowering gives
2317 // better results in that case. The target-specific lowering should learn how
2318 // to handle exact sdivs efficiently.
2319 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2320 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2321 (N1C->getAPIntValue().isPowerOf2() ||
2322 (-N1C->getAPIntValue()).isPowerOf2())) {
2323 // Target-specific implementation of sdiv x, pow2.
2324 if (SDValue Res = BuildSDIVPow2(N))
2327 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2329 // Splat the sign bit into the register
2331 DAG.getNode(ISD::SRA, DL, VT, N0,
2332 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2333 getShiftAmountTy(N0.getValueType())));
2334 AddToWorklist(SGN.getNode());
2336 // Add (N0 < 0) ? abs2 - 1 : 0;
2338 DAG.getNode(ISD::SRL, DL, VT, SGN,
2339 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2340 getShiftAmountTy(SGN.getValueType())));
2341 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2342 AddToWorklist(SRL.getNode());
2343 AddToWorklist(ADD.getNode()); // Divide by pow2
2344 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2345 DAG.getConstant(lg2, DL,
2346 getShiftAmountTy(ADD.getValueType())));
2348 // If we're dividing by a positive value, we're done. Otherwise, we must
2349 // negate the result.
2350 if (N1C->getAPIntValue().isNonNegative())
2353 AddToWorklist(SRA.getNode());
2354 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2357 // If integer divide is expensive and we satisfy the requirements, emit an
2358 // alternate sequence. Targets may check function attributes for size/speed
2360 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2361 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2362 if (SDValue Op = BuildSDIV(N))
2365 // sdiv, srem -> sdivrem
2366 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2367 // Otherwise, we break the simplification logic in visitREM().
2368 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2369 if (SDValue DivRem = useDivRem(N))
2373 if (N0.getOpcode() == ISD::UNDEF)
2374 return DAG.getConstant(0, DL, VT);
2375 // X / undef -> undef
2376 if (N1.getOpcode() == ISD::UNDEF)
2382 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2383 SDValue N0 = N->getOperand(0);
2384 SDValue N1 = N->getOperand(1);
2385 EVT VT = N->getValueType(0);
2389 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2394 // fold (udiv c1, c2) -> c1/c2
2395 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2396 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2398 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2401 // fold (udiv x, (1 << c)) -> x >>u c
2402 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2())
2403 return DAG.getNode(ISD::SRL, DL, VT, N0,
2404 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2405 getShiftAmountTy(N0.getValueType())));
2407 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2408 if (N1.getOpcode() == ISD::SHL) {
2409 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2410 if (SHC->getAPIntValue().isPowerOf2()) {
2411 EVT ADDVT = N1.getOperand(1).getValueType();
2412 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2414 DAG.getConstant(SHC->getAPIntValue()
2417 AddToWorklist(Add.getNode());
2418 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2423 // fold (udiv x, c) -> alternate
2424 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2425 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2426 if (SDValue Op = BuildUDIV(N))
2429 // sdiv, srem -> sdivrem
2430 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2431 // Otherwise, we break the simplification logic in visitREM().
2432 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2433 if (SDValue DivRem = useDivRem(N))
2437 if (N0.getOpcode() == ISD::UNDEF)
2438 return DAG.getConstant(0, DL, VT);
2439 // X / undef -> undef
2440 if (N1.getOpcode() == ISD::UNDEF)
2446 // handles ISD::SREM and ISD::UREM
2447 SDValue DAGCombiner::visitREM(SDNode *N) {
2448 unsigned Opcode = N->getOpcode();
2449 SDValue N0 = N->getOperand(0);
2450 SDValue N1 = N->getOperand(1);
2451 EVT VT = N->getValueType(0);
2452 bool isSigned = (Opcode == ISD::SREM);
2455 // fold (rem c1, c2) -> c1%c2
2456 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2457 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2459 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2463 // If we know the sign bits of both operands are zero, strength reduce to a
2464 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2465 if (!VT.isVector()) {
2466 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2467 return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2470 // fold (urem x, pow2) -> (and x, pow2-1)
2471 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2472 N1C->getAPIntValue().isPowerOf2()) {
2473 return DAG.getNode(ISD::AND, DL, VT, N0,
2474 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2476 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2477 if (N1.getOpcode() == ISD::SHL) {
2478 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2479 if (SHC->getAPIntValue().isPowerOf2()) {
2481 DAG.getNode(ISD::ADD, DL, VT, N1,
2482 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2484 AddToWorklist(Add.getNode());
2485 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2491 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2493 // If X/C can be simplified by the division-by-constant logic, lower
2494 // X%C to the equivalent of X-X/C*C.
2495 // To avoid mangling nodes, this simplification requires that the combine()
2496 // call for the speculative DIV must not cause a DIVREM conversion. We guard
2497 // against this by skipping the simplification if isIntDivCheap(). When
2498 // div is not cheap, combine will not return a DIVREM. Regardless,
2499 // checking cheapness here makes sense since the simplification results in
2501 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2502 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2503 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2504 AddToWorklist(Div.getNode());
2505 SDValue OptimizedDiv = combine(Div.getNode());
2506 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2507 assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2508 (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2509 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2510 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2511 AddToWorklist(Mul.getNode());
2516 // sdiv, srem -> sdivrem
2517 if (SDValue DivRem = useDivRem(N))
2518 return DivRem.getValue(1);
2521 if (N0.getOpcode() == ISD::UNDEF)
2522 return DAG.getConstant(0, DL, VT);
2523 // X % undef -> undef
2524 if (N1.getOpcode() == ISD::UNDEF)
2530 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2531 SDValue N0 = N->getOperand(0);
2532 SDValue N1 = N->getOperand(1);
2533 EVT VT = N->getValueType(0);
2536 // fold (mulhs x, 0) -> 0
2537 if (isNullConstant(N1))
2539 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2540 if (isOneConstant(N1)) {
2542 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2543 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2545 getShiftAmountTy(N0.getValueType())));
2547 // fold (mulhs x, undef) -> 0
2548 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2549 return DAG.getConstant(0, SDLoc(N), VT);
2551 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2553 if (VT.isSimple() && !VT.isVector()) {
2554 MVT Simple = VT.getSimpleVT();
2555 unsigned SimpleSize = Simple.getSizeInBits();
2556 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2557 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2558 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2559 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2560 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2561 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2562 DAG.getConstant(SimpleSize, DL,
2563 getShiftAmountTy(N1.getValueType())));
2564 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2571 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2572 SDValue N0 = N->getOperand(0);
2573 SDValue N1 = N->getOperand(1);
2574 EVT VT = N->getValueType(0);
2577 // fold (mulhu x, 0) -> 0
2578 if (isNullConstant(N1))
2580 // fold (mulhu x, 1) -> 0
2581 if (isOneConstant(N1))
2582 return DAG.getConstant(0, DL, N0.getValueType());
2583 // fold (mulhu x, undef) -> 0
2584 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2585 return DAG.getConstant(0, DL, VT);
2587 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2589 if (VT.isSimple() && !VT.isVector()) {
2590 MVT Simple = VT.getSimpleVT();
2591 unsigned SimpleSize = Simple.getSizeInBits();
2592 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2593 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2594 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2595 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2596 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2597 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2598 DAG.getConstant(SimpleSize, DL,
2599 getShiftAmountTy(N1.getValueType())));
2600 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2607 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2608 /// give the opcodes for the two computations that are being performed. Return
2609 /// true if a simplification was made.
2610 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2612 // If the high half is not needed, just compute the low half.
2613 bool HiExists = N->hasAnyUseOfValue(1);
2615 (!LegalOperations ||
2616 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2617 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2618 return CombineTo(N, Res, Res);
2621 // If the low half is not needed, just compute the high half.
2622 bool LoExists = N->hasAnyUseOfValue(0);
2624 (!LegalOperations ||
2625 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2626 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2627 return CombineTo(N, Res, Res);
2630 // If both halves are used, return as it is.
2631 if (LoExists && HiExists)
2634 // If the two computed results can be simplified separately, separate them.
2636 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2637 AddToWorklist(Lo.getNode());
2638 SDValue LoOpt = combine(Lo.getNode());
2639 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2640 (!LegalOperations ||
2641 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2642 return CombineTo(N, LoOpt, LoOpt);
2646 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2647 AddToWorklist(Hi.getNode());
2648 SDValue HiOpt = combine(Hi.getNode());
2649 if (HiOpt.getNode() && HiOpt != Hi &&
2650 (!LegalOperations ||
2651 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2652 return CombineTo(N, HiOpt, HiOpt);
2658 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2659 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2662 EVT VT = N->getValueType(0);
2665 // If the type is twice as wide is legal, transform the mulhu to a wider
2666 // multiply plus a shift.
2667 if (VT.isSimple() && !VT.isVector()) {
2668 MVT Simple = VT.getSimpleVT();
2669 unsigned SimpleSize = Simple.getSizeInBits();
2670 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2671 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2672 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2673 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2674 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2675 // Compute the high part as N1.
2676 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2677 DAG.getConstant(SimpleSize, DL,
2678 getShiftAmountTy(Lo.getValueType())));
2679 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2680 // Compute the low part as N0.
2681 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2682 return CombineTo(N, Lo, Hi);
2689 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2690 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2693 EVT VT = N->getValueType(0);
2696 // If the type is twice as wide is legal, transform the mulhu to a wider
2697 // multiply plus a shift.
2698 if (VT.isSimple() && !VT.isVector()) {
2699 MVT Simple = VT.getSimpleVT();
2700 unsigned SimpleSize = Simple.getSizeInBits();
2701 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2702 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2703 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2704 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2705 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2706 // Compute the high part as N1.
2707 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2708 DAG.getConstant(SimpleSize, DL,
2709 getShiftAmountTy(Lo.getValueType())));
2710 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2711 // Compute the low part as N0.
2712 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2713 return CombineTo(N, Lo, Hi);
2720 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2721 // (smulo x, 2) -> (saddo x, x)
2722 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2723 if (C2->getAPIntValue() == 2)
2724 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2725 N->getOperand(0), N->getOperand(0));
2730 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2731 // (umulo x, 2) -> (uaddo x, x)
2732 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2733 if (C2->getAPIntValue() == 2)
2734 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2735 N->getOperand(0), N->getOperand(0));
2740 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2741 SDValue N0 = N->getOperand(0);
2742 SDValue N1 = N->getOperand(1);
2743 EVT VT = N0.getValueType();
2747 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2750 // fold (add c1, c2) -> c1+c2
2751 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2752 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2754 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2756 // canonicalize constant to RHS
2757 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2758 !isConstantIntBuildVectorOrConstantInt(N1))
2759 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2764 /// If this is a binary operator with two operands of the same opcode, try to
2766 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2767 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2768 EVT VT = N0.getValueType();
2769 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2771 // Bail early if none of these transforms apply.
2772 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2774 // For each of OP in AND/OR/XOR:
2775 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2776 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2777 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2778 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2779 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2781 // do not sink logical op inside of a vector extend, since it may combine
2783 EVT Op0VT = N0.getOperand(0).getValueType();
2784 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2785 N0.getOpcode() == ISD::SIGN_EXTEND ||
2786 N0.getOpcode() == ISD::BSWAP ||
2787 // Avoid infinite looping with PromoteIntBinOp.
2788 (N0.getOpcode() == ISD::ANY_EXTEND &&
2789 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2790 (N0.getOpcode() == ISD::TRUNCATE &&
2791 (!TLI.isZExtFree(VT, Op0VT) ||
2792 !TLI.isTruncateFree(Op0VT, VT)) &&
2793 TLI.isTypeLegal(Op0VT))) &&
2795 Op0VT == N1.getOperand(0).getValueType() &&
2796 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2797 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2798 N0.getOperand(0).getValueType(),
2799 N0.getOperand(0), N1.getOperand(0));
2800 AddToWorklist(ORNode.getNode());
2801 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2804 // For each of OP in SHL/SRL/SRA/AND...
2805 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2806 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2807 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2808 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2809 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2810 N0.getOperand(1) == N1.getOperand(1)) {
2811 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2812 N0.getOperand(0).getValueType(),
2813 N0.getOperand(0), N1.getOperand(0));
2814 AddToWorklist(ORNode.getNode());
2815 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2816 ORNode, N0.getOperand(1));
2819 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2820 // Only perform this optimization after type legalization and before
2821 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2822 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2823 // we don't want to undo this promotion.
2824 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2826 if ((N0.getOpcode() == ISD::BITCAST ||
2827 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2828 Level == AfterLegalizeTypes) {
2829 SDValue In0 = N0.getOperand(0);
2830 SDValue In1 = N1.getOperand(0);
2831 EVT In0Ty = In0.getValueType();
2832 EVT In1Ty = In1.getValueType();
2834 // If both incoming values are integers, and the original types are the
2836 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2837 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2838 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2839 AddToWorklist(Op.getNode());
2844 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2845 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2846 // If both shuffles use the same mask, and both shuffle within a single
2847 // vector, then it is worthwhile to move the swizzle after the operation.
2848 // The type-legalizer generates this pattern when loading illegal
2849 // vector types from memory. In many cases this allows additional shuffle
2851 // There are other cases where moving the shuffle after the xor/and/or
2852 // is profitable even if shuffles don't perform a swizzle.
2853 // If both shuffles use the same mask, and both shuffles have the same first
2854 // or second operand, then it might still be profitable to move the shuffle
2855 // after the xor/and/or operation.
2856 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2857 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2858 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2860 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2861 "Inputs to shuffles are not the same type");
2863 // Check that both shuffles use the same mask. The masks are known to be of
2864 // the same length because the result vector type is the same.
2865 // Check also that shuffles have only one use to avoid introducing extra
2867 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2868 SVN0->getMask().equals(SVN1->getMask())) {
2869 SDValue ShOp = N0->getOperand(1);
2871 // Don't try to fold this node if it requires introducing a
2872 // build vector of all zeros that might be illegal at this stage.
2873 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2875 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2880 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2881 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2882 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2883 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2884 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2885 N0->getOperand(0), N1->getOperand(0));
2886 AddToWorklist(NewNode.getNode());
2887 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2888 &SVN0->getMask()[0]);
2891 // Don't try to fold this node if it requires introducing a
2892 // build vector of all zeros that might be illegal at this stage.
2893 ShOp = N0->getOperand(0);
2894 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2896 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2901 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2902 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2903 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2904 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2905 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2906 N0->getOperand(1), N1->getOperand(1));
2907 AddToWorklist(NewNode.getNode());
2908 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2909 &SVN0->getMask()[0]);
2917 /// This contains all DAGCombine rules which reduce two values combined by
2918 /// an And operation to a single value. This makes them reusable in the context
2919 /// of visitSELECT(). Rules involving constants are not included as
2920 /// visitSELECT() already handles those cases.
2921 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2922 SDNode *LocReference) {
2923 EVT VT = N1.getValueType();
2925 // fold (and x, undef) -> 0
2926 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2927 return DAG.getConstant(0, SDLoc(LocReference), VT);
2928 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2929 SDValue LL, LR, RL, RR, CC0, CC1;
2930 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2931 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2932 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2934 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2935 LL.getValueType().isInteger()) {
2936 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2937 if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2938 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2939 LR.getValueType(), LL, RL);
2940 AddToWorklist(ORNode.getNode());
2941 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2943 if (isAllOnesConstant(LR)) {
2944 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2945 if (Op1 == ISD::SETEQ) {
2946 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2947 LR.getValueType(), LL, RL);
2948 AddToWorklist(ANDNode.getNode());
2949 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2951 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2952 if (Op1 == ISD::SETGT) {
2953 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2954 LR.getValueType(), LL, RL);
2955 AddToWorklist(ORNode.getNode());
2956 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2960 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2961 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2962 Op0 == Op1 && LL.getValueType().isInteger() &&
2963 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2964 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2966 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2967 LL, DAG.getConstant(1, DL,
2968 LL.getValueType()));
2969 AddToWorklist(ADDNode.getNode());
2970 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2971 DAG.getConstant(2, DL, LL.getValueType()),
2974 // canonicalize equivalent to ll == rl
2975 if (LL == RR && LR == RL) {
2976 Op1 = ISD::getSetCCSwappedOperands(Op1);
2979 if (LL == RL && LR == RR) {
2980 bool isInteger = LL.getValueType().isInteger();
2981 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2982 if (Result != ISD::SETCC_INVALID &&
2983 (!LegalOperations ||
2984 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2985 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
2986 EVT CCVT = getSetCCResultType(LL.getValueType());
2987 if (N0.getValueType() == CCVT ||
2988 (!LegalOperations && N0.getValueType() == MVT::i1))
2989 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2995 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2996 VT.getSizeInBits() <= 64) {
2997 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2998 APInt ADDC = ADDI->getAPIntValue();
2999 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3000 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3001 // immediate for an add, but it is legal if its top c2 bits are set,
3002 // transform the ADD so the immediate doesn't need to be materialized
3004 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3005 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3006 SRLI->getZExtValue());
3007 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3009 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3012 DAG.getNode(ISD::ADD, DL, VT,
3013 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
3014 CombineTo(N0.getNode(), NewAdd);
3015 // Return N so it doesn't get rechecked!
3016 return SDValue(LocReference, 0);
3027 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3028 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
3030 uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
3032 if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue()))
3035 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3036 LoadedVT = LoadN->getMemoryVT();
3038 if (ExtVT == LoadedVT &&
3039 (!LegalOperations ||
3040 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3041 // ZEXTLOAD will match without needing to change the size of the value being
3047 // Do not change the width of a volatile load.
3048 if (LoadN->isVolatile())
3051 // Do not generate loads of non-round integer types since these can
3052 // be expensive (and would be wrong if the type is not byte sized).
3053 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3056 if (LegalOperations &&
3057 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3060 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3067 SDValue DAGCombiner::visitAND(SDNode *N) {
3068 SDValue N0 = N->getOperand(0);
3069 SDValue N1 = N->getOperand(1);
3070 EVT VT = N1.getValueType();
3073 if (VT.isVector()) {
3074 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3077 // fold (and x, 0) -> 0, vector edition
3078 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3079 // do not return N0, because undef node may exist in N0
3080 return DAG.getConstant(
3081 APInt::getNullValue(
3082 N0.getValueType().getScalarType().getSizeInBits()),
3083 SDLoc(N), N0.getValueType());
3084 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3085 // do not return N1, because undef node may exist in N1
3086 return DAG.getConstant(
3087 APInt::getNullValue(
3088 N1.getValueType().getScalarType().getSizeInBits()),
3089 SDLoc(N), N1.getValueType());
3091 // fold (and x, -1) -> x, vector edition
3092 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3094 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3098 // fold (and c1, c2) -> c1&c2
3099 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3100 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3102 // XXX-disabled: (and x, 0) should not be folded.
3103 if (!N0C && N1C->isNullValue()) {
3107 if (N0C && N1C && !N1C->isOpaque())
3108 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3109 // canonicalize constant to RHS
3110 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3111 !isConstantIntBuildVectorOrConstantInt(N1))
3112 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3113 // fold (and x, -1) -> x
3114 if (isAllOnesConstant(N1))
3116 // if (and x, c) is known to be zero, return 0
3117 unsigned BitWidth = VT.getScalarType().getSizeInBits();
3118 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3119 APInt::getAllOnesValue(BitWidth)))
3120 return DAG.getConstant(0, SDLoc(N), VT);
3122 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3124 // fold (and (or x, C), D) -> D if (C & D) == D
3125 if (N1C && N0.getOpcode() == ISD::OR)
3126 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3127 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3129 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3130 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3131 SDValue N0Op0 = N0.getOperand(0);
3132 APInt Mask = ~N1C->getAPIntValue();
3133 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
3134 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3135 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3136 N0.getValueType(), N0Op0);
3138 // Replace uses of the AND with uses of the Zero extend node.
3141 // We actually want to replace all uses of the any_extend with the
3142 // zero_extend, to avoid duplicating things. This will later cause this
3143 // AND to be folded.
3144 CombineTo(N0.getNode(), Zext);
3145 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3148 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3149 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3150 // already be zero by virtue of the width of the base type of the load.
3152 // the 'X' node here can either be nothing or an extract_vector_elt to catch
3154 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3155 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
3156 N0.getOpcode() == ISD::LOAD) {
3157 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3158 N0 : N0.getOperand(0) );
3160 // Get the constant (if applicable) the zero'th operand is being ANDed with.
3161 // This can be a pure constant or a vector splat, in which case we treat the
3162 // vector as a scalar and use the splat value.
3163 APInt Constant = APInt::getNullValue(1);
3164 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3165 Constant = C->getAPIntValue();
3166 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3167 APInt SplatValue, SplatUndef;
3168 unsigned SplatBitSize;
3170 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3171 SplatBitSize, HasAnyUndefs);
3173 // Undef bits can contribute to a possible optimisation if set, so
3175 SplatValue |= SplatUndef;
3177 // The splat value may be something like "0x00FFFFFF", which means 0 for
3178 // the first vector value and FF for the rest, repeating. We need a mask
3179 // that will apply equally to all members of the vector, so AND all the
3180 // lanes of the constant together.
3181 EVT VT = Vector->getValueType(0);
3182 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3184 // If the splat value has been compressed to a bitlength lower
3185 // than the size of the vector lane, we need to re-expand it to
3187 if (BitWidth > SplatBitSize)
3188 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3189 SplatBitSize < BitWidth;
3190 SplatBitSize = SplatBitSize * 2)
3191 SplatValue |= SplatValue.shl(SplatBitSize);
3193 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3194 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3195 if (SplatBitSize % BitWidth == 0) {
3196 Constant = APInt::getAllOnesValue(BitWidth);
3197 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3198 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3203 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3204 // actually legal and isn't going to get expanded, else this is a false
3206 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3207 Load->getValueType(0),
3208 Load->getMemoryVT());
3210 // Resize the constant to the same size as the original memory access before
3211 // extension. If it is still the AllOnesValue then this AND is completely
3214 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3217 switch (Load->getExtensionType()) {
3218 default: B = false; break;
3219 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3221 case ISD::NON_EXTLOAD: B = true; break;
3224 if (B && Constant.isAllOnesValue()) {
3225 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3226 // preserve semantics once we get rid of the AND.
3227 SDValue NewLoad(Load, 0);
3228 if (Load->getExtensionType() == ISD::EXTLOAD) {
3229 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3230 Load->getValueType(0), SDLoc(Load),
3231 Load->getChain(), Load->getBasePtr(),
3232 Load->getOffset(), Load->getMemoryVT(),
3233 Load->getMemOperand());
3234 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3235 if (Load->getNumValues() == 3) {
3236 // PRE/POST_INC loads have 3 values.
3237 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3238 NewLoad.getValue(2) };
3239 CombineTo(Load, To, 3, true);
3241 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3245 // Fold the AND away, taking care not to fold to the old load node if we
3247 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3249 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3253 // fold (and (load x), 255) -> (zextload x, i8)
3254 // fold (and (extload x, i16), 255) -> (zextload x, i8)
3255 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3256 if (N1C && (N0.getOpcode() == ISD::LOAD ||
3257 (N0.getOpcode() == ISD::ANY_EXTEND &&
3258 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3259 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3260 LoadSDNode *LN0 = HasAnyExt
3261 ? cast<LoadSDNode>(N0.getOperand(0))
3262 : cast<LoadSDNode>(N0);
3263 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3264 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3265 auto NarrowLoad = false;
3266 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3267 EVT ExtVT, LoadedVT;
3268 if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3272 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3273 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3274 LN0->getMemOperand());
3276 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3277 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3279 EVT PtrType = LN0->getOperand(1).getValueType();
3281 unsigned Alignment = LN0->getAlignment();
3282 SDValue NewPtr = LN0->getBasePtr();
3284 // For big endian targets, we need to add an offset to the pointer
3285 // to load the correct bytes. For little endian systems, we merely
3286 // need to read fewer bytes from the same pointer.
3287 if (DAG.getDataLayout().isBigEndian()) {
3288 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3289 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3290 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3292 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3293 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3294 Alignment = MinAlign(Alignment, PtrOff);
3297 AddToWorklist(NewPtr.getNode());
3300 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3301 LN0->getChain(), NewPtr,
3302 LN0->getPointerInfo(),
3303 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3304 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3306 CombineTo(LN0, Load, Load.getValue(1));
3307 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3313 if (SDValue Combined = visitANDLike(N0, N1, N))
3316 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3317 if (N0.getOpcode() == N1.getOpcode())
3318 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3321 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3322 // fold (and (sra)) -> (and (srl)) when possible.
3323 if (!VT.isVector() &&
3324 SimplifyDemandedBits(SDValue(N, 0)))
3325 return SDValue(N, 0);
3327 // fold (zext_inreg (extload x)) -> (zextload x)
3328 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3329 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3330 EVT MemVT = LN0->getMemoryVT();
3331 // If we zero all the possible extended bits, then we can turn this into
3332 // a zextload if we are running before legalize or the operation is legal.
3333 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3334 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3335 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3336 ((!LegalOperations && !LN0->isVolatile()) ||
3337 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3338 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3339 LN0->getChain(), LN0->getBasePtr(),
3340 MemVT, LN0->getMemOperand());
3342 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3343 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3346 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3347 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3349 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3350 EVT MemVT = LN0->getMemoryVT();
3351 // If we zero all the possible extended bits, then we can turn this into
3352 // a zextload if we are running before legalize or the operation is legal.
3353 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3354 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3355 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3356 ((!LegalOperations && !LN0->isVolatile()) ||
3357 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3358 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3359 LN0->getChain(), LN0->getBasePtr(),
3360 MemVT, LN0->getMemOperand());
3362 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3363 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3366 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3367 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3368 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3369 N0.getOperand(1), false);
3370 if (BSwap.getNode())
3377 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3378 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3379 bool DemandHighBits) {
3380 if (!LegalOperations)
3383 EVT VT = N->getValueType(0);
3384 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3386 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3389 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3390 bool LookPassAnd0 = false;
3391 bool LookPassAnd1 = false;
3392 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3394 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3396 if (N0.getOpcode() == ISD::AND) {
3397 if (!N0.getNode()->hasOneUse())
3399 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3400 if (!N01C || N01C->getZExtValue() != 0xFF00)
3402 N0 = N0.getOperand(0);
3403 LookPassAnd0 = true;
3406 if (N1.getOpcode() == ISD::AND) {
3407 if (!N1.getNode()->hasOneUse())
3409 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3410 if (!N11C || N11C->getZExtValue() != 0xFF)
3412 N1 = N1.getOperand(0);
3413 LookPassAnd1 = true;
3416 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3418 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3420 if (!N0.getNode()->hasOneUse() ||
3421 !N1.getNode()->hasOneUse())
3424 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3425 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3428 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3431 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3432 SDValue N00 = N0->getOperand(0);
3433 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3434 if (!N00.getNode()->hasOneUse())
3436 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3437 if (!N001C || N001C->getZExtValue() != 0xFF)
3439 N00 = N00.getOperand(0);
3440 LookPassAnd0 = true;
3443 SDValue N10 = N1->getOperand(0);
3444 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3445 if (!N10.getNode()->hasOneUse())
3447 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3448 if (!N101C || N101C->getZExtValue() != 0xFF00)
3450 N10 = N10.getOperand(0);
3451 LookPassAnd1 = true;
3457 // Make sure everything beyond the low halfword gets set to zero since the SRL
3458 // 16 will clear the top bits.
3459 unsigned OpSizeInBits = VT.getSizeInBits();
3460 if (DemandHighBits && OpSizeInBits > 16) {
3461 // If the left-shift isn't masked out then the only way this is a bswap is
3462 // if all bits beyond the low 8 are 0. In that case the entire pattern
3463 // reduces to a left shift anyway: leave it for other parts of the combiner.
3467 // However, if the right shift isn't masked out then it might be because
3468 // it's not needed. See if we can spot that too.
3469 if (!LookPassAnd1 &&
3470 !DAG.MaskedValueIsZero(
3471 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3475 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3476 if (OpSizeInBits > 16) {
3478 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3479 DAG.getConstant(OpSizeInBits - 16, DL,
3480 getShiftAmountTy(VT)));
3485 /// Return true if the specified node is an element that makes up a 32-bit
3486 /// packed halfword byteswap.
3487 /// ((x & 0x000000ff) << 8) |
3488 /// ((x & 0x0000ff00) >> 8) |
3489 /// ((x & 0x00ff0000) << 8) |
3490 /// ((x & 0xff000000) >> 8)
3491 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3492 if (!N.getNode()->hasOneUse())
3495 unsigned Opc = N.getOpcode();
3496 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3499 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3504 switch (N1C->getZExtValue()) {
3507 case 0xFF: Num = 0; break;
3508 case 0xFF00: Num = 1; break;
3509 case 0xFF0000: Num = 2; break;
3510 case 0xFF000000: Num = 3; break;
3513 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3514 SDValue N0 = N.getOperand(0);
3515 if (Opc == ISD::AND) {
3516 if (Num == 0 || Num == 2) {
3518 // (x >> 8) & 0xff0000
3519 if (N0.getOpcode() != ISD::SRL)
3521 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3522 if (!C || C->getZExtValue() != 8)
3525 // (x << 8) & 0xff00
3526 // (x << 8) & 0xff000000
3527 if (N0.getOpcode() != ISD::SHL)
3529 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3530 if (!C || C->getZExtValue() != 8)
3533 } else if (Opc == ISD::SHL) {
3535 // (x & 0xff0000) << 8
3536 if (Num != 0 && Num != 2)
3538 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3539 if (!C || C->getZExtValue() != 8)
3541 } else { // Opc == ISD::SRL
3542 // (x & 0xff00) >> 8
3543 // (x & 0xff000000) >> 8
3544 if (Num != 1 && Num != 3)
3546 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3547 if (!C || C->getZExtValue() != 8)
3554 Parts[Num] = N0.getOperand(0).getNode();
3558 /// Match a 32-bit packed halfword bswap. That is
3559 /// ((x & 0x000000ff) << 8) |
3560 /// ((x & 0x0000ff00) >> 8) |
3561 /// ((x & 0x00ff0000) << 8) |
3562 /// ((x & 0xff000000) >> 8)
3563 /// => (rotl (bswap x), 16)
3564 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3565 if (!LegalOperations)
3568 EVT VT = N->getValueType(0);
3571 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3575 // (or (or (and), (and)), (or (and), (and)))
3576 // (or (or (or (and), (and)), (and)), (and))
3577 if (N0.getOpcode() != ISD::OR)
3579 SDValue N00 = N0.getOperand(0);
3580 SDValue N01 = N0.getOperand(1);
3581 SDNode *Parts[4] = {};
3583 if (N1.getOpcode() == ISD::OR &&
3584 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3585 // (or (or (and), (and)), (or (and), (and)))
3586 SDValue N000 = N00.getOperand(0);
3587 if (!isBSwapHWordElement(N000, Parts))
3590 SDValue N001 = N00.getOperand(1);
3591 if (!isBSwapHWordElement(N001, Parts))
3593 SDValue N010 = N01.getOperand(0);
3594 if (!isBSwapHWordElement(N010, Parts))
3596 SDValue N011 = N01.getOperand(1);
3597 if (!isBSwapHWordElement(N011, Parts))
3600 // (or (or (or (and), (and)), (and)), (and))
3601 if (!isBSwapHWordElement(N1, Parts))
3603 if (!isBSwapHWordElement(N01, Parts))
3605 if (N00.getOpcode() != ISD::OR)
3607 SDValue N000 = N00.getOperand(0);
3608 if (!isBSwapHWordElement(N000, Parts))
3610 SDValue N001 = N00.getOperand(1);
3611 if (!isBSwapHWordElement(N001, Parts))
3615 // Make sure the parts are all coming from the same node.
3616 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3620 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3621 SDValue(Parts[0], 0));
3623 // Result of the bswap should be rotated by 16. If it's not legal, then
3624 // do (x << 16) | (x >> 16).
3625 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3626 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3627 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3628 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3629 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3630 return DAG.getNode(ISD::OR, DL, VT,
3631 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3632 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3635 /// This contains all DAGCombine rules which reduce two values combined by
3636 /// an Or operation to a single value \see visitANDLike().
3637 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3638 EVT VT = N1.getValueType();
3639 // fold (or x, undef) -> -1
3640 if (!LegalOperations &&
3641 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3642 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3643 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3644 SDLoc(LocReference), VT);
3646 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3647 SDValue LL, LR, RL, RR, CC0, CC1;
3648 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3649 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3650 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3652 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3653 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3654 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3655 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3656 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3657 LR.getValueType(), LL, RL);
3658 AddToWorklist(ORNode.getNode());
3659 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3661 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3662 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3663 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3664 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3665 LR.getValueType(), LL, RL);
3666 AddToWorklist(ANDNode.getNode());
3667 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3670 // canonicalize equivalent to ll == rl
3671 if (LL == RR && LR == RL) {
3672 Op1 = ISD::getSetCCSwappedOperands(Op1);
3675 if (LL == RL && LR == RR) {
3676 bool isInteger = LL.getValueType().isInteger();
3677 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3678 if (Result != ISD::SETCC_INVALID &&
3679 (!LegalOperations ||
3680 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3681 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3682 EVT CCVT = getSetCCResultType(LL.getValueType());
3683 if (N0.getValueType() == CCVT ||
3684 (!LegalOperations && N0.getValueType() == MVT::i1))
3685 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3691 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3692 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3693 // Don't increase # computations.
3694 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3695 // We can only do this xform if we know that bits from X that are set in C2
3696 // but not in C1 are already zero. Likewise for Y.
3697 if (const ConstantSDNode *N0O1C =
3698 getAsNonOpaqueConstant(N0.getOperand(1))) {
3699 if (const ConstantSDNode *N1O1C =
3700 getAsNonOpaqueConstant(N1.getOperand(1))) {
3701 // We can only do this xform if we know that bits from X that are set in
3702 // C2 but not in C1 are already zero. Likewise for Y.
3703 const APInt &LHSMask = N0O1C->getAPIntValue();
3704 const APInt &RHSMask = N1O1C->getAPIntValue();
3706 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3707 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3708 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3709 N0.getOperand(0), N1.getOperand(0));
3710 SDLoc DL(LocReference);
3711 return DAG.getNode(ISD::AND, DL, VT, X,
3712 DAG.getConstant(LHSMask | RHSMask, DL, VT));
3718 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3719 if (N0.getOpcode() == ISD::AND &&
3720 N1.getOpcode() == ISD::AND &&
3721 N0.getOperand(0) == N1.getOperand(0) &&
3722 // Don't increase # computations.
3723 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3724 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3725 N0.getOperand(1), N1.getOperand(1));
3726 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3732 SDValue DAGCombiner::visitOR(SDNode *N) {
3733 SDValue N0 = N->getOperand(0);
3734 SDValue N1 = N->getOperand(1);
3735 EVT VT = N1.getValueType();
3738 if (VT.isVector()) {
3739 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3742 // fold (or x, 0) -> x, vector edition
3743 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3745 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3748 // fold (or x, -1) -> -1, vector edition
3749 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3750 // do not return N0, because undef node may exist in N0
3751 return DAG.getConstant(
3752 APInt::getAllOnesValue(
3753 N0.getValueType().getScalarType().getSizeInBits()),
3754 SDLoc(N), N0.getValueType());
3755 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3756 // do not return N1, because undef node may exist in N1
3757 return DAG.getConstant(
3758 APInt::getAllOnesValue(
3759 N1.getValueType().getScalarType().getSizeInBits()),
3760 SDLoc(N), N1.getValueType());
3762 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3763 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3764 // Do this only if the resulting shuffle is legal.
3765 if (isa<ShuffleVectorSDNode>(N0) &&
3766 isa<ShuffleVectorSDNode>(N1) &&
3767 // Avoid folding a node with illegal type.
3768 TLI.isTypeLegal(VT) &&
3769 N0->getOperand(1) == N1->getOperand(1) &&
3770 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3771 bool CanFold = true;
3772 unsigned NumElts = VT.getVectorNumElements();
3773 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3774 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3775 // We construct two shuffle masks:
3776 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3777 // and N1 as the second operand.
3778 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3779 // and N0 as the second operand.
3780 // We do this because OR is commutable and therefore there might be
3781 // two ways to fold this node into a shuffle.
3782 SmallVector<int,4> Mask1;
3783 SmallVector<int,4> Mask2;
3785 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3786 int M0 = SV0->getMaskElt(i);
3787 int M1 = SV1->getMaskElt(i);
3789 // Both shuffle indexes are undef. Propagate Undef.
3790 if (M0 < 0 && M1 < 0) {
3791 Mask1.push_back(M0);
3792 Mask2.push_back(M0);
3796 if (M0 < 0 || M1 < 0 ||
3797 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3798 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3803 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3804 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3808 // Fold this sequence only if the resulting shuffle is 'legal'.
3809 if (TLI.isShuffleMaskLegal(Mask1, VT))
3810 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3811 N1->getOperand(0), &Mask1[0]);
3812 if (TLI.isShuffleMaskLegal(Mask2, VT))
3813 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3814 N0->getOperand(0), &Mask2[0]);
3819 // fold (or c1, c2) -> c1|c2
3820 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3821 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3822 if (N0C && N1C && !N1C->isOpaque())
3823 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3824 // canonicalize constant to RHS
3825 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3826 !isConstantIntBuildVectorOrConstantInt(N1))
3827 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3828 // fold (or x, 0) -> x
3829 if (isNullConstant(N1))
3831 // fold (or x, -1) -> -1
3832 if (isAllOnesConstant(N1))
3834 // fold (or x, c) -> c iff (x & ~c) == 0
3835 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3838 if (SDValue Combined = visitORLike(N0, N1, N))
3841 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3842 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3844 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3848 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3850 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3851 // iff (c1 & c2) == 0.
3852 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3853 isa<ConstantSDNode>(N0.getOperand(1))) {
3854 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3855 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3856 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3859 ISD::AND, SDLoc(N), VT,
3860 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3864 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3865 if (N0.getOpcode() == N1.getOpcode())
3866 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3869 // See if this is some rotate idiom.
3870 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3871 return SDValue(Rot, 0);
3873 // Simplify the operands using demanded-bits information.
3874 if (!VT.isVector() &&
3875 SimplifyDemandedBits(SDValue(N, 0)))
3876 return SDValue(N, 0);
3881 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3882 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3883 if (Op.getOpcode() == ISD::AND) {
3884 if (isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
3885 Mask = Op.getOperand(1);
3886 Op = Op.getOperand(0);
3892 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3900 // Return true if we can prove that, whenever Neg and Pos are both in the
3901 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that
3902 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3904 // (or (shift1 X, Neg), (shift2 X, Pos))
3906 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3907 // in direction shift1 by Neg. The range [0, EltSize) means that we only need
3908 // to consider shift amounts with defined behavior.
3909 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
3910 // If EltSize is a power of 2 then:
3912 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
3913 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
3915 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
3916 // for the stronger condition:
3918 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A]
3920 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
3921 // we can just replace Neg with Neg' for the rest of the function.
3923 // In other cases we check for the even stronger condition:
3925 // Neg == EltSize - Pos [B]
3927 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3928 // behavior if Pos == 0 (and consequently Neg == EltSize).
3930 // We could actually use [A] whenever EltSize is a power of 2, but the
3931 // only extra cases that it would match are those uninteresting ones
3932 // where Neg and Pos are never in range at the same time. E.g. for
3933 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3934 // as well as (sub 32, Pos), but:
3936 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3938 // always invokes undefined behavior for 32-bit X.
3940 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
3941 unsigned MaskLoBits = 0;
3942 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
3943 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
3944 if (NegC->getAPIntValue() == EltSize - 1) {
3945 Neg = Neg.getOperand(0);
3946 MaskLoBits = Log2_64(EltSize);
3951 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3952 if (Neg.getOpcode() != ISD::SUB)
3954 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
3957 SDValue NegOp1 = Neg.getOperand(1);
3959 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
3960 // Pos'. The truncation is redundant for the purpose of the equality.
3961 if (MaskLoBits && Pos.getOpcode() == ISD::AND)
3962 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3963 if (PosC->getAPIntValue() == EltSize - 1)
3964 Pos = Pos.getOperand(0);
3966 // The condition we need is now:
3968 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
3970 // If NegOp1 == Pos then we need:
3972 // EltSize & Mask == NegC & Mask
3974 // (because "x & Mask" is a truncation and distributes through subtraction).
3977 Width = NegC->getAPIntValue();
3979 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3980 // Then the condition we want to prove becomes:
3982 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
3984 // which, again because "x & Mask" is a truncation, becomes:
3986 // NegC & Mask == (EltSize - PosC) & Mask
3987 // EltSize & Mask == (NegC + PosC) & Mask
3988 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
3989 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3990 Width = PosC->getAPIntValue() + NegC->getAPIntValue();
3996 // Now we just need to check that EltSize & Mask == Width & Mask.
3998 // EltSize & Mask is 0 since Mask is EltSize - 1.
3999 return Width.getLoBits(MaskLoBits) == 0;
4000 return Width == EltSize;
4003 // A subroutine of MatchRotate used once we have found an OR of two opposite
4004 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
4005 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4006 // former being preferred if supported. InnerPos and InnerNeg are Pos and
4007 // Neg with outer conversions stripped away.
4008 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4009 SDValue Neg, SDValue InnerPos,
4010 SDValue InnerNeg, unsigned PosOpcode,
4011 unsigned NegOpcode, SDLoc DL) {
4012 // fold (or (shl x, (*ext y)),
4013 // (srl x, (*ext (sub 32, y)))) ->
4014 // (rotl x, y) or (rotr x, (sub 32, y))
4016 // fold (or (shl x, (*ext (sub 32, y))),
4017 // (srl x, (*ext y))) ->
4018 // (rotr x, y) or (rotl x, (sub 32, y))
4019 EVT VT = Shifted.getValueType();
4020 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4021 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4022 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4023 HasPos ? Pos : Neg).getNode();
4029 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
4030 // idioms for rotate, and if the target supports rotation instructions, generate
4032 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
4033 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
4034 EVT VT = LHS.getValueType();
4035 if (!TLI.isTypeLegal(VT)) return nullptr;
4037 // The target must have at least one rotate flavor.
4038 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4039 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4040 if (!HasROTL && !HasROTR) return nullptr;
4042 // Match "(X shl/srl V1) & V2" where V2 may not be present.
4043 SDValue LHSShift; // The shift.
4044 SDValue LHSMask; // AND value if any.
4045 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4046 return nullptr; // Not part of a rotate.
4048 SDValue RHSShift; // The shift.
4049 SDValue RHSMask; // AND value if any.
4050 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4051 return nullptr; // Not part of a rotate.
4053 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4054 return nullptr; // Not shifting the same value.
4056 if (LHSShift.getOpcode() == RHSShift.getOpcode())
4057 return nullptr; // Shifts must disagree.
4059 // Canonicalize shl to left side in a shl/srl pair.
4060 if (RHSShift.getOpcode() == ISD::SHL) {
4061 std::swap(LHS, RHS);
4062 std::swap(LHSShift, RHSShift);
4063 std::swap(LHSMask, RHSMask);
4066 unsigned EltSizeInBits = VT.getScalarSizeInBits();
4067 SDValue LHSShiftArg = LHSShift.getOperand(0);
4068 SDValue LHSShiftAmt = LHSShift.getOperand(1);
4069 SDValue RHSShiftArg = RHSShift.getOperand(0);
4070 SDValue RHSShiftAmt = RHSShift.getOperand(1);
4072 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4073 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4074 if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4075 uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4076 uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4077 if ((LShVal + RShVal) != EltSizeInBits)
4080 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4081 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4083 // If there is an AND of either shifted operand, apply it to the result.
4084 if (LHSMask.getNode() || RHSMask.getNode()) {
4085 APInt AllBits = APInt::getAllOnesValue(EltSizeInBits);
4086 SDValue Mask = DAG.getConstant(AllBits, DL, VT);
4088 if (LHSMask.getNode()) {
4089 APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4090 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4091 DAG.getNode(ISD::OR, DL, VT, LHSMask,
4092 DAG.getConstant(RHSBits, DL, VT)));
4094 if (RHSMask.getNode()) {
4095 APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4096 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4097 DAG.getNode(ISD::OR, DL, VT, RHSMask,
4098 DAG.getConstant(LHSBits, DL, VT)));
4101 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4104 return Rot.getNode();
4107 // If there is a mask here, and we have a variable shift, we can't be sure
4108 // that we're masking out the right stuff.
4109 if (LHSMask.getNode() || RHSMask.getNode())
4112 // If the shift amount is sign/zext/any-extended just peel it off.
4113 SDValue LExtOp0 = LHSShiftAmt;
4114 SDValue RExtOp0 = RHSShiftAmt;
4115 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4116 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4117 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4118 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4119 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4120 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4121 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4122 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4123 LExtOp0 = LHSShiftAmt.getOperand(0);
4124 RExtOp0 = RHSShiftAmt.getOperand(0);
4127 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4128 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4132 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4133 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4140 SDValue DAGCombiner::visitXOR(SDNode *N) {
4141 SDValue N0 = N->getOperand(0);
4142 SDValue N1 = N->getOperand(1);
4143 EVT VT = N0.getValueType();
4146 if (VT.isVector()) {
4147 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4150 // fold (xor x, 0) -> x, vector edition
4151 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4153 if (ISD::isBuildVectorAllZeros(N1.getNode()))
4157 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4158 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
4159 return DAG.getConstant(0, SDLoc(N), VT);
4160 // fold (xor x, undef) -> undef
4161 if (N0.getOpcode() == ISD::UNDEF)
4163 if (N1.getOpcode() == ISD::UNDEF)
4165 // fold (xor c1, c2) -> c1^c2
4166 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4167 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4169 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4170 // canonicalize constant to RHS
4171 if (isConstantIntBuildVectorOrConstantInt(N0) &&
4172 !isConstantIntBuildVectorOrConstantInt(N1))
4173 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4174 // fold (xor x, 0) -> x
4175 if (isNullConstant(N1))
4178 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4181 // fold !(x cc y) -> (x !cc y)
4182 SDValue LHS, RHS, CC;
4183 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4184 bool isInt = LHS.getValueType().isInteger();
4185 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4188 if (!LegalOperations ||
4189 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4190 switch (N0.getOpcode()) {
4192 llvm_unreachable("Unhandled SetCC Equivalent!");
4194 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4195 case ISD::SELECT_CC:
4196 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4197 N0.getOperand(3), NotCC);
4202 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4203 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4204 N0.getNode()->hasOneUse() &&
4205 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4206 SDValue V = N0.getOperand(0);
4208 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4209 DAG.getConstant(1, DL, V.getValueType()));
4210 AddToWorklist(V.getNode());
4211 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4214 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4215 if (isOneConstant(N1) && VT == MVT::i1 &&
4216 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4217 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4218 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4219 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4220 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4221 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4222 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4223 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4226 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4227 if (isAllOnesConstant(N1) &&
4228 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4229 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4230 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4231 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4232 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4233 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4234 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4235 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4238 // fold (xor (and x, y), y) -> (and (not x), y)
4239 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4240 N0->getOperand(1) == N1) {
4241 SDValue X = N0->getOperand(0);
4242 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4243 AddToWorklist(NotX.getNode());
4244 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4246 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4247 if (N1C && N0.getOpcode() == ISD::XOR) {
4248 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4250 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4251 DAG.getConstant(N1C->getAPIntValue() ^
4252 N00C->getAPIntValue(), DL, VT));
4254 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4256 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4257 DAG.getConstant(N1C->getAPIntValue() ^
4258 N01C->getAPIntValue(), DL, VT));
4261 // fold (xor x, x) -> 0
4263 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4265 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4266 // Here is a concrete example of this equivalence:
4268 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
4269 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4273 // i16 ~1 == 0b1111111111111110
4274 // i16 rol(~1, 14) == 0b1011111111111111
4276 // Some additional tips to help conceptualize this transform:
4277 // - Try to see the operation as placing a single zero in a value of all ones.
4278 // - There exists no value for x which would allow the result to contain zero.
4279 // - Values of x larger than the bitwidth are undefined and do not require a
4280 // consistent result.
4281 // - Pushing the zero left requires shifting one bits in from the right.
4282 // A rotate left of ~1 is a nice way of achieving the desired result.
4283 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4284 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4286 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4290 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4291 if (N0.getOpcode() == N1.getOpcode())
4292 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4295 // Simplify the expression using non-local knowledge.
4296 if (!VT.isVector() &&
4297 SimplifyDemandedBits(SDValue(N, 0)))
4298 return SDValue(N, 0);
4303 /// Handle transforms common to the three shifts, when the shift amount is a
4305 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4306 SDNode *LHS = N->getOperand(0).getNode();
4307 if (!LHS->hasOneUse()) return SDValue();
4309 // We want to pull some binops through shifts, so that we have (and (shift))
4310 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4311 // thing happens with address calculations, so it's important to canonicalize
4313 bool HighBitSet = false; // Can we transform this if the high bit is set?
4315 switch (LHS->getOpcode()) {
4316 default: return SDValue();
4319 HighBitSet = false; // We can only transform sra if the high bit is clear.
4322 HighBitSet = true; // We can only transform sra if the high bit is set.
4325 if (N->getOpcode() != ISD::SHL)
4326 return SDValue(); // only shl(add) not sr[al](add).
4327 HighBitSet = false; // We can only transform sra if the high bit is clear.
4331 // We require the RHS of the binop to be a constant and not opaque as well.
4332 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4333 if (!BinOpCst) return SDValue();
4335 // FIXME: disable this unless the input to the binop is a shift by a constant.
4336 // If it is not a shift, it pessimizes some common cases like:
4338 // void foo(int *X, int i) { X[i & 1235] = 1; }
4339 // int bar(int *X, int i) { return X[i & 255]; }
4340 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4341 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4342 BinOpLHSVal->getOpcode() != ISD::SRA &&
4343 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4344 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4347 EVT VT = N->getValueType(0);
4349 // If this is a signed shift right, and the high bit is modified by the
4350 // logical operation, do not perform the transformation. The highBitSet
4351 // boolean indicates the value of the high bit of the constant which would
4352 // cause it to be modified for this operation.
4353 if (N->getOpcode() == ISD::SRA) {
4354 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4355 if (BinOpRHSSignSet != HighBitSet)
4359 if (!TLI.isDesirableToCommuteWithShift(LHS))
4362 // Fold the constants, shifting the binop RHS by the shift amount.
4363 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4365 LHS->getOperand(1), N->getOperand(1));
4366 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4368 // Create the new shift.
4369 SDValue NewShift = DAG.getNode(N->getOpcode(),
4370 SDLoc(LHS->getOperand(0)),
4371 VT, LHS->getOperand(0), N->getOperand(1));
4373 // Create the new binop.
4374 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4377 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4378 assert(N->getOpcode() == ISD::TRUNCATE);
4379 assert(N->getOperand(0).getOpcode() == ISD::AND);
4381 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4382 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4383 SDValue N01 = N->getOperand(0).getOperand(1);
4385 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4386 if (!N01C->isOpaque()) {
4387 EVT TruncVT = N->getValueType(0);
4388 SDValue N00 = N->getOperand(0).getOperand(0);
4389 APInt TruncC = N01C->getAPIntValue();
4390 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4393 return DAG.getNode(ISD::AND, DL, TruncVT,
4394 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4395 DAG.getConstant(TruncC, DL, TruncVT));
4403 SDValue DAGCombiner::visitRotate(SDNode *N) {
4404 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4405 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4406 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4407 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4408 if (NewOp1.getNode())
4409 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4410 N->getOperand(0), NewOp1);
4415 SDValue DAGCombiner::visitSHL(SDNode *N) {
4416 SDValue N0 = N->getOperand(0);
4417 SDValue N1 = N->getOperand(1);
4418 EVT VT = N0.getValueType();
4419 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4422 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4423 if (VT.isVector()) {
4424 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4427 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4428 // If setcc produces all-one true value then:
4429 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4430 if (N1CV && N1CV->isConstant()) {
4431 if (N0.getOpcode() == ISD::AND) {
4432 SDValue N00 = N0->getOperand(0);
4433 SDValue N01 = N0->getOperand(1);
4434 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4436 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4437 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4438 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4439 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4441 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4444 N1C = isConstOrConstSplat(N1);
4449 // fold (shl c1, c2) -> c1<<c2
4450 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4451 if (N0C && N1C && !N1C->isOpaque())
4452 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4453 // fold (shl 0, x) -> 0
4454 if (isNullConstant(N0))
4456 // fold (shl x, c >= size(x)) -> undef
4457 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4458 return DAG.getUNDEF(VT);
4459 // fold (shl x, 0) -> x
4460 if (N1C && N1C->isNullValue())
4462 // fold (shl undef, x) -> 0
4463 if (N0.getOpcode() == ISD::UNDEF)
4464 return DAG.getConstant(0, SDLoc(N), VT);
4465 // if (shl x, c) is known to be zero, return 0
4466 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4467 APInt::getAllOnesValue(OpSizeInBits)))
4468 return DAG.getConstant(0, SDLoc(N), VT);
4469 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4470 if (N1.getOpcode() == ISD::TRUNCATE &&
4471 N1.getOperand(0).getOpcode() == ISD::AND) {
4472 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4473 if (NewOp1.getNode())
4474 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4477 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4478 return SDValue(N, 0);
4480 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4481 if (N1C && N0.getOpcode() == ISD::SHL) {
4482 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4483 uint64_t c1 = N0C1->getZExtValue();
4484 uint64_t c2 = N1C->getZExtValue();
4486 if (c1 + c2 >= OpSizeInBits)
4487 return DAG.getConstant(0, DL, VT);
4488 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4489 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4493 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4494 // For this to be valid, the second form must not preserve any of the bits
4495 // that are shifted out by the inner shift in the first form. This means
4496 // the outer shift size must be >= the number of bits added by the ext.
4497 // As a corollary, we don't care what kind of ext it is.
4498 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4499 N0.getOpcode() == ISD::ANY_EXTEND ||
4500 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4501 N0.getOperand(0).getOpcode() == ISD::SHL) {
4502 SDValue N0Op0 = N0.getOperand(0);
4503 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4504 uint64_t c1 = N0Op0C1->getZExtValue();
4505 uint64_t c2 = N1C->getZExtValue();
4506 EVT InnerShiftVT = N0Op0.getValueType();
4507 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4508 if (c2 >= OpSizeInBits - InnerShiftSize) {
4510 if (c1 + c2 >= OpSizeInBits)
4511 return DAG.getConstant(0, DL, VT);
4512 return DAG.getNode(ISD::SHL, DL, VT,
4513 DAG.getNode(N0.getOpcode(), DL, VT,
4514 N0Op0->getOperand(0)),
4515 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4520 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4521 // Only fold this if the inner zext has no other uses to avoid increasing
4522 // the total number of instructions.
4523 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4524 N0.getOperand(0).getOpcode() == ISD::SRL) {
4525 SDValue N0Op0 = N0.getOperand(0);
4526 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4527 uint64_t c1 = N0Op0C1->getZExtValue();
4528 if (c1 < VT.getScalarSizeInBits()) {
4529 uint64_t c2 = N1C->getZExtValue();
4531 SDValue NewOp0 = N0.getOperand(0);
4532 EVT CountVT = NewOp0.getOperand(1).getValueType();
4534 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4536 DAG.getConstant(c2, DL, CountVT));
4537 AddToWorklist(NewSHL.getNode());
4538 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4544 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
4545 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2
4546 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4547 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4548 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4549 uint64_t C1 = N0C1->getZExtValue();
4550 uint64_t C2 = N1C->getZExtValue();
4553 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4554 DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4555 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4556 DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4560 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4561 // (and (srl x, (sub c1, c2), MASK)
4562 // Only fold this if the inner shift has no other uses -- if it does, folding
4563 // this will increase the total number of instructions.
4564 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4565 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4566 uint64_t c1 = N0C1->getZExtValue();
4567 if (c1 < OpSizeInBits) {
4568 uint64_t c2 = N1C->getZExtValue();
4569 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4572 Mask = Mask.shl(c2 - c1);
4574 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4575 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4577 Mask = Mask.lshr(c1 - c2);
4579 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4580 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4583 return DAG.getNode(ISD::AND, DL, VT, Shift,
4584 DAG.getConstant(Mask, DL, VT));
4588 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4589 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4590 unsigned BitSize = VT.getScalarSizeInBits();
4592 SDValue HiBitsMask =
4593 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4594 BitSize - N1C->getZExtValue()),
4596 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4600 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4601 // Variant of version done on multiply, except mul by a power of 2 is turned
4604 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4605 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4606 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4607 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4608 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4609 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4612 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4613 if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4614 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4615 if (SDValue Folded =
4616 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4617 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4621 if (N1C && !N1C->isOpaque())
4622 if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4628 SDValue DAGCombiner::visitSRA(SDNode *N) {
4629 SDValue N0 = N->getOperand(0);
4630 SDValue N1 = N->getOperand(1);
4631 EVT VT = N0.getValueType();
4632 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4635 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4636 if (VT.isVector()) {
4637 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4640 N1C = isConstOrConstSplat(N1);
4643 // fold (sra c1, c2) -> (sra c1, c2)
4644 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4645 if (N0C && N1C && !N1C->isOpaque())
4646 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4647 // fold (sra 0, x) -> 0
4648 if (isNullConstant(N0))
4650 // fold (sra -1, x) -> -1
4651 if (isAllOnesConstant(N0))
4653 // fold (sra x, (setge c, size(x))) -> undef
4654 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4655 return DAG.getUNDEF(VT);
4656 // fold (sra x, 0) -> x
4657 if (N1C && N1C->isNullValue())
4659 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4661 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4662 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4663 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4665 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4666 ExtVT, VT.getVectorNumElements());
4667 if ((!LegalOperations ||
4668 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4669 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4670 N0.getOperand(0), DAG.getValueType(ExtVT));
4673 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4674 if (N1C && N0.getOpcode() == ISD::SRA) {
4675 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4676 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4677 if (Sum >= OpSizeInBits)
4678 Sum = OpSizeInBits - 1;
4680 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4681 DAG.getConstant(Sum, DL, N1.getValueType()));
4685 // fold (sra (shl X, m), (sub result_size, n))
4686 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4687 // result_size - n != m.
4688 // If truncate is free for the target sext(shl) is likely to result in better
4690 if (N0.getOpcode() == ISD::SHL && N1C) {
4691 // Get the two constanst of the shifts, CN0 = m, CN = n.
4692 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4694 LLVMContext &Ctx = *DAG.getContext();
4695 // Determine what the truncate's result bitsize and type would be.
4696 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4699 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4701 // Determine the residual right-shift amount.
4702 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4704 // If the shift is not a no-op (in which case this should be just a sign
4705 // extend already), the truncated to type is legal, sign_extend is legal
4706 // on that type, and the truncate to that type is both legal and free,
4707 // perform the transform.
4708 if ((ShiftAmt > 0) &&
4709 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4710 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4711 TLI.isTruncateFree(VT, TruncVT)) {
4714 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4715 getShiftAmountTy(N0.getOperand(0).getValueType()));
4716 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4717 N0.getOperand(0), Amt);
4718 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4720 return DAG.getNode(ISD::SIGN_EXTEND, DL,
4721 N->getValueType(0), Trunc);
4726 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4727 if (N1.getOpcode() == ISD::TRUNCATE &&
4728 N1.getOperand(0).getOpcode() == ISD::AND) {
4729 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4730 if (NewOp1.getNode())
4731 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4734 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4735 // if c1 is equal to the number of bits the trunc removes
4736 if (N0.getOpcode() == ISD::TRUNCATE &&
4737 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4738 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4739 N0.getOperand(0).hasOneUse() &&
4740 N0.getOperand(0).getOperand(1).hasOneUse() &&
4742 SDValue N0Op0 = N0.getOperand(0);
4743 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4744 unsigned LargeShiftVal = LargeShift->getZExtValue();
4745 EVT LargeVT = N0Op0.getValueType();
4747 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4750 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4751 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4752 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4753 N0Op0.getOperand(0), Amt);
4754 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4759 // Simplify, based on bits shifted out of the LHS.
4760 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4761 return SDValue(N, 0);
4764 // If the sign bit is known to be zero, switch this to a SRL.
4765 if (DAG.SignBitIsZero(N0))
4766 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4768 if (N1C && !N1C->isOpaque())
4769 if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4775 SDValue DAGCombiner::visitSRL(SDNode *N) {
4776 SDValue N0 = N->getOperand(0);
4777 SDValue N1 = N->getOperand(1);
4778 EVT VT = N0.getValueType();
4779 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4782 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4783 if (VT.isVector()) {
4784 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4787 N1C = isConstOrConstSplat(N1);
4790 // fold (srl c1, c2) -> c1 >>u c2
4791 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4792 if (N0C && N1C && !N1C->isOpaque())
4793 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4794 // fold (srl 0, x) -> 0
4795 if (isNullConstant(N0))
4797 // fold (srl x, c >= size(x)) -> undef
4798 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4799 return DAG.getUNDEF(VT);
4800 // fold (srl x, 0) -> x
4801 if (N1C && N1C->isNullValue())
4803 // if (srl x, c) is known to be zero, return 0
4804 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4805 APInt::getAllOnesValue(OpSizeInBits)))
4806 return DAG.getConstant(0, SDLoc(N), VT);
4808 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4809 if (N1C && N0.getOpcode() == ISD::SRL) {
4810 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4811 uint64_t c1 = N01C->getZExtValue();
4812 uint64_t c2 = N1C->getZExtValue();
4814 if (c1 + c2 >= OpSizeInBits)
4815 return DAG.getConstant(0, DL, VT);
4816 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4817 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4821 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4822 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4823 N0.getOperand(0).getOpcode() == ISD::SRL &&
4824 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4826 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4827 uint64_t c2 = N1C->getZExtValue();
4828 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4829 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4830 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4831 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4832 if (c1 + OpSizeInBits == InnerShiftSize) {
4834 if (c1 + c2 >= InnerShiftSize)
4835 return DAG.getConstant(0, DL, VT);
4836 return DAG.getNode(ISD::TRUNCATE, DL, VT,
4837 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4838 N0.getOperand(0)->getOperand(0),
4839 DAG.getConstant(c1 + c2, DL,
4844 // fold (srl (shl x, c), c) -> (and x, cst2)
4845 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4846 unsigned BitSize = N0.getScalarValueSizeInBits();
4847 if (BitSize <= 64) {
4848 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4850 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4851 DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4855 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4856 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4857 // Shifting in all undef bits?
4858 EVT SmallVT = N0.getOperand(0).getValueType();
4859 unsigned BitSize = SmallVT.getScalarSizeInBits();
4860 if (N1C->getZExtValue() >= BitSize)
4861 return DAG.getUNDEF(VT);
4863 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4864 uint64_t ShiftAmt = N1C->getZExtValue();
4866 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4868 DAG.getConstant(ShiftAmt, DL0,
4869 getShiftAmountTy(SmallVT)));
4870 AddToWorklist(SmallShift.getNode());
4871 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4873 return DAG.getNode(ISD::AND, DL, VT,
4874 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4875 DAG.getConstant(Mask, DL, VT));
4879 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4880 // bit, which is unmodified by sra.
4881 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4882 if (N0.getOpcode() == ISD::SRA)
4883 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4886 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4887 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4888 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4889 APInt KnownZero, KnownOne;
4890 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4892 // If any of the input bits are KnownOne, then the input couldn't be all
4893 // zeros, thus the result of the srl will always be zero.
4894 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4896 // If all of the bits input the to ctlz node are known to be zero, then
4897 // the result of the ctlz is "32" and the result of the shift is one.
4898 APInt UnknownBits = ~KnownZero;
4899 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4901 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4902 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4903 // Okay, we know that only that the single bit specified by UnknownBits
4904 // could be set on input to the CTLZ node. If this bit is set, the SRL
4905 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4906 // to an SRL/XOR pair, which is likely to simplify more.
4907 unsigned ShAmt = UnknownBits.countTrailingZeros();
4908 SDValue Op = N0.getOperand(0);
4912 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4913 DAG.getConstant(ShAmt, DL,
4914 getShiftAmountTy(Op.getValueType())));
4915 AddToWorklist(Op.getNode());
4919 return DAG.getNode(ISD::XOR, DL, VT,
4920 Op, DAG.getConstant(1, DL, VT));
4924 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4925 if (N1.getOpcode() == ISD::TRUNCATE &&
4926 N1.getOperand(0).getOpcode() == ISD::AND) {
4927 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4928 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4931 // fold operands of srl based on knowledge that the low bits are not
4933 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4934 return SDValue(N, 0);
4936 if (N1C && !N1C->isOpaque())
4937 if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4940 // Attempt to convert a srl of a load into a narrower zero-extending load.
4941 if (SDValue NarrowLoad = ReduceLoadWidth(N))
4944 // Here is a common situation. We want to optimize:
4947 // %b = and i32 %a, 2
4948 // %c = srl i32 %b, 1
4949 // brcond i32 %c ...
4955 // %c = setcc eq %b, 0
4958 // However when after the source operand of SRL is optimized into AND, the SRL
4959 // itself may not be optimized further. Look for it and add the BRCOND into
4961 if (N->hasOneUse()) {
4962 SDNode *Use = *N->use_begin();
4963 if (Use->getOpcode() == ISD::BRCOND)
4965 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4966 // Also look pass the truncate.
4967 Use = *Use->use_begin();
4968 if (Use->getOpcode() == ISD::BRCOND)
4976 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4977 SDValue N0 = N->getOperand(0);
4978 EVT VT = N->getValueType(0);
4980 // fold (bswap c1) -> c2
4981 if (isConstantIntBuildVectorOrConstantInt(N0))
4982 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4983 // fold (bswap (bswap x)) -> x
4984 if (N0.getOpcode() == ISD::BSWAP)
4985 return N0->getOperand(0);
4989 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4990 SDValue N0 = N->getOperand(0);
4991 EVT VT = N->getValueType(0);
4993 // fold (ctlz c1) -> c2
4994 if (isConstantIntBuildVectorOrConstantInt(N0))
4995 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4999 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
5000 SDValue N0 = N->getOperand(0);
5001 EVT VT = N->getValueType(0);
5003 // fold (ctlz_zero_undef c1) -> c2
5004 if (isConstantIntBuildVectorOrConstantInt(N0))
5005 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5009 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
5010 SDValue N0 = N->getOperand(0);
5011 EVT VT = N->getValueType(0);
5013 // fold (cttz c1) -> c2
5014 if (isConstantIntBuildVectorOrConstantInt(N0))
5015 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
5019 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
5020 SDValue N0 = N->getOperand(0);
5021 EVT VT = N->getValueType(0);
5023 // fold (cttz_zero_undef c1) -> c2
5024 if (isConstantIntBuildVectorOrConstantInt(N0))
5025 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5029 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
5030 SDValue N0 = N->getOperand(0);
5031 EVT VT = N->getValueType(0);
5033 // fold (ctpop c1) -> c2
5034 if (isConstantIntBuildVectorOrConstantInt(N0))
5035 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
5040 /// \brief Generate Min/Max node
5041 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
5042 SDValue True, SDValue False,
5043 ISD::CondCode CC, const TargetLowering &TLI,
5044 SelectionDAG &DAG) {
5045 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
5055 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
5056 if (TLI.isOperationLegal(Opcode, VT))
5057 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5066 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
5067 if (TLI.isOperationLegal(Opcode, VT))
5068 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5076 SDValue DAGCombiner::visitSELECT(SDNode *N) {
5077 SDValue N0 = N->getOperand(0);
5078 SDValue N1 = N->getOperand(1);
5079 SDValue N2 = N->getOperand(2);
5080 EVT VT = N->getValueType(0);
5081 EVT VT0 = N0.getValueType();
5083 // fold (select C, X, X) -> X
5086 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
5087 // fold (select true, X, Y) -> X
5088 // fold (select false, X, Y) -> Y
5089 return !N0C->isNullValue() ? N1 : N2;
5091 // fold (select C, 1, X) -> (or C, X)
5092 if (VT == MVT::i1 && isOneConstant(N1))
5093 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5094 // fold (select C, 0, 1) -> (xor C, 1)
5095 // We can't do this reliably if integer based booleans have different contents
5096 // to floating point based booleans. This is because we can't tell whether we
5097 // have an integer-based boolean or a floating-point-based boolean unless we
5098 // can find the SETCC that produced it and inspect its operands. This is
5099 // fairly easy if C is the SETCC node, but it can potentially be
5100 // undiscoverable (or not reasonably discoverable). For example, it could be
5101 // in another basic block or it could require searching a complicated
5103 if (VT.isInteger() &&
5104 (VT0 == MVT::i1 || (VT0.isInteger() &&
5105 TLI.getBooleanContents(false, false) ==
5106 TLI.getBooleanContents(false, true) &&
5107 TLI.getBooleanContents(false, false) ==
5108 TargetLowering::ZeroOrOneBooleanContent)) &&
5109 isNullConstant(N1) && isOneConstant(N2)) {
5113 return DAG.getNode(ISD::XOR, DL, VT0,
5114 N0, DAG.getConstant(1, DL, VT0));
5117 XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
5118 N0, DAG.getConstant(1, DL0, VT0));
5119 AddToWorklist(XORNode.getNode());
5121 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
5122 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
5124 // fold (select C, 0, X) -> (and (not C), X)
5125 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
5126 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5127 AddToWorklist(NOTNode.getNode());
5128 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
5130 // fold (select C, X, 1) -> (or (not C), X)
5131 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
5132 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5133 AddToWorklist(NOTNode.getNode());
5134 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
5136 // fold (select C, X, 0) -> (and C, X)
5137 if (VT == MVT::i1 && isNullConstant(N2))
5138 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5139 // fold (select X, X, Y) -> (or X, Y)
5140 // fold (select X, 1, Y) -> (or X, Y)
5141 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5142 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5143 // fold (select X, Y, X) -> (and X, Y)
5144 // fold (select X, Y, 0) -> (and X, Y)
5145 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5146 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5148 // If we can fold this based on the true/false value, do so.
5149 if (SimplifySelectOps(N, N1, N2))
5150 return SDValue(N, 0); // Don't revisit N.
5152 if (VT0 == MVT::i1) {
5153 // The code in this block deals with the following 2 equivalences:
5154 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5155 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5156 // The target can specify its prefered form with the
5157 // shouldNormalizeToSelectSequence() callback. However we always transform
5158 // to the right anyway if we find the inner select exists in the DAG anyway
5159 // and we always transform to the left side if we know that we can further
5160 // optimize the combination of the conditions.
5161 bool normalizeToSequence
5162 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5163 // select (and Cond0, Cond1), X, Y
5164 // -> select Cond0, (select Cond1, X, Y), Y
5165 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5166 SDValue Cond0 = N0->getOperand(0);
5167 SDValue Cond1 = N0->getOperand(1);
5168 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5169 N1.getValueType(), Cond1, N1, N2);
5170 if (normalizeToSequence || !InnerSelect.use_empty())
5171 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5174 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5175 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5176 SDValue Cond0 = N0->getOperand(0);
5177 SDValue Cond1 = N0->getOperand(1);
5178 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5179 N1.getValueType(), Cond1, N1, N2);
5180 if (normalizeToSequence || !InnerSelect.use_empty())
5181 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5185 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5186 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5187 SDValue N1_0 = N1->getOperand(0);
5188 SDValue N1_1 = N1->getOperand(1);
5189 SDValue N1_2 = N1->getOperand(2);
5190 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5191 // Create the actual and node if we can generate good code for it.
5192 if (!normalizeToSequence) {
5193 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5195 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5198 // Otherwise see if we can optimize the "and" to a better pattern.
5199 if (SDValue Combined = visitANDLike(N0, N1_0, N))
5200 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5204 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5205 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5206 SDValue N2_0 = N2->getOperand(0);
5207 SDValue N2_1 = N2->getOperand(1);
5208 SDValue N2_2 = N2->getOperand(2);
5209 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5210 // Create the actual or node if we can generate good code for it.
5211 if (!normalizeToSequence) {
5212 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5214 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5217 // Otherwise see if we can optimize to a better pattern.
5218 if (SDValue Combined = visitORLike(N0, N2_0, N))
5219 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5225 // fold selects based on a setcc into other things, such as min/max/abs
5226 if (N0.getOpcode() == ISD::SETCC) {
5227 // select x, y (fcmp lt x, y) -> fminnum x, y
5228 // select x, y (fcmp gt x, y) -> fmaxnum x, y
5230 // This is OK if we don't care about what happens if either operand is a
5234 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5235 // no signed zeros as well as no nans.
5236 const TargetOptions &Options = DAG.getTarget().Options;
5237 if (Options.UnsafeFPMath &&
5238 VT.isFloatingPoint() && N0.hasOneUse() &&
5239 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5240 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5242 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5243 N0.getOperand(1), N1, N2, CC,
5248 if ((!LegalOperations &&
5249 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5250 TLI.isOperationLegal(ISD::SELECT_CC, VT))
5251 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5252 N0.getOperand(0), N0.getOperand(1),
5253 N1, N2, N0.getOperand(2));
5254 return SimplifySelect(SDLoc(N), N0, N1, N2);
5261 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5264 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5266 // Split the inputs.
5267 SDValue Lo, Hi, LL, LH, RL, RH;
5268 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5269 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5271 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5272 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5274 return std::make_pair(Lo, Hi);
5277 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5278 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5279 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5281 SDValue Cond = N->getOperand(0);
5282 SDValue LHS = N->getOperand(1);
5283 SDValue RHS = N->getOperand(2);
5284 EVT VT = N->getValueType(0);
5285 int NumElems = VT.getVectorNumElements();
5286 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5287 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5288 Cond.getOpcode() == ISD::BUILD_VECTOR);
5290 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5291 // binary ones here.
5292 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5295 // We're sure we have an even number of elements due to the
5296 // concat_vectors we have as arguments to vselect.
5297 // Skip BV elements until we find one that's not an UNDEF
5298 // After we find an UNDEF element, keep looping until we get to half the
5299 // length of the BV and see if all the non-undef nodes are the same.
5300 ConstantSDNode *BottomHalf = nullptr;
5301 for (int i = 0; i < NumElems / 2; ++i) {
5302 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5305 if (BottomHalf == nullptr)
5306 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5307 else if (Cond->getOperand(i).getNode() != BottomHalf)
5311 // Do the same for the second half of the BuildVector
5312 ConstantSDNode *TopHalf = nullptr;
5313 for (int i = NumElems / 2; i < NumElems; ++i) {
5314 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5317 if (TopHalf == nullptr)
5318 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5319 else if (Cond->getOperand(i).getNode() != TopHalf)
5323 assert(TopHalf && BottomHalf &&
5324 "One half of the selector was all UNDEFs and the other was all the "
5325 "same value. This should have been addressed before this function.");
5327 ISD::CONCAT_VECTORS, dl, VT,
5328 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5329 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5332 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5334 if (Level >= AfterLegalizeTypes)
5337 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5338 SDValue Mask = MSC->getMask();
5339 SDValue Data = MSC->getValue();
5342 // If the MSCATTER data type requires splitting and the mask is provided by a
5343 // SETCC, then split both nodes and its operands before legalization. This
5344 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5345 // and enables future optimizations (e.g. min/max pattern matching on X86).
5346 if (Mask.getOpcode() != ISD::SETCC)
5349 // Check if any splitting is required.
5350 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5351 TargetLowering::TypeSplitVector)
5353 SDValue MaskLo, MaskHi, Lo, Hi;
5354 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5357 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5359 SDValue Chain = MSC->getChain();
5361 EVT MemoryVT = MSC->getMemoryVT();
5362 unsigned Alignment = MSC->getOriginalAlignment();
5364 EVT LoMemVT, HiMemVT;
5365 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5367 SDValue DataLo, DataHi;
5368 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5370 SDValue BasePtr = MSC->getBasePtr();
5371 SDValue IndexLo, IndexHi;
5372 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5374 MachineMemOperand *MMO = DAG.getMachineFunction().
5375 getMachineMemOperand(MSC->getPointerInfo(),
5376 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5377 Alignment, MSC->getAAInfo(), MSC->getRanges());
5379 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5380 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5383 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5384 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5387 AddToWorklist(Lo.getNode());
5388 AddToWorklist(Hi.getNode());
5390 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5393 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5395 if (Level >= AfterLegalizeTypes)
5398 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5399 SDValue Mask = MST->getMask();
5400 SDValue Data = MST->getValue();
5403 // If the MSTORE data type requires splitting and the mask is provided by a
5404 // SETCC, then split both nodes and its operands before legalization. This
5405 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5406 // and enables future optimizations (e.g. min/max pattern matching on X86).
5407 if (Mask.getOpcode() == ISD::SETCC) {
5409 // Check if any splitting is required.
5410 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5411 TargetLowering::TypeSplitVector)
5414 SDValue MaskLo, MaskHi, Lo, Hi;
5415 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5418 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5420 SDValue Chain = MST->getChain();
5421 SDValue Ptr = MST->getBasePtr();
5423 EVT MemoryVT = MST->getMemoryVT();
5424 unsigned Alignment = MST->getOriginalAlignment();
5426 // if Alignment is equal to the vector size,
5427 // take the half of it for the second part
5428 unsigned SecondHalfAlignment =
5429 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5430 Alignment/2 : Alignment;
5432 EVT LoMemVT, HiMemVT;
5433 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5435 SDValue DataLo, DataHi;
5436 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5438 MachineMemOperand *MMO = DAG.getMachineFunction().
5439 getMachineMemOperand(MST->getPointerInfo(),
5440 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5441 Alignment, MST->getAAInfo(), MST->getRanges());
5443 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5444 MST->isTruncatingStore());
5446 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5447 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5448 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5450 MMO = DAG.getMachineFunction().
5451 getMachineMemOperand(MST->getPointerInfo(),
5452 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5453 SecondHalfAlignment, MST->getAAInfo(),
5456 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5457 MST->isTruncatingStore());
5459 AddToWorklist(Lo.getNode());
5460 AddToWorklist(Hi.getNode());
5462 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5467 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5469 if (Level >= AfterLegalizeTypes)
5472 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5473 SDValue Mask = MGT->getMask();
5476 // If the MGATHER result requires splitting and the mask is provided by a
5477 // SETCC, then split both nodes and its operands before legalization. This
5478 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5479 // and enables future optimizations (e.g. min/max pattern matching on X86).
5481 if (Mask.getOpcode() != ISD::SETCC)
5484 EVT VT = N->getValueType(0);
5486 // Check if any splitting is required.
5487 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5488 TargetLowering::TypeSplitVector)
5491 SDValue MaskLo, MaskHi, Lo, Hi;
5492 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5494 SDValue Src0 = MGT->getValue();
5495 SDValue Src0Lo, Src0Hi;
5496 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5499 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5501 SDValue Chain = MGT->getChain();
5502 EVT MemoryVT = MGT->getMemoryVT();
5503 unsigned Alignment = MGT->getOriginalAlignment();
5505 EVT LoMemVT, HiMemVT;
5506 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5508 SDValue BasePtr = MGT->getBasePtr();
5509 SDValue Index = MGT->getIndex();
5510 SDValue IndexLo, IndexHi;
5511 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5513 MachineMemOperand *MMO = DAG.getMachineFunction().
5514 getMachineMemOperand(MGT->getPointerInfo(),
5515 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5516 Alignment, MGT->getAAInfo(), MGT->getRanges());
5518 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5519 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5522 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5523 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5526 AddToWorklist(Lo.getNode());
5527 AddToWorklist(Hi.getNode());
5529 // Build a factor node to remember that this load is independent of the
5531 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5534 // Legalized the chain result - switch anything that used the old chain to
5536 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5538 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5540 SDValue RetOps[] = { GatherRes, Chain };
5541 return DAG.getMergeValues(RetOps, DL);
5544 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5546 if (Level >= AfterLegalizeTypes)
5549 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5550 SDValue Mask = MLD->getMask();
5553 // If the MLOAD result requires splitting and the mask is provided by a
5554 // SETCC, then split both nodes and its operands before legalization. This
5555 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5556 // and enables future optimizations (e.g. min/max pattern matching on X86).
5558 if (Mask.getOpcode() == ISD::SETCC) {
5559 EVT VT = N->getValueType(0);
5561 // Check if any splitting is required.
5562 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5563 TargetLowering::TypeSplitVector)
5566 SDValue MaskLo, MaskHi, Lo, Hi;
5567 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5569 SDValue Src0 = MLD->getSrc0();
5570 SDValue Src0Lo, Src0Hi;
5571 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5574 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5576 SDValue Chain = MLD->getChain();
5577 SDValue Ptr = MLD->getBasePtr();
5578 EVT MemoryVT = MLD->getMemoryVT();
5579 unsigned Alignment = MLD->getOriginalAlignment();
5581 // if Alignment is equal to the vector size,
5582 // take the half of it for the second part
5583 unsigned SecondHalfAlignment =
5584 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5585 Alignment/2 : Alignment;
5587 EVT LoMemVT, HiMemVT;
5588 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5590 MachineMemOperand *MMO = DAG.getMachineFunction().
5591 getMachineMemOperand(MLD->getPointerInfo(),
5592 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5593 Alignment, MLD->getAAInfo(), MLD->getRanges());
5595 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5598 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5599 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5600 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5602 MMO = DAG.getMachineFunction().
5603 getMachineMemOperand(MLD->getPointerInfo(),
5604 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5605 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5607 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5610 AddToWorklist(Lo.getNode());
5611 AddToWorklist(Hi.getNode());
5613 // Build a factor node to remember that this load is independent of the
5615 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5618 // Legalized the chain result - switch anything that used the old chain to
5620 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5622 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5624 SDValue RetOps[] = { LoadRes, Chain };
5625 return DAG.getMergeValues(RetOps, DL);
5630 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5631 SDValue N0 = N->getOperand(0);
5632 SDValue N1 = N->getOperand(1);
5633 SDValue N2 = N->getOperand(2);
5636 // Canonicalize integer abs.
5637 // vselect (setg[te] X, 0), X, -X ->
5638 // vselect (setgt X, -1), X, -X ->
5639 // vselect (setl[te] X, 0), -X, X ->
5640 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5641 if (N0.getOpcode() == ISD::SETCC) {
5642 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5643 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5645 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5647 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5648 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5649 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5650 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5651 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5652 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5653 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5656 EVT VT = LHS.getValueType();
5657 SDValue Shift = DAG.getNode(
5658 ISD::SRA, DL, VT, LHS,
5659 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5660 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5661 AddToWorklist(Shift.getNode());
5662 AddToWorklist(Add.getNode());
5663 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5667 if (SimplifySelectOps(N, N1, N2))
5668 return SDValue(N, 0); // Don't revisit N.
5670 // If the VSELECT result requires splitting and the mask is provided by a
5671 // SETCC, then split both nodes and its operands before legalization. This
5672 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5673 // and enables future optimizations (e.g. min/max pattern matching on X86).
5674 if (N0.getOpcode() == ISD::SETCC) {
5675 EVT VT = N->getValueType(0);
5677 // Check if any splitting is required.
5678 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5679 TargetLowering::TypeSplitVector)
5682 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5683 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5684 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5685 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5687 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5688 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5690 // Add the new VSELECT nodes to the work list in case they need to be split
5692 AddToWorklist(Lo.getNode());
5693 AddToWorklist(Hi.getNode());
5695 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5698 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5699 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5701 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5702 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5705 // The ConvertSelectToConcatVector function is assuming both the above
5706 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5708 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5709 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5710 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5711 if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5718 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5719 SDValue N0 = N->getOperand(0);
5720 SDValue N1 = N->getOperand(1);
5721 SDValue N2 = N->getOperand(2);
5722 SDValue N3 = N->getOperand(3);
5723 SDValue N4 = N->getOperand(4);
5724 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5726 // fold select_cc lhs, rhs, x, x, cc -> x
5730 // Determine if the condition we're dealing with is constant
5731 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5732 N0, N1, CC, SDLoc(N), false);
5733 if (SCC.getNode()) {
5734 AddToWorklist(SCC.getNode());
5736 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5737 if (!SCCC->isNullValue())
5738 return N2; // cond always true -> true val
5740 return N3; // cond always false -> false val
5741 } else if (SCC->getOpcode() == ISD::UNDEF) {
5742 // When the condition is UNDEF, just return the first operand. This is
5743 // coherent the DAG creation, no setcc node is created in this case
5745 } else if (SCC.getOpcode() == ISD::SETCC) {
5746 // Fold to a simpler select_cc
5747 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5748 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5753 // If we can fold this based on the true/false value, do so.
5754 if (SimplifySelectOps(N, N2, N3))
5755 return SDValue(N, 0); // Don't revisit N.
5757 // fold select_cc into other things, such as min/max/abs
5758 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5761 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5762 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5763 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5767 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
5768 SDValue LHS = N->getOperand(0);
5769 SDValue RHS = N->getOperand(1);
5770 SDValue Carry = N->getOperand(2);
5771 SDValue Cond = N->getOperand(3);
5773 // If Carry is false, fold to a regular SETCC.
5774 if (Carry.getOpcode() == ISD::CARRY_FALSE)
5775 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
5780 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5781 /// a build_vector of constants.
5782 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5783 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5784 /// Vector extends are not folded if operations are legal; this is to
5785 /// avoid introducing illegal build_vector dag nodes.
5786 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5787 SelectionDAG &DAG, bool LegalTypes,
5788 bool LegalOperations) {
5789 unsigned Opcode = N->getOpcode();
5790 SDValue N0 = N->getOperand(0);
5791 EVT VT = N->getValueType(0);
5793 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5794 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5795 && "Expected EXTEND dag node in input!");
5797 // fold (sext c1) -> c1
5798 // fold (zext c1) -> c1
5799 // fold (aext c1) -> c1
5800 if (isa<ConstantSDNode>(N0))
5801 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5803 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5804 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5805 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5806 EVT SVT = VT.getScalarType();
5807 if (!(VT.isVector() &&
5808 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5809 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5812 // We can fold this node into a build_vector.
5813 unsigned VTBits = SVT.getSizeInBits();
5814 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5815 SmallVector<SDValue, 8> Elts;
5816 unsigned NumElts = VT.getVectorNumElements();
5819 for (unsigned i=0; i != NumElts; ++i) {
5820 SDValue Op = N0->getOperand(i);
5821 if (Op->getOpcode() == ISD::UNDEF) {
5822 Elts.push_back(DAG.getUNDEF(SVT));
5827 // Get the constant value and if needed trunc it to the size of the type.
5828 // Nodes like build_vector might have constants wider than the scalar type.
5829 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5830 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5831 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5833 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5836 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5839 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5840 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5841 // transformation. Returns true if extension are possible and the above
5842 // mentioned transformation is profitable.
5843 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5845 SmallVectorImpl<SDNode *> &ExtendNodes,
5846 const TargetLowering &TLI) {
5847 bool HasCopyToRegUses = false;
5848 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5849 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5850 UE = N0.getNode()->use_end();
5855 if (UI.getUse().getResNo() != N0.getResNo())
5857 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5858 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5859 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5860 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5861 // Sign bits will be lost after a zext.
5864 for (unsigned i = 0; i != 2; ++i) {
5865 SDValue UseOp = User->getOperand(i);
5868 if (!isa<ConstantSDNode>(UseOp))
5873 ExtendNodes.push_back(User);
5876 // If truncates aren't free and there are users we can't
5877 // extend, it isn't worthwhile.
5880 // Remember if this value is live-out.
5881 if (User->getOpcode() == ISD::CopyToReg)
5882 HasCopyToRegUses = true;
5885 if (HasCopyToRegUses) {
5886 bool BothLiveOut = false;
5887 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5889 SDUse &Use = UI.getUse();
5890 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5896 // Both unextended and extended values are live out. There had better be
5897 // a good reason for the transformation.
5898 return ExtendNodes.size();
5903 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5904 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5905 ISD::NodeType ExtType) {
5906 // Extend SetCC uses if necessary.
5907 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5908 SDNode *SetCC = SetCCs[i];
5909 SmallVector<SDValue, 4> Ops;
5911 for (unsigned j = 0; j != 2; ++j) {
5912 SDValue SOp = SetCC->getOperand(j);
5914 Ops.push_back(ExtLoad);
5916 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5919 Ops.push_back(SetCC->getOperand(2));
5920 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5924 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5925 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5926 SDValue N0 = N->getOperand(0);
5927 EVT DstVT = N->getValueType(0);
5928 EVT SrcVT = N0.getValueType();
5930 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5931 N->getOpcode() == ISD::ZERO_EXTEND) &&
5932 "Unexpected node type (not an extend)!");
5934 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5935 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5936 // (v8i32 (sext (v8i16 (load x))))
5938 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5939 // (v4i32 (sextload (x + 16)))))
5940 // Where uses of the original load, i.e.:
5942 // are replaced with:
5944 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5945 // (v4i32 (sextload (x + 16)))))))
5947 // This combine is only applicable to illegal, but splittable, vectors.
5948 // All legal types, and illegal non-vector types, are handled elsewhere.
5949 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5951 if (N0->getOpcode() != ISD::LOAD)
5954 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5956 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5957 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5958 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5961 SmallVector<SDNode *, 4> SetCCs;
5962 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5965 ISD::LoadExtType ExtType =
5966 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5968 // Try to split the vector types to get down to legal types.
5969 EVT SplitSrcVT = SrcVT;
5970 EVT SplitDstVT = DstVT;
5971 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5972 SplitSrcVT.getVectorNumElements() > 1) {
5973 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5974 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5977 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5981 const unsigned NumSplits =
5982 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5983 const unsigned Stride = SplitSrcVT.getStoreSize();
5984 SmallVector<SDValue, 4> Loads;
5985 SmallVector<SDValue, 4> Chains;
5987 SDValue BasePtr = LN0->getBasePtr();
5988 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5989 const unsigned Offset = Idx * Stride;
5990 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5992 SDValue SplitLoad = DAG.getExtLoad(
5993 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5994 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5995 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5996 Align, LN0->getAAInfo());
5998 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5999 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
6001 Loads.push_back(SplitLoad.getValue(0));
6002 Chains.push_back(SplitLoad.getValue(1));
6005 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
6006 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
6008 CombineTo(N, NewValue);
6010 // Replace uses of the original load (before extension)
6011 // with a truncate of the concatenated sextloaded vectors.
6013 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
6014 CombineTo(N0.getNode(), Trunc, NewChain);
6015 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
6016 (ISD::NodeType)N->getOpcode());
6017 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6020 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
6021 SDValue N0 = N->getOperand(0);
6022 EVT VT = N->getValueType(0);
6024 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6026 return SDValue(Res, 0);
6028 // fold (sext (sext x)) -> (sext x)
6029 // fold (sext (aext x)) -> (sext x)
6030 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6031 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
6034 if (N0.getOpcode() == ISD::TRUNCATE) {
6035 // fold (sext (truncate (load x))) -> (sext (smaller load x))
6036 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
6037 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6038 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6039 if (NarrowLoad.getNode() != N0.getNode()) {
6040 CombineTo(N0.getNode(), NarrowLoad);
6041 // CombineTo deleted the truncate, if needed, but not what's under it.
6044 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6047 // See if the value being truncated is already sign extended. If so, just
6048 // eliminate the trunc/sext pair.
6049 SDValue Op = N0.getOperand(0);
6050 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
6051 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
6052 unsigned DestBits = VT.getScalarType().getSizeInBits();
6053 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
6055 if (OpBits == DestBits) {
6056 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
6057 // bits, it is already ready.
6058 if (NumSignBits > DestBits-MidBits)
6060 } else if (OpBits < DestBits) {
6061 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
6062 // bits, just sext from i32.
6063 if (NumSignBits > OpBits-MidBits)
6064 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
6066 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
6067 // bits, just truncate to i32.
6068 if (NumSignBits > OpBits-MidBits)
6069 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6072 // fold (sext (truncate x)) -> (sextinreg x).
6073 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
6074 N0.getValueType())) {
6075 if (OpBits < DestBits)
6076 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
6077 else if (OpBits > DestBits)
6078 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
6079 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
6080 DAG.getValueType(N0.getValueType()));
6084 // fold (sext (load x)) -> (sext (truncate (sextload x)))
6085 // Only generate vector extloads when 1) they're legal, and 2) they are
6086 // deemed desirable by the target.
6087 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6088 ((!LegalOperations && !VT.isVector() &&
6089 !cast<LoadSDNode>(N0)->isVolatile()) ||
6090 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
6091 bool DoXform = true;
6092 SmallVector<SDNode*, 4> SetCCs;
6093 if (!N0.hasOneUse())
6094 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
6096 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6098 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6099 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6101 LN0->getBasePtr(), N0.getValueType(),
6102 LN0->getMemOperand());
6103 CombineTo(N, ExtLoad);
6104 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6105 N0.getValueType(), ExtLoad);
6106 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6107 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6109 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6113 // fold (sext (load x)) to multiple smaller sextloads.
6114 // Only on illegal but splittable vectors.
6115 if (SDValue ExtLoad = CombineExtLoad(N))
6118 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6119 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6120 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6121 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6122 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6123 EVT MemVT = LN0->getMemoryVT();
6124 if ((!LegalOperations && !LN0->isVolatile()) ||
6125 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6126 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6128 LN0->getBasePtr(), MemVT,
6129 LN0->getMemOperand());
6130 CombineTo(N, ExtLoad);
6131 CombineTo(N0.getNode(),
6132 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6133 N0.getValueType(), ExtLoad),
6134 ExtLoad.getValue(1));
6135 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6139 // fold (sext (and/or/xor (load x), cst)) ->
6140 // (and/or/xor (sextload x), (sext cst))
6141 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6142 N0.getOpcode() == ISD::XOR) &&
6143 isa<LoadSDNode>(N0.getOperand(0)) &&
6144 N0.getOperand(1).getOpcode() == ISD::Constant &&
6145 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
6146 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6147 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6148 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
6149 bool DoXform = true;
6150 SmallVector<SDNode*, 4> SetCCs;
6151 if (!N0.hasOneUse())
6152 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6155 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6156 LN0->getChain(), LN0->getBasePtr(),
6158 LN0->getMemOperand());
6159 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6160 Mask = Mask.sext(VT.getSizeInBits());
6162 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6163 ExtLoad, DAG.getConstant(Mask, DL, VT));
6164 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6165 SDLoc(N0.getOperand(0)),
6166 N0.getOperand(0).getValueType(), ExtLoad);
6168 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6169 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6171 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6176 if (N0.getOpcode() == ISD::SETCC) {
6177 EVT N0VT = N0.getOperand(0).getValueType();
6178 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6179 // Only do this before legalize for now.
6180 if (VT.isVector() && !LegalOperations &&
6181 TLI.getBooleanContents(N0VT) ==
6182 TargetLowering::ZeroOrNegativeOneBooleanContent) {
6183 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6184 // of the same size as the compared operands. Only optimize sext(setcc())
6185 // if this is the case.
6186 EVT SVT = getSetCCResultType(N0VT);
6188 // We know that the # elements of the results is the same as the
6189 // # elements of the compare (and the # elements of the compare result
6190 // for that matter). Check to see that they are the same size. If so,
6191 // we know that the element size of the sext'd result matches the
6192 // element size of the compare operands.
6193 if (VT.getSizeInBits() == SVT.getSizeInBits())
6194 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6196 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6198 // If the desired elements are smaller or larger than the source
6199 // elements we can use a matching integer vector type and then
6200 // truncate/sign extend
6201 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6202 if (SVT == MatchingVectorType) {
6203 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6204 N0.getOperand(0), N0.getOperand(1),
6205 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6206 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6210 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6211 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6214 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6216 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6217 NegOne, DAG.getConstant(0, DL, VT),
6218 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6219 if (SCC.getNode()) return SCC;
6221 if (!VT.isVector()) {
6222 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6223 if (!LegalOperations ||
6224 TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6226 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6227 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6228 N0.getOperand(0), N0.getOperand(1), CC);
6229 return DAG.getSelect(DL, VT, SetCC,
6230 NegOne, DAG.getConstant(0, DL, VT));
6235 // fold (sext x) -> (zext x) if the sign bit is known zero.
6236 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6237 DAG.SignBitIsZero(N0))
6238 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6243 // isTruncateOf - If N is a truncate of some other value, return true, record
6244 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6245 // This function computes KnownZero to avoid a duplicated call to
6246 // computeKnownBits in the caller.
6247 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6250 if (N->getOpcode() == ISD::TRUNCATE) {
6251 Op = N->getOperand(0);
6252 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6256 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6257 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6260 SDValue Op0 = N->getOperand(0);
6261 SDValue Op1 = N->getOperand(1);
6262 assert(Op0.getValueType() == Op1.getValueType());
6264 if (isNullConstant(Op0))
6266 else if (isNullConstant(Op1))
6271 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6273 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6279 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6280 SDValue N0 = N->getOperand(0);
6281 EVT VT = N->getValueType(0);
6283 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6285 return SDValue(Res, 0);
6287 // fold (zext (zext x)) -> (zext x)
6288 // fold (zext (aext x)) -> (zext x)
6289 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6290 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6293 // fold (zext (truncate x)) -> (zext x) or
6294 // (zext (truncate x)) -> (truncate x)
6295 // This is valid when the truncated bits of x are already zero.
6296 // FIXME: We should extend this to work for vectors too.
6299 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6300 APInt TruncatedBits =
6301 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6302 APInt(Op.getValueSizeInBits(), 0) :
6303 APInt::getBitsSet(Op.getValueSizeInBits(),
6304 N0.getValueSizeInBits(),
6305 std::min(Op.getValueSizeInBits(),
6306 VT.getSizeInBits()));
6307 if (TruncatedBits == (KnownZero & TruncatedBits)) {
6308 if (VT.bitsGT(Op.getValueType()))
6309 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6310 if (VT.bitsLT(Op.getValueType()))
6311 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6317 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6318 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6319 if (N0.getOpcode() == ISD::TRUNCATE) {
6320 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6321 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6322 if (NarrowLoad.getNode() != N0.getNode()) {
6323 CombineTo(N0.getNode(), NarrowLoad);
6324 // CombineTo deleted the truncate, if needed, but not what's under it.
6327 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6331 // fold (zext (truncate x)) -> (and x, mask)
6332 if (N0.getOpcode() == ISD::TRUNCATE) {
6333 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6334 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6335 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6336 SDNode *oye = N0.getNode()->getOperand(0).getNode();
6337 if (NarrowLoad.getNode() != N0.getNode()) {
6338 CombineTo(N0.getNode(), NarrowLoad);
6339 // CombineTo deleted the truncate, if needed, but not what's under it.
6342 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6345 EVT SrcVT = N0.getOperand(0).getValueType();
6346 EVT MinVT = N0.getValueType();
6348 // Try to mask before the extension to avoid having to generate a larger mask,
6349 // possibly over several sub-vectors.
6350 if (SrcVT.bitsLT(VT)) {
6351 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6352 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6353 SDValue Op = N0.getOperand(0);
6354 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6355 AddToWorklist(Op.getNode());
6356 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6360 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6361 SDValue Op = N0.getOperand(0);
6362 if (SrcVT.bitsLT(VT)) {
6363 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6364 AddToWorklist(Op.getNode());
6365 } else if (SrcVT.bitsGT(VT)) {
6366 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6367 AddToWorklist(Op.getNode());
6369 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6373 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6374 // if either of the casts is not free.
6375 if (N0.getOpcode() == ISD::AND &&
6376 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6377 N0.getOperand(1).getOpcode() == ISD::Constant &&
6378 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6379 N0.getValueType()) ||
6380 !TLI.isZExtFree(N0.getValueType(), VT))) {
6381 SDValue X = N0.getOperand(0).getOperand(0);
6382 if (X.getValueType().bitsLT(VT)) {
6383 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6384 } else if (X.getValueType().bitsGT(VT)) {
6385 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6387 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6388 Mask = Mask.zext(VT.getSizeInBits());
6390 return DAG.getNode(ISD::AND, DL, VT,
6391 X, DAG.getConstant(Mask, DL, VT));
6394 // fold (zext (load x)) -> (zext (truncate (zextload x)))
6395 // Only generate vector extloads when 1) they're legal, and 2) they are
6396 // deemed desirable by the target.
6397 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6398 ((!LegalOperations && !VT.isVector() &&
6399 !cast<LoadSDNode>(N0)->isVolatile()) ||
6400 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6401 bool DoXform = true;
6402 SmallVector<SDNode*, 4> SetCCs;
6403 if (!N0.hasOneUse())
6404 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6406 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6408 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6409 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6411 LN0->getBasePtr(), N0.getValueType(),
6412 LN0->getMemOperand());
6413 CombineTo(N, ExtLoad);
6414 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6415 N0.getValueType(), ExtLoad);
6416 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6418 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6420 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6424 // fold (zext (load x)) to multiple smaller zextloads.
6425 // Only on illegal but splittable vectors.
6426 if (SDValue ExtLoad = CombineExtLoad(N))
6429 // fold (zext (and/or/xor (load x), cst)) ->
6430 // (and/or/xor (zextload x), (zext cst))
6431 // Unless (and (load x) cst) will match as a zextload already and has
6432 // additional users.
6433 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6434 N0.getOpcode() == ISD::XOR) &&
6435 isa<LoadSDNode>(N0.getOperand(0)) &&
6436 N0.getOperand(1).getOpcode() == ISD::Constant &&
6437 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6438 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6439 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6440 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6441 bool DoXform = true;
6442 SmallVector<SDNode*, 4> SetCCs;
6443 if (!N0.hasOneUse()) {
6444 if (N0.getOpcode() == ISD::AND) {
6445 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
6446 auto NarrowLoad = false;
6447 EVT LoadResultTy = AndC->getValueType(0);
6448 EVT ExtVT, LoadedVT;
6449 if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
6454 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
6455 ISD::ZERO_EXTEND, SetCCs, TLI);
6458 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6459 LN0->getChain(), LN0->getBasePtr(),
6461 LN0->getMemOperand());
6462 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6463 Mask = Mask.zext(VT.getSizeInBits());
6465 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6466 ExtLoad, DAG.getConstant(Mask, DL, VT));
6467 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6468 SDLoc(N0.getOperand(0)),
6469 N0.getOperand(0).getValueType(), ExtLoad);
6471 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6472 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6474 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6479 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6480 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6481 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6482 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6483 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6484 EVT MemVT = LN0->getMemoryVT();
6485 if ((!LegalOperations && !LN0->isVolatile()) ||
6486 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6487 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6489 LN0->getBasePtr(), MemVT,
6490 LN0->getMemOperand());
6491 CombineTo(N, ExtLoad);
6492 CombineTo(N0.getNode(),
6493 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6495 ExtLoad.getValue(1));
6496 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6500 if (N0.getOpcode() == ISD::SETCC) {
6501 if (!LegalOperations && VT.isVector() &&
6502 N0.getValueType().getVectorElementType() == MVT::i1) {
6503 EVT N0VT = N0.getOperand(0).getValueType();
6504 if (getSetCCResultType(N0VT) == N0.getValueType())
6507 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6508 // Only do this before legalize for now.
6509 EVT EltVT = VT.getVectorElementType();
6511 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6512 DAG.getConstant(1, DL, EltVT));
6513 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6514 // We know that the # elements of the results is the same as the
6515 // # elements of the compare (and the # elements of the compare result
6516 // for that matter). Check to see that they are the same size. If so,
6517 // we know that the element size of the sext'd result matches the
6518 // element size of the compare operands.
6519 return DAG.getNode(ISD::AND, DL, VT,
6520 DAG.getSetCC(DL, VT, N0.getOperand(0),
6522 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6523 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6526 // If the desired elements are smaller or larger than the source
6527 // elements we can use a matching integer vector type and then
6528 // truncate/sign extend
6529 EVT MatchingElementType =
6530 EVT::getIntegerVT(*DAG.getContext(),
6531 N0VT.getScalarType().getSizeInBits());
6532 EVT MatchingVectorType =
6533 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6534 N0VT.getVectorNumElements());
6536 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6538 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6539 return DAG.getNode(ISD::AND, DL, VT,
6540 DAG.getSExtOrTrunc(VsetCC, DL, VT),
6541 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6544 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6547 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6548 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6549 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6550 if (SCC.getNode()) return SCC;
6553 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6554 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6555 isa<ConstantSDNode>(N0.getOperand(1)) &&
6556 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6558 SDValue ShAmt = N0.getOperand(1);
6559 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6560 if (N0.getOpcode() == ISD::SHL) {
6561 SDValue InnerZExt = N0.getOperand(0);
6562 // If the original shl may be shifting out bits, do not perform this
6564 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6565 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6566 if (ShAmtVal > KnownZeroBits)
6572 // Ensure that the shift amount is wide enough for the shifted value.
6573 if (VT.getSizeInBits() >= 256)
6574 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6576 return DAG.getNode(N0.getOpcode(), DL, VT,
6577 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6584 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6585 SDValue N0 = N->getOperand(0);
6586 EVT VT = N->getValueType(0);
6588 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6590 return SDValue(Res, 0);
6592 // fold (aext (aext x)) -> (aext x)
6593 // fold (aext (zext x)) -> (zext x)
6594 // fold (aext (sext x)) -> (sext x)
6595 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6596 N0.getOpcode() == ISD::ZERO_EXTEND ||
6597 N0.getOpcode() == ISD::SIGN_EXTEND)
6598 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6600 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6601 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6602 if (N0.getOpcode() == ISD::TRUNCATE) {
6603 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6604 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6605 if (NarrowLoad.getNode() != N0.getNode()) {
6606 CombineTo(N0.getNode(), NarrowLoad);
6607 // CombineTo deleted the truncate, if needed, but not what's under it.
6610 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6614 // fold (aext (truncate x))
6615 if (N0.getOpcode() == ISD::TRUNCATE) {
6616 SDValue TruncOp = N0.getOperand(0);
6617 if (TruncOp.getValueType() == VT)
6618 return TruncOp; // x iff x size == zext size.
6619 if (TruncOp.getValueType().bitsGT(VT))
6620 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6621 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6624 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6625 // if the trunc is not free.
6626 if (N0.getOpcode() == ISD::AND &&
6627 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6628 N0.getOperand(1).getOpcode() == ISD::Constant &&
6629 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6630 N0.getValueType())) {
6631 SDValue X = N0.getOperand(0).getOperand(0);
6632 if (X.getValueType().bitsLT(VT)) {
6633 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6634 } else if (X.getValueType().bitsGT(VT)) {
6635 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6637 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6638 Mask = Mask.zext(VT.getSizeInBits());
6640 return DAG.getNode(ISD::AND, DL, VT,
6641 X, DAG.getConstant(Mask, DL, VT));
6644 // fold (aext (load x)) -> (aext (truncate (extload x)))
6645 // None of the supported targets knows how to perform load and any_ext
6646 // on vectors in one instruction. We only perform this transformation on
6648 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6649 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6650 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6651 bool DoXform = true;
6652 SmallVector<SDNode*, 4> SetCCs;
6653 if (!N0.hasOneUse())
6654 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6656 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6657 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6659 LN0->getBasePtr(), N0.getValueType(),
6660 LN0->getMemOperand());
6661 CombineTo(N, ExtLoad);
6662 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6663 N0.getValueType(), ExtLoad);
6664 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6665 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6667 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6671 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6672 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6673 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6674 if (N0.getOpcode() == ISD::LOAD &&
6675 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6677 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6678 ISD::LoadExtType ExtType = LN0->getExtensionType();
6679 EVT MemVT = LN0->getMemoryVT();
6680 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6681 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6682 VT, LN0->getChain(), LN0->getBasePtr(),
6683 MemVT, LN0->getMemOperand());
6684 CombineTo(N, ExtLoad);
6685 CombineTo(N0.getNode(),
6686 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6687 N0.getValueType(), ExtLoad),
6688 ExtLoad.getValue(1));
6689 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6693 if (N0.getOpcode() == ISD::SETCC) {
6695 // aext(setcc) -> vsetcc
6696 // aext(setcc) -> truncate(vsetcc)
6697 // aext(setcc) -> aext(vsetcc)
6698 // Only do this before legalize for now.
6699 if (VT.isVector() && !LegalOperations) {
6700 EVT N0VT = N0.getOperand(0).getValueType();
6701 // We know that the # elements of the results is the same as the
6702 // # elements of the compare (and the # elements of the compare result
6703 // for that matter). Check to see that they are the same size. If so,
6704 // we know that the element size of the sext'd result matches the
6705 // element size of the compare operands.
6706 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6707 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6709 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6710 // If the desired elements are smaller or larger than the source
6711 // elements we can use a matching integer vector type and then
6712 // truncate/any extend
6714 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6716 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6718 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6719 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6723 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6726 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6727 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6728 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6736 /// See if the specified operand can be simplified with the knowledge that only
6737 /// the bits specified by Mask are used. If so, return the simpler operand,
6738 /// otherwise return a null SDValue.
6739 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6740 switch (V.getOpcode()) {
6742 case ISD::Constant: {
6743 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6744 assert(CV && "Const value should be ConstSDNode.");
6745 const APInt &CVal = CV->getAPIntValue();
6746 APInt NewVal = CVal & Mask;
6748 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6753 // If the LHS or RHS don't contribute bits to the or, drop them.
6754 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6755 return V.getOperand(1);
6756 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6757 return V.getOperand(0);
6760 // Only look at single-use SRLs.
6761 if (!V.getNode()->hasOneUse())
6763 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6764 // See if we can recursively simplify the LHS.
6765 unsigned Amt = RHSC->getZExtValue();
6767 // Watch out for shift count overflow though.
6768 if (Amt >= Mask.getBitWidth()) break;
6769 APInt NewMask = Mask << Amt;
6770 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6771 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6772 SimplifyLHS, V.getOperand(1));
6778 /// If the result of a wider load is shifted to right of N bits and then
6779 /// truncated to a narrower type and where N is a multiple of number of bits of
6780 /// the narrower type, transform it to a narrower load from address + N / num of
6781 /// bits of new type. If the result is to be extended, also fold the extension
6782 /// to form a extending load.
6783 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6784 unsigned Opc = N->getOpcode();
6786 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6787 SDValue N0 = N->getOperand(0);
6788 EVT VT = N->getValueType(0);
6791 // This transformation isn't valid for vector loads.
6795 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6797 if (Opc == ISD::SIGN_EXTEND_INREG) {
6798 ExtType = ISD::SEXTLOAD;
6799 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6800 } else if (Opc == ISD::SRL) {
6801 // Another special-case: SRL is basically zero-extending a narrower value.
6802 ExtType = ISD::ZEXTLOAD;
6804 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6805 if (!N01) return SDValue();
6806 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6807 VT.getSizeInBits() - N01->getZExtValue());
6809 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6812 unsigned EVTBits = ExtVT.getSizeInBits();
6814 // Do not generate loads of non-round integer types since these can
6815 // be expensive (and would be wrong if the type is not byte sized).
6816 if (!ExtVT.isRound())
6820 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6821 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6822 ShAmt = N01->getZExtValue();
6823 // Is the shift amount a multiple of size of VT?
6824 if ((ShAmt & (EVTBits-1)) == 0) {
6825 N0 = N0.getOperand(0);
6826 // Is the load width a multiple of size of VT?
6827 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6831 // At this point, we must have a load or else we can't do the transform.
6832 if (!isa<LoadSDNode>(N0)) return SDValue();
6834 // Because a SRL must be assumed to *need* to zero-extend the high bits
6835 // (as opposed to anyext the high bits), we can't combine the zextload
6836 // lowering of SRL and an sextload.
6837 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6840 // If the shift amount is larger than the input type then we're not
6841 // accessing any of the loaded bytes. If the load was a zextload/extload
6842 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6843 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6848 // If the load is shifted left (and the result isn't shifted back right),
6849 // we can fold the truncate through the shift.
6850 unsigned ShLeftAmt = 0;
6851 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6852 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6853 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6854 ShLeftAmt = N01->getZExtValue();
6855 N0 = N0.getOperand(0);
6859 // If we haven't found a load, we can't narrow it. Don't transform one with
6860 // multiple uses, this would require adding a new load.
6861 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6864 // Don't change the width of a volatile load.
6865 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6866 if (LN0->isVolatile())
6869 // Verify that we are actually reducing a load width here.
6870 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6873 // For the transform to be legal, the load must produce only two values
6874 // (the value loaded and the chain). Don't transform a pre-increment
6875 // load, for example, which produces an extra value. Otherwise the
6876 // transformation is not equivalent, and the downstream logic to replace
6877 // uses gets things wrong.
6878 if (LN0->getNumValues() > 2)
6881 // If the load that we're shrinking is an extload and we're not just
6882 // discarding the extension we can't simply shrink the load. Bail.
6883 // TODO: It would be possible to merge the extensions in some cases.
6884 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6885 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6888 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6891 EVT PtrType = N0.getOperand(1).getValueType();
6893 if (PtrType == MVT::Untyped || PtrType.isExtended())
6894 // It's not possible to generate a constant of extended or untyped type.
6897 // For big endian targets, we need to adjust the offset to the pointer to
6898 // load the correct bytes.
6899 if (DAG.getDataLayout().isBigEndian()) {
6900 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6901 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6902 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6905 uint64_t PtrOff = ShAmt / 8;
6906 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6908 // The original load itself didn't wrap, so an offset within it doesn't.
6910 Flags.setNoUnsignedWrap(true);
6911 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6912 PtrType, LN0->getBasePtr(),
6913 DAG.getConstant(PtrOff, DL, PtrType),
6915 AddToWorklist(NewPtr.getNode());
6918 if (ExtType == ISD::NON_EXTLOAD)
6919 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6920 LN0->getPointerInfo().getWithOffset(PtrOff),
6921 LN0->isVolatile(), LN0->isNonTemporal(),
6922 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6924 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6925 LN0->getPointerInfo().getWithOffset(PtrOff),
6926 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6927 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6929 // Replace the old load's chain with the new load's chain.
6930 WorklistRemover DeadNodes(*this);
6931 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6933 // Shift the result left, if we've swallowed a left shift.
6934 SDValue Result = Load;
6935 if (ShLeftAmt != 0) {
6936 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6937 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6939 // If the shift amount is as large as the result size (but, presumably,
6940 // no larger than the source) then the useful bits of the result are
6941 // zero; we can't simply return the shortened shift, because the result
6942 // of that operation is undefined.
6944 if (ShLeftAmt >= VT.getSizeInBits())
6945 Result = DAG.getConstant(0, DL, VT);
6947 Result = DAG.getNode(ISD::SHL, DL, VT,
6948 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6951 // Return the new loaded value.
6955 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6956 SDValue N0 = N->getOperand(0);
6957 SDValue N1 = N->getOperand(1);
6958 EVT VT = N->getValueType(0);
6959 EVT EVT = cast<VTSDNode>(N1)->getVT();
6960 unsigned VTBits = VT.getScalarType().getSizeInBits();
6961 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6964 return DAG.getUNDEF(VT);
6966 // fold (sext_in_reg c1) -> c1
6967 if (isConstantIntBuildVectorOrConstantInt(N0))
6968 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6970 // If the input is already sign extended, just drop the extension.
6971 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6974 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6975 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6976 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6977 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6978 N0.getOperand(0), N1);
6980 // fold (sext_in_reg (sext x)) -> (sext x)
6981 // fold (sext_in_reg (aext x)) -> (sext x)
6982 // if x is small enough.
6983 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6984 SDValue N00 = N0.getOperand(0);
6985 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6986 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6987 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6990 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6991 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6992 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6994 // fold operands of sext_in_reg based on knowledge that the top bits are not
6996 if (SimplifyDemandedBits(SDValue(N, 0)))
6997 return SDValue(N, 0);
6999 // fold (sext_in_reg (load x)) -> (smaller sextload x)
7000 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
7001 if (SDValue NarrowLoad = ReduceLoadWidth(N))
7004 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
7005 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
7006 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
7007 if (N0.getOpcode() == ISD::SRL) {
7008 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
7009 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
7010 // We can turn this into an SRA iff the input to the SRL is already sign
7012 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
7013 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
7014 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
7015 N0.getOperand(0), N0.getOperand(1));
7019 // fold (sext_inreg (extload x)) -> (sextload x)
7020 if (ISD::isEXTLoad(N0.getNode()) &&
7021 ISD::isUNINDEXEDLoad(N0.getNode()) &&
7022 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7023 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7024 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7025 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7026 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7028 LN0->getBasePtr(), EVT,
7029 LN0->getMemOperand());
7030 CombineTo(N, ExtLoad);
7031 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7032 AddToWorklist(ExtLoad.getNode());
7033 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7035 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
7036 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7038 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7039 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7040 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7041 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7042 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7044 LN0->getBasePtr(), EVT,
7045 LN0->getMemOperand());
7046 CombineTo(N, ExtLoad);
7047 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7048 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7051 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
7052 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
7053 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
7054 N0.getOperand(1), false);
7055 if (BSwap.getNode())
7056 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7063 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
7064 SDValue N0 = N->getOperand(0);
7065 EVT VT = N->getValueType(0);
7067 if (N0.getOpcode() == ISD::UNDEF)
7068 return DAG.getUNDEF(VT);
7070 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7072 return SDValue(Res, 0);
7077 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
7078 SDValue N0 = N->getOperand(0);
7079 EVT VT = N->getValueType(0);
7080 bool isLE = DAG.getDataLayout().isLittleEndian();
7083 if (N0.getValueType() == N->getValueType(0))
7085 // fold (truncate c1) -> c1
7086 if (isConstantIntBuildVectorOrConstantInt(N0))
7087 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
7088 // fold (truncate (truncate x)) -> (truncate x)
7089 if (N0.getOpcode() == ISD::TRUNCATE)
7090 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7091 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
7092 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
7093 N0.getOpcode() == ISD::SIGN_EXTEND ||
7094 N0.getOpcode() == ISD::ANY_EXTEND) {
7095 if (N0.getOperand(0).getValueType().bitsLT(VT))
7096 // if the source is smaller than the dest, we still need an extend
7097 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
7099 if (N0.getOperand(0).getValueType().bitsGT(VT))
7100 // if the source is larger than the dest, than we just need the truncate
7101 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7102 // if the source and dest are the same type, we can drop both the extend
7103 // and the truncate.
7104 return N0.getOperand(0);
7107 // Fold extract-and-trunc into a narrow extract. For example:
7108 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
7109 // i32 y = TRUNCATE(i64 x)
7111 // v16i8 b = BITCAST (v2i64 val)
7112 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
7114 // Note: We only run this optimization after type legalization (which often
7115 // creates this pattern) and before operation legalization after which
7116 // we need to be more careful about the vector instructions that we generate.
7117 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7118 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
7120 EVT VecTy = N0.getOperand(0).getValueType();
7121 EVT ExTy = N0.getValueType();
7122 EVT TrTy = N->getValueType(0);
7124 unsigned NumElem = VecTy.getVectorNumElements();
7125 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
7127 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
7128 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
7130 SDValue EltNo = N0->getOperand(1);
7131 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
7132 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7133 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7134 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
7136 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
7137 NVT, N0.getOperand(0));
7140 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
7142 DAG.getConstant(Index, DL, IndexTy));
7146 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
7147 if (N0.getOpcode() == ISD::SELECT) {
7148 EVT SrcVT = N0.getValueType();
7149 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
7150 TLI.isTruncateFree(SrcVT, VT)) {
7152 SDValue Cond = N0.getOperand(0);
7153 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7154 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7155 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7159 // Fold a series of buildvector, bitcast, and truncate if possible.
7161 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7162 // (2xi32 (buildvector x, y)).
7163 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7164 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7165 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7166 N0.getOperand(0).hasOneUse()) {
7168 SDValue BuildVect = N0.getOperand(0);
7169 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7170 EVT TruncVecEltTy = VT.getVectorElementType();
7172 // Check that the element types match.
7173 if (BuildVectEltTy == TruncVecEltTy) {
7174 // Now we only need to compute the offset of the truncated elements.
7175 unsigned BuildVecNumElts = BuildVect.getNumOperands();
7176 unsigned TruncVecNumElts = VT.getVectorNumElements();
7177 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7179 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7180 "Invalid number of elements");
7182 SmallVector<SDValue, 8> Opnds;
7183 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7184 Opnds.push_back(BuildVect.getOperand(i));
7186 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
7190 // See if we can simplify the input to this truncate through knowledge that
7191 // only the low bits are being used.
7192 // For example "trunc (or (shl x, 8), y)" // -> trunc y
7193 // Currently we only perform this optimization on scalars because vectors
7194 // may have different active low bits.
7195 if (!VT.isVector()) {
7197 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7198 VT.getSizeInBits()));
7199 if (Shorter.getNode())
7200 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7202 // fold (truncate (load x)) -> (smaller load x)
7203 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7204 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7205 if (SDValue Reduced = ReduceLoadWidth(N))
7208 // Handle the case where the load remains an extending load even
7209 // after truncation.
7210 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7211 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7212 if (!LN0->isVolatile() &&
7213 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7214 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7215 VT, LN0->getChain(), LN0->getBasePtr(),
7217 LN0->getMemOperand());
7218 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7223 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7224 // where ... are all 'undef'.
7225 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7226 SmallVector<EVT, 8> VTs;
7229 unsigned NumDefs = 0;
7231 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7232 SDValue X = N0.getOperand(i);
7233 if (X.getOpcode() != ISD::UNDEF) {
7238 // Stop if more than one members are non-undef.
7241 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7242 VT.getVectorElementType(),
7243 X.getValueType().getVectorNumElements()));
7247 return DAG.getUNDEF(VT);
7250 assert(V.getNode() && "The single defined operand is empty!");
7251 SmallVector<SDValue, 8> Opnds;
7252 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7254 Opnds.push_back(DAG.getUNDEF(VTs[i]));
7257 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7258 AddToWorklist(NV.getNode());
7259 Opnds.push_back(NV);
7261 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7265 // Simplify the operands using demanded-bits information.
7266 if (!VT.isVector() &&
7267 SimplifyDemandedBits(SDValue(N, 0)))
7268 return SDValue(N, 0);
7273 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7274 SDValue Elt = N->getOperand(i);
7275 if (Elt.getOpcode() != ISD::MERGE_VALUES)
7276 return Elt.getNode();
7277 return Elt.getOperand(Elt.getResNo()).getNode();
7280 /// build_pair (load, load) -> load
7281 /// if load locations are consecutive.
7282 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7283 assert(N->getOpcode() == ISD::BUILD_PAIR);
7285 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7286 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7287 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7288 LD1->getAddressSpace() != LD2->getAddressSpace())
7290 EVT LD1VT = LD1->getValueType(0);
7292 if (ISD::isNON_EXTLoad(LD2) &&
7294 // If both are volatile this would reduce the number of volatile loads.
7295 // If one is volatile it might be ok, but play conservative and bail out.
7296 !LD1->isVolatile() &&
7297 !LD2->isVolatile() &&
7298 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7299 unsigned Align = LD1->getAlignment();
7300 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7301 VT.getTypeForEVT(*DAG.getContext()));
7303 if (NewAlign <= Align &&
7304 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7305 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7306 LD1->getBasePtr(), LD1->getPointerInfo(),
7307 false, false, false, Align);
7313 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
7314 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
7315 // and Lo parts; on big-endian machines it doesn't.
7316 return DAG.getDataLayout().isBigEndian() ? 1 : 0;
7319 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7320 SDValue N0 = N->getOperand(0);
7321 EVT VT = N->getValueType(0);
7323 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7324 // Only do this before legalize, since afterward the target may be depending
7325 // on the bitconvert.
7326 // First check to see if this is all constant.
7328 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7330 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7332 EVT DestEltVT = N->getValueType(0).getVectorElementType();
7333 assert(!DestEltVT.isVector() &&
7334 "Element type of vector ValueType must not be vector!");
7336 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7339 // If the input is a constant, let getNode fold it.
7340 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7341 // If we can't allow illegal operations, we need to check that this is just
7342 // a fp -> int or int -> conversion and that the resulting operation will
7344 if (!LegalOperations ||
7345 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7346 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7347 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7348 TLI.isOperationLegal(ISD::Constant, VT)))
7349 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7352 // (conv (conv x, t1), t2) -> (conv x, t2)
7353 if (N0.getOpcode() == ISD::BITCAST)
7354 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7357 // fold (conv (load x)) -> (load (conv*)x)
7358 // If the resultant load doesn't need a higher alignment than the original!
7359 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7360 // Do not change the width of a volatile load.
7361 !cast<LoadSDNode>(N0)->isVolatile() &&
7362 // Do not remove the cast if the types differ in endian layout.
7363 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7364 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7365 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7366 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7367 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7368 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7369 VT.getTypeForEVT(*DAG.getContext()));
7370 unsigned OrigAlign = LN0->getAlignment();
7372 if (Align <= OrigAlign) {
7373 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7374 LN0->getBasePtr(), LN0->getPointerInfo(),
7375 LN0->isVolatile(), LN0->isNonTemporal(),
7376 LN0->isInvariant(), OrigAlign,
7378 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7383 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7384 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7387 // fold (bitcast (fneg x)) ->
7388 // flipbit = signbit
7389 // (xor (bitcast x) (build_pair flipbit, flipbit))
7391 // fold (bitcast (fabs x)) ->
7392 // flipbit = (and (extract_element (bitcast x), 0), signbit)
7393 // (xor (bitcast x) (build_pair flipbit, flipbit))
7394 // This often reduces constant pool loads.
7395 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7396 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7397 N0.getNode()->hasOneUse() && VT.isInteger() &&
7398 !VT.isVector() && !N0.getValueType().isVector()) {
7399 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7401 AddToWorklist(NewConv.getNode());
7404 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7405 assert(VT.getSizeInBits() == 128);
7406 SDValue SignBit = DAG.getConstant(
7407 APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
7409 if (N0.getOpcode() == ISD::FNEG) {
7411 AddToWorklist(FlipBit.getNode());
7413 assert(N0.getOpcode() == ISD::FABS);
7415 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
7416 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7418 AddToWorklist(Hi.getNode());
7419 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
7420 AddToWorklist(FlipBit.getNode());
7423 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7424 AddToWorklist(FlipBits.getNode());
7425 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
7427 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7428 if (N0.getOpcode() == ISD::FNEG)
7429 return DAG.getNode(ISD::XOR, DL, VT,
7430 NewConv, DAG.getConstant(SignBit, DL, VT));
7431 assert(N0.getOpcode() == ISD::FABS);
7432 return DAG.getNode(ISD::AND, DL, VT,
7433 NewConv, DAG.getConstant(~SignBit, DL, VT));
7436 // fold (bitconvert (fcopysign cst, x)) ->
7437 // (or (and (bitconvert x), sign), (and cst, (not sign)))
7438 // Note that we don't handle (copysign x, cst) because this can always be
7439 // folded to an fneg or fabs.
7442 // fold (bitcast (fcopysign cst, x)) ->
7443 // flipbit = (and (extract_element
7444 // (xor (bitcast cst), (bitcast x)), 0),
7446 // (xor (bitcast cst) (build_pair flipbit, flipbit))
7447 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7448 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7449 VT.isInteger() && !VT.isVector()) {
7450 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7451 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7452 if (isTypeLegal(IntXVT)) {
7453 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7454 IntXVT, N0.getOperand(1));
7455 AddToWorklist(X.getNode());
7457 // If X has a different width than the result/lhs, sext it or truncate it.
7458 unsigned VTWidth = VT.getSizeInBits();
7459 if (OrigXWidth < VTWidth) {
7460 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7461 AddToWorklist(X.getNode());
7462 } else if (OrigXWidth > VTWidth) {
7463 // To get the sign bit in the right place, we have to shift it right
7464 // before truncating.
7466 X = DAG.getNode(ISD::SRL, DL,
7467 X.getValueType(), X,
7468 DAG.getConstant(OrigXWidth-VTWidth, DL,
7470 AddToWorklist(X.getNode());
7471 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7472 AddToWorklist(X.getNode());
7475 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7476 APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2);
7477 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0.getOperand(0)), VT,
7479 AddToWorklist(Cst.getNode());
7480 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0.getOperand(1)), VT,
7482 AddToWorklist(X.getNode());
7483 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
7484 AddToWorklist(XorResult.getNode());
7485 SDValue XorResult64 = DAG.getNode(
7486 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
7487 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7489 AddToWorklist(XorResult64.getNode());
7491 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
7492 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
7493 AddToWorklist(FlipBit.getNode());
7495 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7496 AddToWorklist(FlipBits.getNode());
7497 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
7499 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7500 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7501 X, DAG.getConstant(SignBit, SDLoc(X), VT));
7502 AddToWorklist(X.getNode());
7504 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7505 VT, N0.getOperand(0));
7506 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7507 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7508 AddToWorklist(Cst.getNode());
7510 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7514 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7515 if (N0.getOpcode() == ISD::BUILD_PAIR)
7516 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7519 // Remove double bitcasts from shuffles - this is often a legacy of
7520 // XformToShuffleWithZero being used to combine bitmaskings (of
7521 // float vectors bitcast to integer vectors) into shuffles.
7522 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7523 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7524 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7525 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7526 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7527 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7529 // If operands are a bitcast, peek through if it casts the original VT.
7530 // If operands are a constant, just bitcast back to original VT.
7531 auto PeekThroughBitcast = [&](SDValue Op) {
7532 if (Op.getOpcode() == ISD::BITCAST &&
7533 Op.getOperand(0).getValueType() == VT)
7534 return SDValue(Op.getOperand(0));
7535 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7536 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7537 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7541 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7542 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7547 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7548 SmallVector<int, 8> NewMask;
7549 for (int M : SVN->getMask())
7550 for (int i = 0; i != MaskScale; ++i)
7551 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7553 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7555 std::swap(SV0, SV1);
7556 ShuffleVectorSDNode::commuteMask(NewMask);
7557 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7561 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7567 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7568 EVT VT = N->getValueType(0);
7569 return CombineConsecutiveLoads(N, VT);
7572 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7573 /// operands. DstEltVT indicates the destination element value type.
7574 SDValue DAGCombiner::
7575 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7576 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7578 // If this is already the right type, we're done.
7579 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7581 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7582 unsigned DstBitSize = DstEltVT.getSizeInBits();
7584 // If this is a conversion of N elements of one type to N elements of another
7585 // type, convert each element. This handles FP<->INT cases.
7586 if (SrcBitSize == DstBitSize) {
7587 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7588 BV->getValueType(0).getVectorNumElements());
7590 // Due to the FP element handling below calling this routine recursively,
7591 // we can end up with a scalar-to-vector node here.
7592 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7593 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7594 DAG.getNode(ISD::BITCAST, SDLoc(BV),
7595 DstEltVT, BV->getOperand(0)));
7597 SmallVector<SDValue, 8> Ops;
7598 for (SDValue Op : BV->op_values()) {
7599 // If the vector element type is not legal, the BUILD_VECTOR operands
7600 // are promoted and implicitly truncated. Make that explicit here.
7601 if (Op.getValueType() != SrcEltVT)
7602 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7603 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7605 AddToWorklist(Ops.back().getNode());
7607 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7610 // Otherwise, we're growing or shrinking the elements. To avoid having to
7611 // handle annoying details of growing/shrinking FP values, we convert them to
7613 if (SrcEltVT.isFloatingPoint()) {
7614 // Convert the input float vector to a int vector where the elements are the
7616 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7617 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7621 // Now we know the input is an integer vector. If the output is a FP type,
7622 // convert to integer first, then to FP of the right size.
7623 if (DstEltVT.isFloatingPoint()) {
7624 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7625 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7627 // Next, convert to FP elements of the same size.
7628 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7633 // Okay, we know the src/dst types are both integers of differing types.
7634 // Handling growing first.
7635 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7636 if (SrcBitSize < DstBitSize) {
7637 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7639 SmallVector<SDValue, 8> Ops;
7640 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7641 i += NumInputsPerOutput) {
7642 bool isLE = DAG.getDataLayout().isLittleEndian();
7643 APInt NewBits = APInt(DstBitSize, 0);
7644 bool EltIsUndef = true;
7645 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7646 // Shift the previously computed bits over.
7647 NewBits <<= SrcBitSize;
7648 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7649 if (Op.getOpcode() == ISD::UNDEF) continue;
7652 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7653 zextOrTrunc(SrcBitSize).zext(DstBitSize);
7657 Ops.push_back(DAG.getUNDEF(DstEltVT));
7659 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7662 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7663 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7666 // Finally, this must be the case where we are shrinking elements: each input
7667 // turns into multiple outputs.
7668 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7669 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7670 NumOutputsPerInput*BV->getNumOperands());
7671 SmallVector<SDValue, 8> Ops;
7673 for (const SDValue &Op : BV->op_values()) {
7674 if (Op.getOpcode() == ISD::UNDEF) {
7675 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7679 APInt OpVal = cast<ConstantSDNode>(Op)->
7680 getAPIntValue().zextOrTrunc(SrcBitSize);
7682 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7683 APInt ThisVal = OpVal.trunc(DstBitSize);
7684 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7685 OpVal = OpVal.lshr(DstBitSize);
7688 // For big endian targets, swap the order of the pieces of each element.
7689 if (DAG.getDataLayout().isBigEndian())
7690 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7693 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7696 /// Try to perform FMA combining on a given FADD node.
7697 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7698 SDValue N0 = N->getOperand(0);
7699 SDValue N1 = N->getOperand(1);
7700 EVT VT = N->getValueType(0);
7703 const TargetOptions &Options = DAG.getTarget().Options;
7705 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7707 // Floating-point multiply-add with intermediate rounding.
7708 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7710 // Floating-point multiply-add without intermediate rounding.
7712 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7713 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7715 // No valid opcode, do not combine.
7716 if (!HasFMAD && !HasFMA)
7719 // Always prefer FMAD to FMA for precision.
7720 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7721 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7722 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7724 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7725 // prefer to fold the multiply with fewer uses.
7726 if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7727 N1.getOpcode() == ISD::FMUL) {
7728 if (N0.getNode()->use_size() > N1.getNode()->use_size())
7732 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7733 if (N0.getOpcode() == ISD::FMUL &&
7734 (Aggressive || N0->hasOneUse())) {
7735 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7736 N0.getOperand(0), N0.getOperand(1), N1);
7739 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7740 // Note: Commutes FADD operands.
7741 if (N1.getOpcode() == ISD::FMUL &&
7742 (Aggressive || N1->hasOneUse())) {
7743 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7744 N1.getOperand(0), N1.getOperand(1), N0);
7747 // Look through FP_EXTEND nodes to do more combining.
7748 if (AllowFusion && LookThroughFPExt) {
7749 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7750 if (N0.getOpcode() == ISD::FP_EXTEND) {
7751 SDValue N00 = N0.getOperand(0);
7752 if (N00.getOpcode() == ISD::FMUL)
7753 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7754 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7756 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7757 N00.getOperand(1)), N1);
7760 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7761 // Note: Commutes FADD operands.
7762 if (N1.getOpcode() == ISD::FP_EXTEND) {
7763 SDValue N10 = N1.getOperand(0);
7764 if (N10.getOpcode() == ISD::FMUL)
7765 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7766 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7768 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7769 N10.getOperand(1)), N0);
7773 // More folding opportunities when target permits.
7774 if ((AllowFusion || HasFMAD) && Aggressive) {
7775 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7776 if (N0.getOpcode() == PreferredFusedOpcode &&
7777 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7778 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7779 N0.getOperand(0), N0.getOperand(1),
7780 DAG.getNode(PreferredFusedOpcode, SL, VT,
7781 N0.getOperand(2).getOperand(0),
7782 N0.getOperand(2).getOperand(1),
7786 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7787 if (N1->getOpcode() == PreferredFusedOpcode &&
7788 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7789 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7790 N1.getOperand(0), N1.getOperand(1),
7791 DAG.getNode(PreferredFusedOpcode, SL, VT,
7792 N1.getOperand(2).getOperand(0),
7793 N1.getOperand(2).getOperand(1),
7797 if (AllowFusion && LookThroughFPExt) {
7798 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7799 // -> (fma x, y, (fma (fpext u), (fpext v), z))
7800 auto FoldFAddFMAFPExtFMul = [&] (
7801 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7802 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7803 DAG.getNode(PreferredFusedOpcode, SL, VT,
7804 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7805 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7808 if (N0.getOpcode() == PreferredFusedOpcode) {
7809 SDValue N02 = N0.getOperand(2);
7810 if (N02.getOpcode() == ISD::FP_EXTEND) {
7811 SDValue N020 = N02.getOperand(0);
7812 if (N020.getOpcode() == ISD::FMUL)
7813 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7814 N020.getOperand(0), N020.getOperand(1),
7819 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7820 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7821 // FIXME: This turns two single-precision and one double-precision
7822 // operation into two double-precision operations, which might not be
7823 // interesting for all targets, especially GPUs.
7824 auto FoldFAddFPExtFMAFMul = [&] (
7825 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7826 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7827 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7828 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7829 DAG.getNode(PreferredFusedOpcode, SL, VT,
7830 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7831 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7834 if (N0.getOpcode() == ISD::FP_EXTEND) {
7835 SDValue N00 = N0.getOperand(0);
7836 if (N00.getOpcode() == PreferredFusedOpcode) {
7837 SDValue N002 = N00.getOperand(2);
7838 if (N002.getOpcode() == ISD::FMUL)
7839 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7840 N002.getOperand(0), N002.getOperand(1),
7845 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7846 // -> (fma y, z, (fma (fpext u), (fpext v), x))
7847 if (N1.getOpcode() == PreferredFusedOpcode) {
7848 SDValue N12 = N1.getOperand(2);
7849 if (N12.getOpcode() == ISD::FP_EXTEND) {
7850 SDValue N120 = N12.getOperand(0);
7851 if (N120.getOpcode() == ISD::FMUL)
7852 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7853 N120.getOperand(0), N120.getOperand(1),
7858 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7859 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7860 // FIXME: This turns two single-precision and one double-precision
7861 // operation into two double-precision operations, which might not be
7862 // interesting for all targets, especially GPUs.
7863 if (N1.getOpcode() == ISD::FP_EXTEND) {
7864 SDValue N10 = N1.getOperand(0);
7865 if (N10.getOpcode() == PreferredFusedOpcode) {
7866 SDValue N102 = N10.getOperand(2);
7867 if (N102.getOpcode() == ISD::FMUL)
7868 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7869 N102.getOperand(0), N102.getOperand(1),
7879 /// Try to perform FMA combining on a given FSUB node.
7880 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7881 SDValue N0 = N->getOperand(0);
7882 SDValue N1 = N->getOperand(1);
7883 EVT VT = N->getValueType(0);
7886 const TargetOptions &Options = DAG.getTarget().Options;
7888 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7890 // Floating-point multiply-add with intermediate rounding.
7891 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7893 // Floating-point multiply-add without intermediate rounding.
7895 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7896 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7898 // No valid opcode, do not combine.
7899 if (!HasFMAD && !HasFMA)
7902 // Always prefer FMAD to FMA for precision.
7903 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7904 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7905 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7907 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7908 if (N0.getOpcode() == ISD::FMUL &&
7909 (Aggressive || N0->hasOneUse())) {
7910 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7911 N0.getOperand(0), N0.getOperand(1),
7912 DAG.getNode(ISD::FNEG, SL, VT, N1));
7915 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7916 // Note: Commutes FSUB operands.
7917 if (N1.getOpcode() == ISD::FMUL &&
7918 (Aggressive || N1->hasOneUse()))
7919 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7920 DAG.getNode(ISD::FNEG, SL, VT,
7922 N1.getOperand(1), N0);
7924 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7925 if (N0.getOpcode() == ISD::FNEG &&
7926 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7927 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7928 SDValue N00 = N0.getOperand(0).getOperand(0);
7929 SDValue N01 = N0.getOperand(0).getOperand(1);
7930 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7931 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7932 DAG.getNode(ISD::FNEG, SL, VT, N1));
7935 // Look through FP_EXTEND nodes to do more combining.
7936 if (AllowFusion && LookThroughFPExt) {
7937 // fold (fsub (fpext (fmul x, y)), z)
7938 // -> (fma (fpext x), (fpext y), (fneg z))
7939 if (N0.getOpcode() == ISD::FP_EXTEND) {
7940 SDValue N00 = N0.getOperand(0);
7941 if (N00.getOpcode() == ISD::FMUL)
7942 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7943 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7945 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7947 DAG.getNode(ISD::FNEG, SL, VT, N1));
7950 // fold (fsub x, (fpext (fmul y, z)))
7951 // -> (fma (fneg (fpext y)), (fpext z), x)
7952 // Note: Commutes FSUB operands.
7953 if (N1.getOpcode() == ISD::FP_EXTEND) {
7954 SDValue N10 = N1.getOperand(0);
7955 if (N10.getOpcode() == ISD::FMUL)
7956 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7957 DAG.getNode(ISD::FNEG, SL, VT,
7958 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7959 N10.getOperand(0))),
7960 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7965 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7966 // -> (fneg (fma (fpext x), (fpext y), z))
7967 // Note: This could be removed with appropriate canonicalization of the
7968 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7969 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7970 // from implementing the canonicalization in visitFSUB.
7971 if (N0.getOpcode() == ISD::FP_EXTEND) {
7972 SDValue N00 = N0.getOperand(0);
7973 if (N00.getOpcode() == ISD::FNEG) {
7974 SDValue N000 = N00.getOperand(0);
7975 if (N000.getOpcode() == ISD::FMUL) {
7976 return DAG.getNode(ISD::FNEG, SL, VT,
7977 DAG.getNode(PreferredFusedOpcode, SL, VT,
7978 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7979 N000.getOperand(0)),
7980 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7981 N000.getOperand(1)),
7987 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7988 // -> (fneg (fma (fpext x)), (fpext y), z)
7989 // Note: This could be removed with appropriate canonicalization of the
7990 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7991 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7992 // from implementing the canonicalization in visitFSUB.
7993 if (N0.getOpcode() == ISD::FNEG) {
7994 SDValue N00 = N0.getOperand(0);
7995 if (N00.getOpcode() == ISD::FP_EXTEND) {
7996 SDValue N000 = N00.getOperand(0);
7997 if (N000.getOpcode() == ISD::FMUL) {
7998 return DAG.getNode(ISD::FNEG, SL, VT,
7999 DAG.getNode(PreferredFusedOpcode, SL, VT,
8000 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8001 N000.getOperand(0)),
8002 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8003 N000.getOperand(1)),
8011 // More folding opportunities when target permits.
8012 if ((AllowFusion || HasFMAD) && Aggressive) {
8013 // fold (fsub (fma x, y, (fmul u, v)), z)
8014 // -> (fma x, y (fma u, v, (fneg z)))
8015 if (N0.getOpcode() == PreferredFusedOpcode &&
8016 N0.getOperand(2).getOpcode() == ISD::FMUL) {
8017 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8018 N0.getOperand(0), N0.getOperand(1),
8019 DAG.getNode(PreferredFusedOpcode, SL, VT,
8020 N0.getOperand(2).getOperand(0),
8021 N0.getOperand(2).getOperand(1),
8022 DAG.getNode(ISD::FNEG, SL, VT,
8026 // fold (fsub x, (fma y, z, (fmul u, v)))
8027 // -> (fma (fneg y), z, (fma (fneg u), v, x))
8028 if (N1.getOpcode() == PreferredFusedOpcode &&
8029 N1.getOperand(2).getOpcode() == ISD::FMUL) {
8030 SDValue N20 = N1.getOperand(2).getOperand(0);
8031 SDValue N21 = N1.getOperand(2).getOperand(1);
8032 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8033 DAG.getNode(ISD::FNEG, SL, VT,
8036 DAG.getNode(PreferredFusedOpcode, SL, VT,
8037 DAG.getNode(ISD::FNEG, SL, VT, N20),
8042 if (AllowFusion && LookThroughFPExt) {
8043 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
8044 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
8045 if (N0.getOpcode() == PreferredFusedOpcode) {
8046 SDValue N02 = N0.getOperand(2);
8047 if (N02.getOpcode() == ISD::FP_EXTEND) {
8048 SDValue N020 = N02.getOperand(0);
8049 if (N020.getOpcode() == ISD::FMUL)
8050 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8051 N0.getOperand(0), N0.getOperand(1),
8052 DAG.getNode(PreferredFusedOpcode, SL, VT,
8053 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8054 N020.getOperand(0)),
8055 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8056 N020.getOperand(1)),
8057 DAG.getNode(ISD::FNEG, SL, VT,
8062 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
8063 // -> (fma (fpext x), (fpext y),
8064 // (fma (fpext u), (fpext v), (fneg z)))
8065 // FIXME: This turns two single-precision and one double-precision
8066 // operation into two double-precision operations, which might not be
8067 // interesting for all targets, especially GPUs.
8068 if (N0.getOpcode() == ISD::FP_EXTEND) {
8069 SDValue N00 = N0.getOperand(0);
8070 if (N00.getOpcode() == PreferredFusedOpcode) {
8071 SDValue N002 = N00.getOperand(2);
8072 if (N002.getOpcode() == ISD::FMUL)
8073 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8074 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8076 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8078 DAG.getNode(PreferredFusedOpcode, SL, VT,
8079 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8080 N002.getOperand(0)),
8081 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8082 N002.getOperand(1)),
8083 DAG.getNode(ISD::FNEG, SL, VT,
8088 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
8089 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
8090 if (N1.getOpcode() == PreferredFusedOpcode &&
8091 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
8092 SDValue N120 = N1.getOperand(2).getOperand(0);
8093 if (N120.getOpcode() == ISD::FMUL) {
8094 SDValue N1200 = N120.getOperand(0);
8095 SDValue N1201 = N120.getOperand(1);
8096 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8097 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
8099 DAG.getNode(PreferredFusedOpcode, SL, VT,
8100 DAG.getNode(ISD::FNEG, SL, VT,
8101 DAG.getNode(ISD::FP_EXTEND, SL,
8103 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8109 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
8110 // -> (fma (fneg (fpext y)), (fpext z),
8111 // (fma (fneg (fpext u)), (fpext v), x))
8112 // FIXME: This turns two single-precision and one double-precision
8113 // operation into two double-precision operations, which might not be
8114 // interesting for all targets, especially GPUs.
8115 if (N1.getOpcode() == ISD::FP_EXTEND &&
8116 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
8117 SDValue N100 = N1.getOperand(0).getOperand(0);
8118 SDValue N101 = N1.getOperand(0).getOperand(1);
8119 SDValue N102 = N1.getOperand(0).getOperand(2);
8120 if (N102.getOpcode() == ISD::FMUL) {
8121 SDValue N1020 = N102.getOperand(0);
8122 SDValue N1021 = N102.getOperand(1);
8123 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8124 DAG.getNode(ISD::FNEG, SL, VT,
8125 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8127 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
8128 DAG.getNode(PreferredFusedOpcode, SL, VT,
8129 DAG.getNode(ISD::FNEG, SL, VT,
8130 DAG.getNode(ISD::FP_EXTEND, SL,
8132 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8143 /// Try to perform FMA combining on a given FMUL node.
8144 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
8145 SDValue N0 = N->getOperand(0);
8146 SDValue N1 = N->getOperand(1);
8147 EVT VT = N->getValueType(0);
8150 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
8152 const TargetOptions &Options = DAG.getTarget().Options;
8154 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8156 // Floating-point multiply-add with intermediate rounding.
8157 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8159 // Floating-point multiply-add without intermediate rounding.
8161 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8162 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8164 // No valid opcode, do not combine.
8165 if (!HasFMAD && !HasFMA)
8168 // Always prefer FMAD to FMA for precision.
8169 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8170 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8172 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
8173 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
8174 auto FuseFADD = [&](SDValue X, SDValue Y) {
8175 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
8176 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8177 if (XC1 && XC1->isExactlyValue(+1.0))
8178 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8179 if (XC1 && XC1->isExactlyValue(-1.0))
8180 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8181 DAG.getNode(ISD::FNEG, SL, VT, Y));
8186 if (SDValue FMA = FuseFADD(N0, N1))
8188 if (SDValue FMA = FuseFADD(N1, N0))
8191 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
8192 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
8193 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
8194 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
8195 auto FuseFSUB = [&](SDValue X, SDValue Y) {
8196 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
8197 auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
8198 if (XC0 && XC0->isExactlyValue(+1.0))
8199 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8200 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8202 if (XC0 && XC0->isExactlyValue(-1.0))
8203 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8204 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8205 DAG.getNode(ISD::FNEG, SL, VT, Y));
8207 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8208 if (XC1 && XC1->isExactlyValue(+1.0))
8209 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8210 DAG.getNode(ISD::FNEG, SL, VT, Y));
8211 if (XC1 && XC1->isExactlyValue(-1.0))
8212 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8217 if (SDValue FMA = FuseFSUB(N0, N1))
8219 if (SDValue FMA = FuseFSUB(N1, N0))
8225 SDValue DAGCombiner::visitFADD(SDNode *N) {
8226 SDValue N0 = N->getOperand(0);
8227 SDValue N1 = N->getOperand(1);
8228 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
8229 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8230 EVT VT = N->getValueType(0);
8232 const TargetOptions &Options = DAG.getTarget().Options;
8233 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8237 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8240 // fold (fadd c1, c2) -> c1 + c2
8242 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8244 // canonicalize constant to RHS
8245 if (N0CFP && !N1CFP)
8246 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8248 // fold (fadd A, (fneg B)) -> (fsub A, B)
8249 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8250 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8251 return DAG.getNode(ISD::FSUB, DL, VT, N0,
8252 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8254 // fold (fadd (fneg A), B) -> (fsub B, A)
8255 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8256 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8257 return DAG.getNode(ISD::FSUB, DL, VT, N1,
8258 GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8260 // If 'unsafe math' is enabled, fold lots of things.
8261 if (Options.UnsafeFPMath) {
8262 // No FP constant should be created after legalization as Instruction
8263 // Selection pass has a hard time dealing with FP constants.
8264 bool AllowNewConst = (Level < AfterLegalizeDAG);
8266 // fold (fadd A, 0) -> A
8267 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8271 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8272 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8273 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8274 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8275 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8279 // If allowed, fold (fadd (fneg x), x) -> 0.0
8280 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8281 return DAG.getConstantFP(0.0, DL, VT);
8283 // If allowed, fold (fadd x, (fneg x)) -> 0.0
8284 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8285 return DAG.getConstantFP(0.0, DL, VT);
8287 // We can fold chains of FADD's of the same value into multiplications.
8288 // This transform is not safe in general because we are reducing the number
8289 // of rounding steps.
8290 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8291 if (N0.getOpcode() == ISD::FMUL) {
8292 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8293 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8295 // (fadd (fmul x, c), x) -> (fmul x, c+1)
8296 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8297 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8298 DAG.getConstantFP(1.0, DL, VT), Flags);
8299 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8302 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8303 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8304 N1.getOperand(0) == N1.getOperand(1) &&
8305 N0.getOperand(0) == N1.getOperand(0)) {
8306 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8307 DAG.getConstantFP(2.0, DL, VT), Flags);
8308 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8312 if (N1.getOpcode() == ISD::FMUL) {
8313 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8314 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8316 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8317 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8318 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8319 DAG.getConstantFP(1.0, DL, VT), Flags);
8320 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8323 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8324 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8325 N0.getOperand(0) == N0.getOperand(1) &&
8326 N1.getOperand(0) == N0.getOperand(0)) {
8327 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8328 DAG.getConstantFP(2.0, DL, VT), Flags);
8329 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8333 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8334 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8335 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8336 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8337 (N0.getOperand(0) == N1)) {
8338 return DAG.getNode(ISD::FMUL, DL, VT,
8339 N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8343 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8344 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8345 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8346 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8347 N1.getOperand(0) == N0) {
8348 return DAG.getNode(ISD::FMUL, DL, VT,
8349 N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8353 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8354 if (AllowNewConst &&
8355 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8356 N0.getOperand(0) == N0.getOperand(1) &&
8357 N1.getOperand(0) == N1.getOperand(1) &&
8358 N0.getOperand(0) == N1.getOperand(0)) {
8359 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8360 DAG.getConstantFP(4.0, DL, VT), Flags);
8363 } // enable-unsafe-fp-math
8365 // FADD -> FMA combines:
8366 if (SDValue Fused = visitFADDForFMACombine(N)) {
8367 AddToWorklist(Fused.getNode());
8374 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8375 SDValue N0 = N->getOperand(0);
8376 SDValue N1 = N->getOperand(1);
8377 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8378 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8379 EVT VT = N->getValueType(0);
8381 const TargetOptions &Options = DAG.getTarget().Options;
8382 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8386 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8389 // fold (fsub c1, c2) -> c1-c2
8391 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags);
8393 // fold (fsub A, (fneg B)) -> (fadd A, B)
8394 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8395 return DAG.getNode(ISD::FADD, dl, VT, N0,
8396 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8398 // If 'unsafe math' is enabled, fold lots of things.
8399 if (Options.UnsafeFPMath) {
8401 if (N1CFP && N1CFP->isZero())
8404 // (fsub 0, B) -> -B
8405 if (N0CFP && N0CFP->isZero()) {
8406 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8407 return GetNegatedExpression(N1, DAG, LegalOperations);
8408 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8409 return DAG.getNode(ISD::FNEG, dl, VT, N1);
8412 // (fsub x, x) -> 0.0
8414 return DAG.getConstantFP(0.0f, dl, VT);
8416 // (fsub x, (fadd x, y)) -> (fneg y)
8417 // (fsub x, (fadd y, x)) -> (fneg y)
8418 if (N1.getOpcode() == ISD::FADD) {
8419 SDValue N10 = N1->getOperand(0);
8420 SDValue N11 = N1->getOperand(1);
8422 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8423 return GetNegatedExpression(N11, DAG, LegalOperations);
8425 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8426 return GetNegatedExpression(N10, DAG, LegalOperations);
8430 // FSUB -> FMA combines:
8431 if (SDValue Fused = visitFSUBForFMACombine(N)) {
8432 AddToWorklist(Fused.getNode());
8439 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8440 SDValue N0 = N->getOperand(0);
8441 SDValue N1 = N->getOperand(1);
8442 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8443 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8444 EVT VT = N->getValueType(0);
8446 const TargetOptions &Options = DAG.getTarget().Options;
8447 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8450 if (VT.isVector()) {
8451 // This just handles C1 * C2 for vectors. Other vector folds are below.
8452 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8456 // fold (fmul c1, c2) -> c1*c2
8458 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8460 // canonicalize constant to RHS
8461 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8462 !isConstantFPBuildVectorOrConstantFP(N1))
8463 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8465 // fold (fmul A, 1.0) -> A
8466 if (N1CFP && N1CFP->isExactlyValue(1.0))
8469 if (Options.UnsafeFPMath) {
8470 // fold (fmul A, 0) -> 0
8471 if (N1CFP && N1CFP->isZero())
8474 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8475 if (N0.getOpcode() == ISD::FMUL) {
8476 // Fold scalars or any vector constants (not just splats).
8477 // This fold is done in general by InstCombine, but extra fmul insts
8478 // may have been generated during lowering.
8479 SDValue N00 = N0.getOperand(0);
8480 SDValue N01 = N0.getOperand(1);
8481 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8482 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8483 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8485 // Check 1: Make sure that the first operand of the inner multiply is NOT
8486 // a constant. Otherwise, we may induce infinite looping.
8487 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8488 // Check 2: Make sure that the second operand of the inner multiply and
8489 // the second operand of the outer multiply are constants.
8490 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8491 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8492 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8493 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8498 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8499 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8500 // during an early run of DAGCombiner can prevent folding with fmuls
8501 // inserted during lowering.
8502 if (N0.getOpcode() == ISD::FADD &&
8503 (N0.getOperand(0) == N0.getOperand(1)) &&
8505 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8506 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8507 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8511 // fold (fmul X, 2.0) -> (fadd X, X)
8512 if (N1CFP && N1CFP->isExactlyValue(+2.0))
8513 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8515 // fold (fmul X, -1.0) -> (fneg X)
8516 if (N1CFP && N1CFP->isExactlyValue(-1.0))
8517 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8518 return DAG.getNode(ISD::FNEG, DL, VT, N0);
8520 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8521 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8522 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8523 // Both can be negated for free, check to see if at least one is cheaper
8525 if (LHSNeg == 2 || RHSNeg == 2)
8526 return DAG.getNode(ISD::FMUL, DL, VT,
8527 GetNegatedExpression(N0, DAG, LegalOperations),
8528 GetNegatedExpression(N1, DAG, LegalOperations),
8533 // FMUL -> FMA combines:
8534 if (SDValue Fused = visitFMULForFMACombine(N)) {
8535 AddToWorklist(Fused.getNode());
8542 SDValue DAGCombiner::visitFMA(SDNode *N) {
8543 SDValue N0 = N->getOperand(0);
8544 SDValue N1 = N->getOperand(1);
8545 SDValue N2 = N->getOperand(2);
8546 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8547 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8548 EVT VT = N->getValueType(0);
8550 const TargetOptions &Options = DAG.getTarget().Options;
8552 // Constant fold FMA.
8553 if (isa<ConstantFPSDNode>(N0) &&
8554 isa<ConstantFPSDNode>(N1) &&
8555 isa<ConstantFPSDNode>(N2)) {
8556 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8559 if (Options.UnsafeFPMath) {
8560 if (N0CFP && N0CFP->isZero())
8562 if (N1CFP && N1CFP->isZero())
8565 // TODO: The FMA node should have flags that propagate to these nodes.
8566 if (N0CFP && N0CFP->isExactlyValue(1.0))
8567 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8568 if (N1CFP && N1CFP->isExactlyValue(1.0))
8569 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8571 // Canonicalize (fma c, x, y) -> (fma x, c, y)
8572 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8573 !isConstantFPBuildVectorOrConstantFP(N1))
8574 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8576 // TODO: FMA nodes should have flags that propagate to the created nodes.
8577 // For now, create a Flags object for use with all unsafe math transforms.
8579 Flags.setUnsafeAlgebra(true);
8581 if (Options.UnsafeFPMath) {
8582 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8583 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8584 isConstantFPBuildVectorOrConstantFP(N1) &&
8585 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8586 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8587 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1),
8591 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8592 if (N0.getOpcode() == ISD::FMUL &&
8593 isConstantFPBuildVectorOrConstantFP(N1) &&
8594 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8595 return DAG.getNode(ISD::FMA, dl, VT,
8597 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1),
8603 // (fma x, 1, y) -> (fadd x, y)
8604 // (fma x, -1, y) -> (fadd (fneg x), y)
8606 if (N1CFP->isExactlyValue(1.0))
8607 // TODO: The FMA node should have flags that propagate to this node.
8608 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8610 if (N1CFP->isExactlyValue(-1.0) &&
8611 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8612 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8613 AddToWorklist(RHSNeg.getNode());
8614 // TODO: The FMA node should have flags that propagate to this node.
8615 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8619 if (Options.UnsafeFPMath) {
8620 // (fma x, c, x) -> (fmul x, (c+1))
8621 if (N1CFP && N0 == N2) {
8622 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8623 DAG.getNode(ISD::FADD, dl, VT,
8624 N1, DAG.getConstantFP(1.0, dl, VT),
8628 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8629 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8630 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8631 DAG.getNode(ISD::FADD, dl, VT,
8632 N1, DAG.getConstantFP(-1.0, dl, VT),
8640 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8642 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8643 // Notice that this is not always beneficial. One reason is different target
8644 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8645 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8646 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8647 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8648 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
8649 const SDNodeFlags *Flags = N->getFlags();
8650 if (!UnsafeMath && !Flags->hasAllowReciprocal())
8653 // Skip if current node is a reciprocal.
8654 SDValue N0 = N->getOperand(0);
8655 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8656 if (N0CFP && N0CFP->isExactlyValue(1.0))
8659 // Exit early if the target does not want this transform or if there can't
8660 // possibly be enough uses of the divisor to make the transform worthwhile.
8661 SDValue N1 = N->getOperand(1);
8662 unsigned MinUses = TLI.combineRepeatedFPDivisors();
8663 if (!MinUses || N1->use_size() < MinUses)
8666 // Find all FDIV users of the same divisor.
8667 // Use a set because duplicates may be present in the user list.
8668 SetVector<SDNode *> Users;
8669 for (auto *U : N1->uses()) {
8670 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
8671 // This division is eligible for optimization only if global unsafe math
8672 // is enabled or if this division allows reciprocal formation.
8673 if (UnsafeMath || U->getFlags()->hasAllowReciprocal())
8678 // Now that we have the actual number of divisor uses, make sure it meets
8679 // the minimum threshold specified by the target.
8680 if (Users.size() < MinUses)
8683 EVT VT = N->getValueType(0);
8685 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8686 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8688 // Dividend / Divisor -> Dividend * Reciprocal
8689 for (auto *U : Users) {
8690 SDValue Dividend = U->getOperand(0);
8691 if (Dividend != FPOne) {
8692 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8694 CombineTo(U, NewNode);
8695 } else if (U != Reciprocal.getNode()) {
8696 // In the absence of fast-math-flags, this user node is always the
8697 // same node as Reciprocal, but with FMF they may be different nodes.
8698 CombineTo(U, Reciprocal);
8701 return SDValue(N, 0); // N was replaced.
8704 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8705 SDValue N0 = N->getOperand(0);
8706 SDValue N1 = N->getOperand(1);
8707 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8708 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8709 EVT VT = N->getValueType(0);
8711 const TargetOptions &Options = DAG.getTarget().Options;
8712 SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8716 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8719 // fold (fdiv c1, c2) -> c1/c2
8721 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8723 if (Options.UnsafeFPMath) {
8724 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8726 // Compute the reciprocal 1.0 / c2.
8727 APFloat N1APF = N1CFP->getValueAPF();
8728 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8729 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8730 // Only do the transform if the reciprocal is a legal fp immediate that
8731 // isn't too nasty (eg NaN, denormal, ...).
8732 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8733 (!LegalOperations ||
8734 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8735 // backend)... we should handle this gracefully after Legalize.
8736 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8737 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8738 TLI.isFPImmLegal(Recip, VT)))
8739 return DAG.getNode(ISD::FMUL, DL, VT, N0,
8740 DAG.getConstantFP(Recip, DL, VT), Flags);
8743 // If this FDIV is part of a reciprocal square root, it may be folded
8744 // into a target-specific square root estimate instruction.
8745 if (N1.getOpcode() == ISD::FSQRT) {
8746 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) {
8747 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8749 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8750 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8751 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8753 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8754 AddToWorklist(RV.getNode());
8755 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8757 } else if (N1.getOpcode() == ISD::FP_ROUND &&
8758 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8759 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8761 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8762 AddToWorklist(RV.getNode());
8763 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8765 } else if (N1.getOpcode() == ISD::FMUL) {
8766 // Look through an FMUL. Even though this won't remove the FDIV directly,
8767 // it's still worthwhile to get rid of the FSQRT if possible.
8770 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8771 SqrtOp = N1.getOperand(0);
8772 OtherOp = N1.getOperand(1);
8773 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8774 SqrtOp = N1.getOperand(1);
8775 OtherOp = N1.getOperand(0);
8777 if (SqrtOp.getNode()) {
8778 // We found a FSQRT, so try to make this fold:
8779 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8780 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
8781 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
8782 AddToWorklist(RV.getNode());
8783 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8788 // Fold into a reciprocal estimate and multiply instead of a real divide.
8789 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
8790 AddToWorklist(RV.getNode());
8791 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8795 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8796 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8797 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8798 // Both can be negated for free, check to see if at least one is cheaper
8800 if (LHSNeg == 2 || RHSNeg == 2)
8801 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8802 GetNegatedExpression(N0, DAG, LegalOperations),
8803 GetNegatedExpression(N1, DAG, LegalOperations),
8808 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8809 return CombineRepeatedDivisors;
8814 SDValue DAGCombiner::visitFREM(SDNode *N) {
8815 SDValue N0 = N->getOperand(0);
8816 SDValue N1 = N->getOperand(1);
8817 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8818 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8819 EVT VT = N->getValueType(0);
8821 // fold (frem c1, c2) -> fmod(c1,c2)
8823 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
8824 &cast<BinaryWithFlagsSDNode>(N)->Flags);
8829 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8830 if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8833 // TODO: FSQRT nodes should have flags that propagate to the created nodes.
8834 // For now, create a Flags object for use with all unsafe math transforms.
8836 Flags.setUnsafeAlgebra(true);
8838 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8839 SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags);
8843 EVT VT = RV.getValueType();
8845 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags);
8846 AddToWorklist(RV.getNode());
8848 // Unfortunately, RV is now NaN if the input was exactly 0.
8849 // Select out this case and force the answer to 0.
8850 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8851 EVT CCVT = getSetCCResultType(VT);
8852 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8853 AddToWorklist(ZeroCmp.getNode());
8854 AddToWorklist(RV.getNode());
8856 return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8860 /// copysign(x, fp_extend(y)) -> copysign(x, y)
8861 /// copysign(x, fp_round(y)) -> copysign(x, y)
8862 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
8863 SDValue N1 = N->getOperand(1);
8864 if ((N1.getOpcode() == ISD::FP_EXTEND ||
8865 N1.getOpcode() == ISD::FP_ROUND)) {
8866 // Do not optimize out type conversion of f128 type yet.
8867 // For some targets like x86_64, configuration is changed to keep one f128
8868 // value in one SSE register, but instruction selection cannot handle
8869 // FCOPYSIGN on SSE registers yet.
8870 EVT N1VT = N1->getValueType(0);
8871 EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
8872 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
8877 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8878 SDValue N0 = N->getOperand(0);
8879 SDValue N1 = N->getOperand(1);
8880 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8881 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8882 EVT VT = N->getValueType(0);
8884 if (N0CFP && N1CFP) // Constant fold
8885 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8888 const APFloat& V = N1CFP->getValueAPF();
8889 // copysign(x, c1) -> fabs(x) iff ispos(c1)
8890 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8891 if (!V.isNegative()) {
8892 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8893 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8895 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8896 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8897 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8901 // copysign(fabs(x), y) -> copysign(x, y)
8902 // copysign(fneg(x), y) -> copysign(x, y)
8903 // copysign(copysign(x,z), y) -> copysign(x, y)
8904 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8905 N0.getOpcode() == ISD::FCOPYSIGN)
8906 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8907 N0.getOperand(0), N1);
8909 // copysign(x, abs(y)) -> abs(x)
8910 if (N1.getOpcode() == ISD::FABS)
8911 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8913 // copysign(x, copysign(y,z)) -> copysign(x, z)
8914 if (N1.getOpcode() == ISD::FCOPYSIGN)
8915 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8916 N0, N1.getOperand(1));
8918 // copysign(x, fp_extend(y)) -> copysign(x, y)
8919 // copysign(x, fp_round(y)) -> copysign(x, y)
8920 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
8921 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8922 N0, N1.getOperand(0));
8927 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8928 SDValue N0 = N->getOperand(0);
8929 EVT VT = N->getValueType(0);
8930 EVT OpVT = N0.getValueType();
8932 // fold (sint_to_fp c1) -> c1fp
8933 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8934 // ...but only if the target supports immediate floating-point values
8935 (!LegalOperations ||
8936 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8937 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8939 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8940 // but UINT_TO_FP is legal on this target, try to convert.
8941 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8942 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8943 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8944 if (DAG.SignBitIsZero(N0))
8945 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8948 // The next optimizations are desirable only if SELECT_CC can be lowered.
8949 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8950 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8951 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8953 (!LegalOperations ||
8954 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8957 { N0.getOperand(0), N0.getOperand(1),
8958 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8960 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8963 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8964 // (select_cc x, y, 1.0, 0.0,, cc)
8965 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8966 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8967 (!LegalOperations ||
8968 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8971 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8972 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8973 N0.getOperand(0).getOperand(2) };
8974 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8981 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8982 SDValue N0 = N->getOperand(0);
8983 EVT VT = N->getValueType(0);
8984 EVT OpVT = N0.getValueType();
8986 // fold (uint_to_fp c1) -> c1fp
8987 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8988 // ...but only if the target supports immediate floating-point values
8989 (!LegalOperations ||
8990 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8991 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8993 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8994 // but SINT_TO_FP is legal on this target, try to convert.
8995 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8996 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8997 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8998 if (DAG.SignBitIsZero(N0))
8999 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9002 // The next optimizations are desirable only if SELECT_CC can be lowered.
9003 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9004 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9006 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
9007 (!LegalOperations ||
9008 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9011 { N0.getOperand(0), N0.getOperand(1),
9012 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9014 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9021 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
9022 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
9023 SDValue N0 = N->getOperand(0);
9024 EVT VT = N->getValueType(0);
9026 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
9029 SDValue Src = N0.getOperand(0);
9030 EVT SrcVT = Src.getValueType();
9031 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
9032 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
9034 // We can safely assume the conversion won't overflow the output range,
9035 // because (for example) (uint8_t)18293.f is undefined behavior.
9037 // Since we can assume the conversion won't overflow, our decision as to
9038 // whether the input will fit in the float should depend on the minimum
9039 // of the input range and output range.
9041 // This means this is also safe for a signed input and unsigned output, since
9042 // a negative input would lead to undefined behavior.
9043 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
9044 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
9045 unsigned ActualSize = std::min(InputSize, OutputSize);
9046 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
9048 // We can only fold away the float conversion if the input range can be
9049 // represented exactly in the float range.
9050 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
9051 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
9052 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
9054 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
9056 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
9057 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
9060 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
9065 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
9066 SDValue N0 = N->getOperand(0);
9067 EVT VT = N->getValueType(0);
9069 // fold (fp_to_sint c1fp) -> c1
9070 if (isConstantFPBuildVectorOrConstantFP(N0))
9071 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
9073 return FoldIntToFPToInt(N, DAG);
9076 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
9077 SDValue N0 = N->getOperand(0);
9078 EVT VT = N->getValueType(0);
9080 // fold (fp_to_uint c1fp) -> c1
9081 if (isConstantFPBuildVectorOrConstantFP(N0))
9082 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
9084 return FoldIntToFPToInt(N, DAG);
9087 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
9088 SDValue N0 = N->getOperand(0);
9089 SDValue N1 = N->getOperand(1);
9090 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9091 EVT VT = N->getValueType(0);
9093 // fold (fp_round c1fp) -> c1fp
9095 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
9097 // fold (fp_round (fp_extend x)) -> x
9098 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
9099 return N0.getOperand(0);
9101 // fold (fp_round (fp_round x)) -> (fp_round x)
9102 if (N0.getOpcode() == ISD::FP_ROUND) {
9103 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
9104 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
9105 // If the first fp_round isn't a value preserving truncation, it might
9106 // introduce a tie in the second fp_round, that wouldn't occur in the
9107 // single-step fp_round we want to fold to.
9108 // In other words, double rounding isn't the same as rounding.
9109 // Also, this is a value preserving truncation iff both fp_round's are.
9110 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
9112 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
9113 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
9117 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
9118 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
9119 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
9120 N0.getOperand(0), N1);
9121 AddToWorklist(Tmp.getNode());
9122 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
9123 Tmp, N0.getOperand(1));
9129 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
9130 SDValue N0 = N->getOperand(0);
9131 EVT VT = N->getValueType(0);
9132 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
9133 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9135 // fold (fp_round_inreg c1fp) -> c1fp
9136 if (N0CFP && isTypeLegal(EVT)) {
9138 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
9139 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
9145 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
9146 SDValue N0 = N->getOperand(0);
9147 EVT VT = N->getValueType(0);
9149 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
9150 if (N->hasOneUse() &&
9151 N->use_begin()->getOpcode() == ISD::FP_ROUND)
9154 // fold (fp_extend c1fp) -> c1fp
9155 if (isConstantFPBuildVectorOrConstantFP(N0))
9156 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
9158 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
9159 if (N0.getOpcode() == ISD::FP16_TO_FP &&
9160 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
9161 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
9163 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
9165 if (N0.getOpcode() == ISD::FP_ROUND
9166 && N0.getNode()->getConstantOperandVal(1) == 1) {
9167 SDValue In = N0.getOperand(0);
9168 if (In.getValueType() == VT) return In;
9169 if (VT.bitsLT(In.getValueType()))
9170 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
9171 In, N0.getOperand(1));
9172 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
9175 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
9176 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9177 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
9178 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9179 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
9181 LN0->getBasePtr(), N0.getValueType(),
9182 LN0->getMemOperand());
9183 CombineTo(N, ExtLoad);
9184 CombineTo(N0.getNode(),
9185 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
9186 N0.getValueType(), ExtLoad,
9187 DAG.getIntPtrConstant(1, SDLoc(N0))),
9188 ExtLoad.getValue(1));
9189 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9195 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
9196 SDValue N0 = N->getOperand(0);
9197 EVT VT = N->getValueType(0);
9199 // fold (fceil c1) -> fceil(c1)
9200 if (isConstantFPBuildVectorOrConstantFP(N0))
9201 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
9206 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
9207 SDValue N0 = N->getOperand(0);
9208 EVT VT = N->getValueType(0);
9210 // fold (ftrunc c1) -> ftrunc(c1)
9211 if (isConstantFPBuildVectorOrConstantFP(N0))
9212 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
9217 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
9218 SDValue N0 = N->getOperand(0);
9219 EVT VT = N->getValueType(0);
9221 // fold (ffloor c1) -> ffloor(c1)
9222 if (isConstantFPBuildVectorOrConstantFP(N0))
9223 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
9228 // FIXME: FNEG and FABS have a lot in common; refactor.
9229 SDValue DAGCombiner::visitFNEG(SDNode *N) {
9230 SDValue N0 = N->getOperand(0);
9231 EVT VT = N->getValueType(0);
9233 // Constant fold FNEG.
9234 if (isConstantFPBuildVectorOrConstantFP(N0))
9235 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
9237 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
9238 &DAG.getTarget().Options))
9239 return GetNegatedExpression(N0, DAG, LegalOperations);
9241 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
9242 // constant pool values.
9243 if (!TLI.isFNegFree(VT) &&
9244 N0.getOpcode() == ISD::BITCAST &&
9245 N0.getNode()->hasOneUse()) {
9246 SDValue Int = N0.getOperand(0);
9247 EVT IntVT = Int.getValueType();
9248 if (IntVT.isInteger() && !IntVT.isVector()) {
9250 if (N0.getValueType().isVector()) {
9251 // For a vector, get a mask such as 0x80... per scalar element
9253 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9254 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9256 // For a scalar, just generate 0x80...
9257 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
9260 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9261 DAG.getConstant(SignMask, DL0, IntVT));
9262 AddToWorklist(Int.getNode());
9263 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
9267 // (fneg (fmul c, x)) -> (fmul -c, x)
9268 if (N0.getOpcode() == ISD::FMUL &&
9269 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9270 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9272 APFloat CVal = CFP1->getValueAPF();
9274 if (Level >= AfterLegalizeDAG &&
9275 (TLI.isFPImmLegal(CVal, VT) ||
9276 TLI.isOperationLegal(ISD::ConstantFP, VT)))
9277 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9278 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9280 &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9287 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
9288 SDValue N0 = N->getOperand(0);
9289 SDValue N1 = N->getOperand(1);
9290 EVT VT = N->getValueType(0);
9291 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9292 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9294 if (N0CFP && N1CFP) {
9295 const APFloat &C0 = N0CFP->getValueAPF();
9296 const APFloat &C1 = N1CFP->getValueAPF();
9297 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9300 // Canonicalize to constant on RHS.
9301 if (isConstantFPBuildVectorOrConstantFP(N0) &&
9302 !isConstantFPBuildVectorOrConstantFP(N1))
9303 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9308 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9309 SDValue N0 = N->getOperand(0);
9310 SDValue N1 = N->getOperand(1);
9311 EVT VT = N->getValueType(0);
9312 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9313 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9315 if (N0CFP && N1CFP) {
9316 const APFloat &C0 = N0CFP->getValueAPF();
9317 const APFloat &C1 = N1CFP->getValueAPF();
9318 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9321 // Canonicalize to constant on RHS.
9322 if (isConstantFPBuildVectorOrConstantFP(N0) &&
9323 !isConstantFPBuildVectorOrConstantFP(N1))
9324 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9329 SDValue DAGCombiner::visitFABS(SDNode *N) {
9330 SDValue N0 = N->getOperand(0);
9331 EVT VT = N->getValueType(0);
9333 // fold (fabs c1) -> fabs(c1)
9334 if (isConstantFPBuildVectorOrConstantFP(N0))
9335 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9337 // fold (fabs (fabs x)) -> (fabs x)
9338 if (N0.getOpcode() == ISD::FABS)
9339 return N->getOperand(0);
9341 // fold (fabs (fneg x)) -> (fabs x)
9342 // fold (fabs (fcopysign x, y)) -> (fabs x)
9343 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9344 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9346 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9347 // constant pool values.
9348 if (!TLI.isFAbsFree(VT) &&
9349 N0.getOpcode() == ISD::BITCAST &&
9350 N0.getNode()->hasOneUse()) {
9351 SDValue Int = N0.getOperand(0);
9352 EVT IntVT = Int.getValueType();
9353 if (IntVT.isInteger() && !IntVT.isVector()) {
9355 if (N0.getValueType().isVector()) {
9356 // For a vector, get a mask such as 0x7f... per scalar element
9358 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9359 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9361 // For a scalar, just generate 0x7f...
9362 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9365 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9366 DAG.getConstant(SignMask, DL, IntVT));
9367 AddToWorklist(Int.getNode());
9368 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
9375 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9376 SDValue Chain = N->getOperand(0);
9377 SDValue N1 = N->getOperand(1);
9378 SDValue N2 = N->getOperand(2);
9380 // If N is a constant we could fold this into a fallthrough or unconditional
9381 // branch. However that doesn't happen very often in normal code, because
9382 // Instcombine/SimplifyCFG should have handled the available opportunities.
9383 // If we did this folding here, it would be necessary to update the
9384 // MachineBasicBlock CFG, which is awkward.
9386 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9388 if (N1.getOpcode() == ISD::SETCC &&
9389 TLI.isOperationLegalOrCustom(ISD::BR_CC,
9390 N1.getOperand(0).getValueType())) {
9391 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9392 Chain, N1.getOperand(2),
9393 N1.getOperand(0), N1.getOperand(1), N2);
9396 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9397 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9398 (N1.getOperand(0).hasOneUse() &&
9399 N1.getOperand(0).getOpcode() == ISD::SRL))) {
9400 SDNode *Trunc = nullptr;
9401 if (N1.getOpcode() == ISD::TRUNCATE) {
9402 // Look pass the truncate.
9403 Trunc = N1.getNode();
9404 N1 = N1.getOperand(0);
9407 // Match this pattern so that we can generate simpler code:
9410 // %b = and i32 %a, 2
9411 // %c = srl i32 %b, 1
9412 // brcond i32 %c ...
9417 // %b = and i32 %a, 2
9418 // %c = setcc eq %b, 0
9421 // This applies only when the AND constant value has one bit set and the
9422 // SRL constant is equal to the log2 of the AND constant. The back-end is
9423 // smart enough to convert the result into a TEST/JMP sequence.
9424 SDValue Op0 = N1.getOperand(0);
9425 SDValue Op1 = N1.getOperand(1);
9427 if (Op0.getOpcode() == ISD::AND &&
9428 Op1.getOpcode() == ISD::Constant) {
9429 SDValue AndOp1 = Op0.getOperand(1);
9431 if (AndOp1.getOpcode() == ISD::Constant) {
9432 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9434 if (AndConst.isPowerOf2() &&
9435 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9439 getSetCCResultType(Op0.getValueType()),
9440 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9443 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9444 MVT::Other, Chain, SetCC, N2);
9445 // Don't add the new BRCond into the worklist or else SimplifySelectCC
9446 // will convert it back to (X & C1) >> C2.
9447 CombineTo(N, NewBRCond, false);
9448 // Truncate is dead.
9450 deleteAndRecombine(Trunc);
9451 // Replace the uses of SRL with SETCC
9452 WorklistRemover DeadNodes(*this);
9453 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9454 deleteAndRecombine(N1.getNode());
9455 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9461 // Restore N1 if the above transformation doesn't match.
9462 N1 = N->getOperand(1);
9465 // Transform br(xor(x, y)) -> br(x != y)
9466 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9467 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9468 SDNode *TheXor = N1.getNode();
9469 SDValue Op0 = TheXor->getOperand(0);
9470 SDValue Op1 = TheXor->getOperand(1);
9471 if (Op0.getOpcode() == Op1.getOpcode()) {
9472 // Avoid missing important xor optimizations.
9473 if (SDValue Tmp = visitXOR(TheXor)) {
9474 if (Tmp.getNode() != TheXor) {
9475 DEBUG(dbgs() << "\nReplacing.8 ";
9477 dbgs() << "\nWith: ";
9478 Tmp.getNode()->dump(&DAG);
9480 WorklistRemover DeadNodes(*this);
9481 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9482 deleteAndRecombine(TheXor);
9483 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9484 MVT::Other, Chain, Tmp, N2);
9487 // visitXOR has changed XOR's operands or replaced the XOR completely,
9489 return SDValue(N, 0);
9493 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9495 if (isOneConstant(Op0) && Op0.hasOneUse() &&
9496 Op0.getOpcode() == ISD::XOR) {
9497 TheXor = Op0.getNode();
9501 EVT SetCCVT = N1.getValueType();
9503 SetCCVT = getSetCCResultType(SetCCVT);
9504 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9507 Equal ? ISD::SETEQ : ISD::SETNE);
9508 // Replace the uses of XOR with SETCC
9509 WorklistRemover DeadNodes(*this);
9510 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9511 deleteAndRecombine(N1.getNode());
9512 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9513 MVT::Other, Chain, SetCC, N2);
9520 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9522 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9523 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9524 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9526 // If N is a constant we could fold this into a fallthrough or unconditional
9527 // branch. However that doesn't happen very often in normal code, because
9528 // Instcombine/SimplifyCFG should have handled the available opportunities.
9529 // If we did this folding here, it would be necessary to update the
9530 // MachineBasicBlock CFG, which is awkward.
9532 // Use SimplifySetCC to simplify SETCC's.
9533 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9534 CondLHS, CondRHS, CC->get(), SDLoc(N),
9536 if (Simp.getNode()) AddToWorklist(Simp.getNode());
9538 // fold to a simpler setcc
9539 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9540 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9541 N->getOperand(0), Simp.getOperand(2),
9542 Simp.getOperand(0), Simp.getOperand(1),
9548 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9549 /// and that N may be folded in the load / store addressing mode.
9550 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9552 const TargetLowering &TLI) {
9556 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
9557 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9559 VT = LD->getMemoryVT();
9560 AS = LD->getAddressSpace();
9561 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
9562 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9564 VT = ST->getMemoryVT();
9565 AS = ST->getAddressSpace();
9569 TargetLowering::AddrMode AM;
9570 if (N->getOpcode() == ISD::ADD) {
9571 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9574 AM.BaseOffs = Offset->getSExtValue();
9578 } else if (N->getOpcode() == ISD::SUB) {
9579 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9582 AM.BaseOffs = -Offset->getSExtValue();
9589 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9590 VT.getTypeForEVT(*DAG.getContext()), AS);
9593 /// Try turning a load/store into a pre-indexed load/store when the base
9594 /// pointer is an add or subtract and it has other uses besides the load/store.
9595 /// After the transformation, the new indexed load/store has effectively folded
9596 /// the add/subtract in and all of its other uses are redirected to the
9598 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9599 if (Level < AfterLegalizeDAG)
9605 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9606 if (LD->isIndexed())
9608 VT = LD->getMemoryVT();
9609 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9610 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9612 Ptr = LD->getBasePtr();
9613 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9614 if (ST->isIndexed())
9616 VT = ST->getMemoryVT();
9617 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9618 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9620 Ptr = ST->getBasePtr();
9626 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9627 // out. There is no reason to make this a preinc/predec.
9628 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9629 Ptr.getNode()->hasOneUse())
9632 // Ask the target to do addressing mode selection.
9635 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9636 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9639 // Backends without true r+i pre-indexed forms may need to pass a
9640 // constant base with a variable offset so that constant coercion
9641 // will work with the patterns in canonical form.
9642 bool Swapped = false;
9643 if (isa<ConstantSDNode>(BasePtr)) {
9644 std::swap(BasePtr, Offset);
9648 // Don't create a indexed load / store with zero offset.
9649 if (isNullConstant(Offset))
9652 // Try turning it into a pre-indexed load / store except when:
9653 // 1) The new base ptr is a frame index.
9654 // 2) If N is a store and the new base ptr is either the same as or is a
9655 // predecessor of the value being stored.
9656 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9657 // that would create a cycle.
9658 // 4) All uses are load / store ops that use it as old base ptr.
9660 // Check #1. Preinc'ing a frame index would require copying the stack pointer
9661 // (plus the implicit offset) to a register to preinc anyway.
9662 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9667 SDValue Val = cast<StoreSDNode>(N)->getValue();
9668 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9672 // If the offset is a constant, there may be other adds of constants that
9673 // can be folded with this one. We should do this to avoid having to keep
9674 // a copy of the original base pointer.
9675 SmallVector<SDNode *, 16> OtherUses;
9676 if (isa<ConstantSDNode>(Offset))
9677 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9678 UE = BasePtr.getNode()->use_end();
9680 SDUse &Use = UI.getUse();
9681 // Skip the use that is Ptr and uses of other results from BasePtr's
9682 // node (important for nodes that return multiple results).
9683 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9686 if (Use.getUser()->isPredecessorOf(N))
9689 if (Use.getUser()->getOpcode() != ISD::ADD &&
9690 Use.getUser()->getOpcode() != ISD::SUB) {
9695 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9696 if (!isa<ConstantSDNode>(Op1)) {
9701 // FIXME: In some cases, we can be smarter about this.
9702 if (Op1.getValueType() != Offset.getValueType()) {
9707 OtherUses.push_back(Use.getUser());
9711 std::swap(BasePtr, Offset);
9713 // Now check for #3 and #4.
9714 bool RealUse = false;
9716 // Caches for hasPredecessorHelper
9717 SmallPtrSet<const SDNode *, 32> Visited;
9718 SmallVector<const SDNode *, 16> Worklist;
9720 for (SDNode *Use : Ptr.getNode()->uses()) {
9723 if (N->hasPredecessorHelper(Use, Visited, Worklist))
9726 // If Ptr may be folded in addressing mode of other use, then it's
9727 // not profitable to do this transformation.
9728 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9737 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9738 BasePtr, Offset, AM);
9740 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9741 BasePtr, Offset, AM);
9744 DEBUG(dbgs() << "\nReplacing.4 ";
9746 dbgs() << "\nWith: ";
9747 Result.getNode()->dump(&DAG);
9749 WorklistRemover DeadNodes(*this);
9751 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9752 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9754 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9757 // Finally, since the node is now dead, remove it from the graph.
9758 deleteAndRecombine(N);
9761 std::swap(BasePtr, Offset);
9763 // Replace other uses of BasePtr that can be updated to use Ptr
9764 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9765 unsigned OffsetIdx = 1;
9766 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9768 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9769 BasePtr.getNode() && "Expected BasePtr operand");
9771 // We need to replace ptr0 in the following expression:
9772 // x0 * offset0 + y0 * ptr0 = t0
9774 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9776 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9777 // indexed load/store and the expresion that needs to be re-written.
9779 // Therefore, we have:
9780 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9782 ConstantSDNode *CN =
9783 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9785 APInt Offset0 = CN->getAPIntValue();
9786 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9788 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9789 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9790 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9791 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9793 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9795 APInt CNV = Offset0;
9796 if (X0 < 0) CNV = -CNV;
9797 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9798 else CNV = CNV - Offset1;
9800 SDLoc DL(OtherUses[i]);
9802 // We can now generate the new expression.
9803 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9804 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9806 SDValue NewUse = DAG.getNode(Opcode,
9808 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9809 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9810 deleteAndRecombine(OtherUses[i]);
9813 // Replace the uses of Ptr with uses of the updated base value.
9814 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9815 deleteAndRecombine(Ptr.getNode());
9820 /// Try to combine a load/store with a add/sub of the base pointer node into a
9821 /// post-indexed load/store. The transformation folded the add/subtract into the
9822 /// new indexed load/store effectively and all of its uses are redirected to the
9824 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9825 if (Level < AfterLegalizeDAG)
9831 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9832 if (LD->isIndexed())
9834 VT = LD->getMemoryVT();
9835 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9836 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9838 Ptr = LD->getBasePtr();
9839 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9840 if (ST->isIndexed())
9842 VT = ST->getMemoryVT();
9843 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9844 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9846 Ptr = ST->getBasePtr();
9852 if (Ptr.getNode()->hasOneUse())
9855 for (SDNode *Op : Ptr.getNode()->uses()) {
9857 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9862 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9863 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9864 // Don't create a indexed load / store with zero offset.
9865 if (isNullConstant(Offset))
9868 // Try turning it into a post-indexed load / store except when
9869 // 1) All uses are load / store ops that use it as base ptr (and
9870 // it may be folded as addressing mmode).
9871 // 2) Op must be independent of N, i.e. Op is neither a predecessor
9872 // nor a successor of N. Otherwise, if Op is folded that would
9875 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9879 bool TryNext = false;
9880 for (SDNode *Use : BasePtr.getNode()->uses()) {
9881 if (Use == Ptr.getNode())
9884 // If all the uses are load / store addresses, then don't do the
9886 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9887 bool RealUse = false;
9888 for (SDNode *UseUse : Use->uses()) {
9889 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9904 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9905 SDValue Result = isLoad
9906 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9907 BasePtr, Offset, AM)
9908 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9909 BasePtr, Offset, AM);
9912 DEBUG(dbgs() << "\nReplacing.5 ";
9914 dbgs() << "\nWith: ";
9915 Result.getNode()->dump(&DAG);
9917 WorklistRemover DeadNodes(*this);
9919 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9920 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9922 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9925 // Finally, since the node is now dead, remove it from the graph.
9926 deleteAndRecombine(N);
9928 // Replace the uses of Use with uses of the updated base value.
9929 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9930 Result.getValue(isLoad ? 1 : 0));
9931 deleteAndRecombine(Op);
9940 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9941 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9942 ISD::MemIndexedMode AM = LD->getAddressingMode();
9943 assert(AM != ISD::UNINDEXED);
9944 SDValue BP = LD->getOperand(1);
9945 SDValue Inc = LD->getOperand(2);
9947 // Some backends use TargetConstants for load offsets, but don't expect
9948 // TargetConstants in general ADD nodes. We can convert these constants into
9949 // regular Constants (if the constant is not opaque).
9950 assert((Inc.getOpcode() != ISD::TargetConstant ||
9951 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9952 "Cannot split out indexing using opaque target constants");
9953 if (Inc.getOpcode() == ISD::TargetConstant) {
9954 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9955 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9956 ConstInc->getValueType(0));
9960 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9961 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9964 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9965 LoadSDNode *LD = cast<LoadSDNode>(N);
9966 SDValue Chain = LD->getChain();
9967 SDValue Ptr = LD->getBasePtr();
9969 // If load is not volatile and there are no uses of the loaded value (and
9970 // the updated indexed value in case of indexed loads), change uses of the
9971 // chain value into uses of the chain input (i.e. delete the dead load).
9972 if (!LD->isVolatile()) {
9973 if (N->getValueType(1) == MVT::Other) {
9975 if (!N->hasAnyUseOfValue(0)) {
9976 // It's not safe to use the two value CombineTo variant here. e.g.
9977 // v1, chain2 = load chain1, loc
9978 // v2, chain3 = load chain2, loc
9980 // Now we replace use of chain2 with chain1. This makes the second load
9981 // isomorphic to the one we are deleting, and thus makes this load live.
9982 DEBUG(dbgs() << "\nReplacing.6 ";
9984 dbgs() << "\nWith chain: ";
9985 Chain.getNode()->dump(&DAG);
9987 WorklistRemover DeadNodes(*this);
9988 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9991 deleteAndRecombine(N);
9993 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9997 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9999 // If this load has an opaque TargetConstant offset, then we cannot split
10000 // the indexing into an add/sub directly (that TargetConstant may not be
10001 // valid for a different type of node, and we cannot convert an opaque
10002 // target constant into a regular constant).
10003 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
10004 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
10006 if (!N->hasAnyUseOfValue(0) &&
10007 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
10008 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
10010 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
10011 Index = SplitIndexingFromLoad(LD);
10012 // Try to fold the base pointer arithmetic into subsequent loads and
10014 AddUsersToWorklist(N);
10016 Index = DAG.getUNDEF(N->getValueType(1));
10017 DEBUG(dbgs() << "\nReplacing.7 ";
10019 dbgs() << "\nWith: ";
10020 Undef.getNode()->dump(&DAG);
10021 dbgs() << " and 2 other values\n");
10022 WorklistRemover DeadNodes(*this);
10023 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
10024 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
10025 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
10026 deleteAndRecombine(N);
10027 return SDValue(N, 0); // Return N so it doesn't get rechecked!
10032 // If this load is directly stored, replace the load value with the stored
10034 // TODO: Handle store large -> read small portion.
10035 // TODO: Handle TRUNCSTORE/LOADEXT
10036 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
10037 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
10038 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
10039 if (PrevST->getBasePtr() == Ptr &&
10040 PrevST->getValue().getValueType() == N->getValueType(0))
10041 return CombineTo(N, Chain.getOperand(1), Chain);
10045 // Try to infer better alignment information than the load already has.
10046 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
10047 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10048 if (Align > LD->getMemOperand()->getBaseAlignment()) {
10050 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
10051 LD->getValueType(0),
10052 Chain, Ptr, LD->getPointerInfo(),
10054 LD->isVolatile(), LD->isNonTemporal(),
10055 LD->isInvariant(), Align, LD->getAAInfo());
10056 if (NewLoad.getNode() != N)
10057 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
10062 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10063 : DAG.getSubtarget().useAA();
10065 if (CombinerAAOnlyFunc.getNumOccurrences() &&
10066 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10069 if (UseAA && LD->isUnindexed()) {
10070 // Walk up chain skipping non-aliasing memory nodes.
10071 SDValue BetterChain = FindBetterChain(N, Chain);
10073 // If there is a better chain.
10074 if (Chain != BetterChain) {
10077 // Replace the chain to void dependency.
10078 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
10079 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
10080 BetterChain, Ptr, LD->getMemOperand());
10082 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
10083 LD->getValueType(0),
10084 BetterChain, Ptr, LD->getMemoryVT(),
10085 LD->getMemOperand());
10088 // Create token factor to keep old chain connected.
10089 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10090 MVT::Other, Chain, ReplLoad.getValue(1));
10092 // Make sure the new and old chains are cleaned up.
10093 AddToWorklist(Token.getNode());
10095 // Replace uses with load result and token factor. Don't add users
10097 return CombineTo(N, ReplLoad.getValue(0), Token, false);
10101 // Try transforming N to an indexed load.
10102 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10103 return SDValue(N, 0);
10105 // Try to slice up N to more direct loads if the slices are mapped to
10106 // different register banks or pairing can take place.
10107 if (SliceUpLoad(N))
10108 return SDValue(N, 0);
10114 /// \brief Helper structure used to slice a load in smaller loads.
10115 /// Basically a slice is obtained from the following sequence:
10116 /// Origin = load Ty1, Base
10117 /// Shift = srl Ty1 Origin, CstTy Amount
10118 /// Inst = trunc Shift to Ty2
10120 /// Then, it will be rewriten into:
10121 /// Slice = load SliceTy, Base + SliceOffset
10122 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
10124 /// SliceTy is deduced from the number of bits that are actually used to
10126 struct LoadedSlice {
10127 /// \brief Helper structure used to compute the cost of a slice.
10129 /// Are we optimizing for code size.
10133 unsigned Truncates;
10134 unsigned CrossRegisterBanksCopies;
10138 Cost(bool ForCodeSize = false)
10139 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
10140 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
10142 /// \brief Get the cost of one isolated slice.
10143 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
10144 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
10145 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
10146 EVT TruncType = LS.Inst->getValueType(0);
10147 EVT LoadedType = LS.getLoadedType();
10148 if (TruncType != LoadedType &&
10149 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
10153 /// \brief Account for slicing gain in the current cost.
10154 /// Slicing provide a few gains like removing a shift or a
10155 /// truncate. This method allows to grow the cost of the original
10156 /// load with the gain from this slice.
10157 void addSliceGain(const LoadedSlice &LS) {
10158 // Each slice saves a truncate.
10159 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
10160 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
10161 LS.Inst->getValueType(0)))
10163 // If there is a shift amount, this slice gets rid of it.
10166 // If this slice can merge a cross register bank copy, account for it.
10167 if (LS.canMergeExpensiveCrossRegisterBankCopy())
10168 ++CrossRegisterBanksCopies;
10171 Cost &operator+=(const Cost &RHS) {
10172 Loads += RHS.Loads;
10173 Truncates += RHS.Truncates;
10174 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
10175 ZExts += RHS.ZExts;
10176 Shift += RHS.Shift;
10180 bool operator==(const Cost &RHS) const {
10181 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
10182 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
10183 ZExts == RHS.ZExts && Shift == RHS.Shift;
10186 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
10188 bool operator<(const Cost &RHS) const {
10189 // Assume cross register banks copies are as expensive as loads.
10190 // FIXME: Do we want some more target hooks?
10191 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
10192 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
10193 // Unless we are optimizing for code size, consider the
10194 // expensive operation first.
10195 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
10196 return ExpensiveOpsLHS < ExpensiveOpsRHS;
10197 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
10198 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
10201 bool operator>(const Cost &RHS) const { return RHS < *this; }
10203 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
10205 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
10207 // The last instruction that represent the slice. This should be a
10208 // truncate instruction.
10210 // The original load instruction.
10211 LoadSDNode *Origin;
10212 // The right shift amount in bits from the original load.
10214 // The DAG from which Origin came from.
10215 // This is used to get some contextual information about legal types, etc.
10218 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
10219 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
10220 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
10222 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
10223 /// \return Result is \p BitWidth and has used bits set to 1 and
10224 /// not used bits set to 0.
10225 APInt getUsedBits() const {
10226 // Reproduce the trunc(lshr) sequence:
10227 // - Start from the truncated value.
10228 // - Zero extend to the desired bit width.
10230 assert(Origin && "No original load to compare against.");
10231 unsigned BitWidth = Origin->getValueSizeInBits(0);
10232 assert(Inst && "This slice is not bound to an instruction");
10233 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
10234 "Extracted slice is bigger than the whole type!");
10235 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
10236 UsedBits.setAllBits();
10237 UsedBits = UsedBits.zext(BitWidth);
10238 UsedBits <<= Shift;
10242 /// \brief Get the size of the slice to be loaded in bytes.
10243 unsigned getLoadedSize() const {
10244 unsigned SliceSize = getUsedBits().countPopulation();
10245 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
10246 return SliceSize / 8;
10249 /// \brief Get the type that will be loaded for this slice.
10250 /// Note: This may not be the final type for the slice.
10251 EVT getLoadedType() const {
10252 assert(DAG && "Missing context");
10253 LLVMContext &Ctxt = *DAG->getContext();
10254 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
10257 /// \brief Get the alignment of the load used for this slice.
10258 unsigned getAlignment() const {
10259 unsigned Alignment = Origin->getAlignment();
10260 unsigned Offset = getOffsetFromBase();
10262 Alignment = MinAlign(Alignment, Alignment + Offset);
10266 /// \brief Check if this slice can be rewritten with legal operations.
10267 bool isLegal() const {
10268 // An invalid slice is not legal.
10269 if (!Origin || !Inst || !DAG)
10272 // Offsets are for indexed load only, we do not handle that.
10273 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
10276 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10278 // Check that the type is legal.
10279 EVT SliceType = getLoadedType();
10280 if (!TLI.isTypeLegal(SliceType))
10283 // Check that the load is legal for this type.
10284 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10287 // Check that the offset can be computed.
10288 // 1. Check its type.
10289 EVT PtrType = Origin->getBasePtr().getValueType();
10290 if (PtrType == MVT::Untyped || PtrType.isExtended())
10293 // 2. Check that it fits in the immediate.
10294 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10297 // 3. Check that the computation is legal.
10298 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10301 // Check that the zext is legal if it needs one.
10302 EVT TruncateType = Inst->getValueType(0);
10303 if (TruncateType != SliceType &&
10304 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10310 /// \brief Get the offset in bytes of this slice in the original chunk of
10312 /// \pre DAG != nullptr.
10313 uint64_t getOffsetFromBase() const {
10314 assert(DAG && "Missing context.");
10315 bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10316 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10317 uint64_t Offset = Shift / 8;
10318 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10319 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10320 "The size of the original loaded type is not a multiple of a"
10322 // If Offset is bigger than TySizeInBytes, it means we are loading all
10323 // zeros. This should have been optimized before in the process.
10324 assert(TySizeInBytes > Offset &&
10325 "Invalid shift amount for given loaded size");
10327 Offset = TySizeInBytes - Offset - getLoadedSize();
10331 /// \brief Generate the sequence of instructions to load the slice
10332 /// represented by this object and redirect the uses of this slice to
10333 /// this new sequence of instructions.
10334 /// \pre this->Inst && this->Origin are valid Instructions and this
10335 /// object passed the legal check: LoadedSlice::isLegal returned true.
10336 /// \return The last instruction of the sequence used to load the slice.
10337 SDValue loadSlice() const {
10338 assert(Inst && Origin && "Unable to replace a non-existing slice.");
10339 const SDValue &OldBaseAddr = Origin->getBasePtr();
10340 SDValue BaseAddr = OldBaseAddr;
10341 // Get the offset in that chunk of bytes w.r.t. the endianess.
10342 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10343 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10345 // BaseAddr = BaseAddr + Offset.
10346 EVT ArithType = BaseAddr.getValueType();
10348 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10349 DAG->getConstant(Offset, DL, ArithType));
10352 // Create the type of the loaded slice according to its size.
10353 EVT SliceType = getLoadedType();
10355 // Create the load for the slice.
10356 SDValue LastInst = DAG->getLoad(
10357 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10358 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
10359 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
10360 // If the final type is not the same as the loaded type, this means that
10361 // we have to pad with zero. Create a zero extend for that.
10362 EVT FinalType = Inst->getValueType(0);
10363 if (SliceType != FinalType)
10365 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10369 /// \brief Check if this slice can be merged with an expensive cross register
10370 /// bank copy. E.g.,
10372 /// f = bitcast i32 i to float
10373 bool canMergeExpensiveCrossRegisterBankCopy() const {
10374 if (!Inst || !Inst->hasOneUse())
10376 SDNode *Use = *Inst->use_begin();
10377 if (Use->getOpcode() != ISD::BITCAST)
10379 assert(DAG && "Missing context");
10380 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10381 EVT ResVT = Use->getValueType(0);
10382 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10383 const TargetRegisterClass *ArgRC =
10384 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10385 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10388 // At this point, we know that we perform a cross-register-bank copy.
10389 // Check if it is expensive.
10390 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10391 // Assume bitcasts are cheap, unless both register classes do not
10392 // explicitly share a common sub class.
10393 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10396 // Check if it will be merged with the load.
10397 // 1. Check the alignment constraint.
10398 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10399 ResVT.getTypeForEVT(*DAG->getContext()));
10401 if (RequiredAlignment > getAlignment())
10404 // 2. Check that the load is a legal operation for that type.
10405 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10408 // 3. Check that we do not have a zext in the way.
10409 if (Inst->getValueType(0) != getLoadedType())
10417 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10418 /// \p UsedBits looks like 0..0 1..1 0..0.
10419 static bool areUsedBitsDense(const APInt &UsedBits) {
10420 // If all the bits are one, this is dense!
10421 if (UsedBits.isAllOnesValue())
10424 // Get rid of the unused bits on the right.
10425 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10426 // Get rid of the unused bits on the left.
10427 if (NarrowedUsedBits.countLeadingZeros())
10428 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10429 // Check that the chunk of bits is completely used.
10430 return NarrowedUsedBits.isAllOnesValue();
10433 /// \brief Check whether or not \p First and \p Second are next to each other
10434 /// in memory. This means that there is no hole between the bits loaded
10435 /// by \p First and the bits loaded by \p Second.
10436 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10437 const LoadedSlice &Second) {
10438 assert(First.Origin == Second.Origin && First.Origin &&
10439 "Unable to match different memory origins.");
10440 APInt UsedBits = First.getUsedBits();
10441 assert((UsedBits & Second.getUsedBits()) == 0 &&
10442 "Slices are not supposed to overlap.");
10443 UsedBits |= Second.getUsedBits();
10444 return areUsedBitsDense(UsedBits);
10447 /// \brief Adjust the \p GlobalLSCost according to the target
10448 /// paring capabilities and the layout of the slices.
10449 /// \pre \p GlobalLSCost should account for at least as many loads as
10450 /// there is in the slices in \p LoadedSlices.
10451 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10452 LoadedSlice::Cost &GlobalLSCost) {
10453 unsigned NumberOfSlices = LoadedSlices.size();
10454 // If there is less than 2 elements, no pairing is possible.
10455 if (NumberOfSlices < 2)
10458 // Sort the slices so that elements that are likely to be next to each
10459 // other in memory are next to each other in the list.
10460 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10461 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10462 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10463 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10465 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10466 // First (resp. Second) is the first (resp. Second) potentially candidate
10467 // to be placed in a paired load.
10468 const LoadedSlice *First = nullptr;
10469 const LoadedSlice *Second = nullptr;
10470 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10471 // Set the beginning of the pair.
10474 Second = &LoadedSlices[CurrSlice];
10476 // If First is NULL, it means we start a new pair.
10477 // Get to the next slice.
10481 EVT LoadedType = First->getLoadedType();
10483 // If the types of the slices are different, we cannot pair them.
10484 if (LoadedType != Second->getLoadedType())
10487 // Check if the target supplies paired loads for this type.
10488 unsigned RequiredAlignment = 0;
10489 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10490 // move to the next pair, this type is hopeless.
10494 // Check if we meet the alignment requirement.
10495 if (RequiredAlignment > First->getAlignment())
10498 // Check that both loads are next to each other in memory.
10499 if (!areSlicesNextToEachOther(*First, *Second))
10502 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10503 --GlobalLSCost.Loads;
10504 // Move to the next pair.
10509 /// \brief Check the profitability of all involved LoadedSlice.
10510 /// Currently, it is considered profitable if there is exactly two
10511 /// involved slices (1) which are (2) next to each other in memory, and
10512 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10514 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10515 /// the elements themselves.
10517 /// FIXME: When the cost model will be mature enough, we can relax
10518 /// constraints (1) and (2).
10519 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10520 const APInt &UsedBits, bool ForCodeSize) {
10521 unsigned NumberOfSlices = LoadedSlices.size();
10522 if (StressLoadSlicing)
10523 return NumberOfSlices > 1;
10526 if (NumberOfSlices != 2)
10530 if (!areUsedBitsDense(UsedBits))
10534 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10535 // The original code has one big load.
10536 OrigCost.Loads = 1;
10537 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10538 const LoadedSlice &LS = LoadedSlices[CurrSlice];
10539 // Accumulate the cost of all the slices.
10540 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10541 GlobalSlicingCost += SliceCost;
10543 // Account as cost in the original configuration the gain obtained
10544 // with the current slices.
10545 OrigCost.addSliceGain(LS);
10548 // If the target supports paired load, adjust the cost accordingly.
10549 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10550 return OrigCost > GlobalSlicingCost;
10553 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10554 /// operations, split it in the various pieces being extracted.
10556 /// This sort of thing is introduced by SROA.
10557 /// This slicing takes care not to insert overlapping loads.
10558 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10559 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10560 if (Level < AfterLegalizeDAG)
10563 LoadSDNode *LD = cast<LoadSDNode>(N);
10564 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10565 !LD->getValueType(0).isInteger())
10568 // Keep track of already used bits to detect overlapping values.
10569 // In that case, we will just abort the transformation.
10570 APInt UsedBits(LD->getValueSizeInBits(0), 0);
10572 SmallVector<LoadedSlice, 4> LoadedSlices;
10574 // Check if this load is used as several smaller chunks of bits.
10575 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10576 // of computation for each trunc.
10577 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10578 UI != UIEnd; ++UI) {
10579 // Skip the uses of the chain.
10580 if (UI.getUse().getResNo() != 0)
10583 SDNode *User = *UI;
10584 unsigned Shift = 0;
10586 // Check if this is a trunc(lshr).
10587 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10588 isa<ConstantSDNode>(User->getOperand(1))) {
10589 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10590 User = *User->use_begin();
10593 // At this point, User is a Truncate, iff we encountered, trunc or
10595 if (User->getOpcode() != ISD::TRUNCATE)
10598 // The width of the type must be a power of 2 and greater than 8-bits.
10599 // Otherwise the load cannot be represented in LLVM IR.
10600 // Moreover, if we shifted with a non-8-bits multiple, the slice
10601 // will be across several bytes. We do not support that.
10602 unsigned Width = User->getValueSizeInBits(0);
10603 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10606 // Build the slice for this chain of computations.
10607 LoadedSlice LS(User, LD, Shift, &DAG);
10608 APInt CurrentUsedBits = LS.getUsedBits();
10610 // Check if this slice overlaps with another.
10611 if ((CurrentUsedBits & UsedBits) != 0)
10613 // Update the bits used globally.
10614 UsedBits |= CurrentUsedBits;
10616 // Check if the new slice would be legal.
10620 // Record the slice.
10621 LoadedSlices.push_back(LS);
10624 // Abort slicing if it does not seem to be profitable.
10625 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10630 // Rewrite each chain to use an independent load.
10631 // By construction, each chain can be represented by a unique load.
10633 // Prepare the argument for the new token factor for all the slices.
10634 SmallVector<SDValue, 8> ArgChains;
10635 for (SmallVectorImpl<LoadedSlice>::const_iterator
10636 LSIt = LoadedSlices.begin(),
10637 LSItEnd = LoadedSlices.end();
10638 LSIt != LSItEnd; ++LSIt) {
10639 SDValue SliceInst = LSIt->loadSlice();
10640 CombineTo(LSIt->Inst, SliceInst, true);
10641 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10642 SliceInst = SliceInst.getOperand(0);
10643 assert(SliceInst->getOpcode() == ISD::LOAD &&
10644 "It takes more than a zext to get to the loaded slice!!");
10645 ArgChains.push_back(SliceInst.getValue(1));
10648 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10650 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10654 /// Check to see if V is (and load (ptr), imm), where the load is having
10655 /// specific bytes cleared out. If so, return the byte size being masked out
10656 /// and the shift amount.
10657 static std::pair<unsigned, unsigned>
10658 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10659 std::pair<unsigned, unsigned> Result(0, 0);
10661 // Check for the structure we're looking for.
10662 if (V->getOpcode() != ISD::AND ||
10663 !isa<ConstantSDNode>(V->getOperand(1)) ||
10664 !ISD::isNormalLoad(V->getOperand(0).getNode()))
10667 // Check the chain and pointer.
10668 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10669 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
10671 // The store should be chained directly to the load or be an operand of a
10673 if (LD == Chain.getNode())
10675 else if (Chain->getOpcode() != ISD::TokenFactor)
10676 return Result; // Fail.
10679 for (const SDValue &ChainOp : Chain->op_values())
10680 if (ChainOp.getNode() == LD) {
10684 if (!isOk) return Result;
10687 // This only handles simple types.
10688 if (V.getValueType() != MVT::i16 &&
10689 V.getValueType() != MVT::i32 &&
10690 V.getValueType() != MVT::i64)
10693 // Check the constant mask. Invert it so that the bits being masked out are
10694 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
10695 // follow the sign bit for uniformity.
10696 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10697 unsigned NotMaskLZ = countLeadingZeros(NotMask);
10698 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
10699 unsigned NotMaskTZ = countTrailingZeros(NotMask);
10700 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
10701 if (NotMaskLZ == 64) return Result; // All zero mask.
10703 // See if we have a continuous run of bits. If so, we have 0*1+0*
10704 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10707 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10708 if (V.getValueType() != MVT::i64 && NotMaskLZ)
10709 NotMaskLZ -= 64-V.getValueSizeInBits();
10711 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10712 switch (MaskedBytes) {
10716 default: return Result; // All one mask, or 5-byte mask.
10719 // Verify that the first bit starts at a multiple of mask so that the access
10720 // is aligned the same as the access width.
10721 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10723 Result.first = MaskedBytes;
10724 Result.second = NotMaskTZ/8;
10729 /// Check to see if IVal is something that provides a value as specified by
10730 /// MaskInfo. If so, replace the specified store with a narrower store of
10731 /// truncated IVal.
10733 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10734 SDValue IVal, StoreSDNode *St,
10736 unsigned NumBytes = MaskInfo.first;
10737 unsigned ByteShift = MaskInfo.second;
10738 SelectionDAG &DAG = DC->getDAG();
10740 // Check to see if IVal is all zeros in the part being masked in by the 'or'
10741 // that uses this. If not, this is not a replacement.
10742 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10743 ByteShift*8, (ByteShift+NumBytes)*8);
10744 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10746 // Check that it is legal on the target to do this. It is legal if the new
10747 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10749 MVT VT = MVT::getIntegerVT(NumBytes*8);
10750 if (!DC->isTypeLegal(VT))
10753 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
10754 // shifted by ByteShift and truncated down to NumBytes.
10757 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10758 DAG.getConstant(ByteShift*8, DL,
10759 DC->getShiftAmountTy(IVal.getValueType())));
10762 // Figure out the offset for the store and the alignment of the access.
10764 unsigned NewAlign = St->getAlignment();
10766 if (DAG.getDataLayout().isLittleEndian())
10767 StOffset = ByteShift;
10769 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10771 SDValue Ptr = St->getBasePtr();
10774 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10775 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10776 NewAlign = MinAlign(NewAlign, StOffset);
10779 // Truncate down to the new size.
10780 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10783 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10784 St->getPointerInfo().getWithOffset(StOffset),
10785 false, false, NewAlign).getNode();
10789 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10790 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10791 /// narrowing the load and store if it would end up being a win for performance
10793 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10794 StoreSDNode *ST = cast<StoreSDNode>(N);
10795 if (ST->isVolatile())
10798 SDValue Chain = ST->getChain();
10799 SDValue Value = ST->getValue();
10800 SDValue Ptr = ST->getBasePtr();
10801 EVT VT = Value.getValueType();
10803 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10806 unsigned Opc = Value.getOpcode();
10808 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10809 // is a byte mask indicating a consecutive number of bytes, check to see if
10810 // Y is known to provide just those bytes. If so, we try to replace the
10811 // load + replace + store sequence with a single (narrower) store, which makes
10813 if (Opc == ISD::OR) {
10814 std::pair<unsigned, unsigned> MaskedLoad;
10815 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10816 if (MaskedLoad.first)
10817 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10818 Value.getOperand(1), ST,this))
10819 return SDValue(NewST, 0);
10821 // Or is commutative, so try swapping X and Y.
10822 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10823 if (MaskedLoad.first)
10824 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10825 Value.getOperand(0), ST,this))
10826 return SDValue(NewST, 0);
10829 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10830 Value.getOperand(1).getOpcode() != ISD::Constant)
10833 SDValue N0 = Value.getOperand(0);
10834 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10835 Chain == SDValue(N0.getNode(), 1)) {
10836 LoadSDNode *LD = cast<LoadSDNode>(N0);
10837 if (LD->getBasePtr() != Ptr ||
10838 LD->getPointerInfo().getAddrSpace() !=
10839 ST->getPointerInfo().getAddrSpace())
10842 // Find the type to narrow it the load / op / store to.
10843 SDValue N1 = Value.getOperand(1);
10844 unsigned BitWidth = N1.getValueSizeInBits();
10845 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10846 if (Opc == ISD::AND)
10847 Imm ^= APInt::getAllOnesValue(BitWidth);
10848 if (Imm == 0 || Imm.isAllOnesValue())
10850 unsigned ShAmt = Imm.countTrailingZeros();
10851 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10852 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10853 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10854 // The narrowing should be profitable, the load/store operation should be
10855 // legal (or custom) and the store size should be equal to the NewVT width.
10856 while (NewBW < BitWidth &&
10857 (NewVT.getStoreSizeInBits() != NewBW ||
10858 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10859 !TLI.isNarrowingProfitable(VT, NewVT))) {
10860 NewBW = NextPowerOf2(NewBW);
10861 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10863 if (NewBW >= BitWidth)
10866 // If the lsb changed does not start at the type bitwidth boundary,
10867 // start at the previous one.
10869 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10870 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10871 std::min(BitWidth, ShAmt + NewBW));
10872 if ((Imm & Mask) == Imm) {
10873 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10874 if (Opc == ISD::AND)
10875 NewImm ^= APInt::getAllOnesValue(NewBW);
10876 uint64_t PtrOff = ShAmt / 8;
10877 // For big endian targets, we need to adjust the offset to the pointer to
10878 // load the correct bytes.
10879 if (DAG.getDataLayout().isBigEndian())
10880 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10882 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10883 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10884 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10887 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10888 Ptr.getValueType(), Ptr,
10889 DAG.getConstant(PtrOff, SDLoc(LD),
10890 Ptr.getValueType()));
10891 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10892 LD->getChain(), NewPtr,
10893 LD->getPointerInfo().getWithOffset(PtrOff),
10894 LD->isVolatile(), LD->isNonTemporal(),
10895 LD->isInvariant(), NewAlign,
10897 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10898 DAG.getConstant(NewImm, SDLoc(Value),
10900 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10902 ST->getPointerInfo().getWithOffset(PtrOff),
10903 false, false, NewAlign);
10905 AddToWorklist(NewPtr.getNode());
10906 AddToWorklist(NewLD.getNode());
10907 AddToWorklist(NewVal.getNode());
10908 WorklistRemover DeadNodes(*this);
10909 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10918 /// For a given floating point load / store pair, if the load value isn't used
10919 /// by any other operations, then consider transforming the pair to integer
10920 /// load / store operations if the target deems the transformation profitable.
10921 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10922 StoreSDNode *ST = cast<StoreSDNode>(N);
10923 SDValue Chain = ST->getChain();
10924 SDValue Value = ST->getValue();
10925 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10926 Value.hasOneUse() &&
10927 Chain == SDValue(Value.getNode(), 1)) {
10928 LoadSDNode *LD = cast<LoadSDNode>(Value);
10929 EVT VT = LD->getMemoryVT();
10930 if (!VT.isFloatingPoint() ||
10931 VT != ST->getMemoryVT() ||
10932 LD->isNonTemporal() ||
10933 ST->isNonTemporal() ||
10934 LD->getPointerInfo().getAddrSpace() != 0 ||
10935 ST->getPointerInfo().getAddrSpace() != 0)
10938 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10939 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10940 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10941 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10942 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10945 unsigned LDAlign = LD->getAlignment();
10946 unsigned STAlign = ST->getAlignment();
10947 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10948 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10949 if (LDAlign < ABIAlign || STAlign < ABIAlign)
10952 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10953 LD->getChain(), LD->getBasePtr(),
10954 LD->getPointerInfo(),
10955 false, false, false, LDAlign);
10957 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10958 NewLD, ST->getBasePtr(),
10959 ST->getPointerInfo(),
10960 false, false, STAlign);
10962 AddToWorklist(NewLD.getNode());
10963 AddToWorklist(NewST.getNode());
10964 WorklistRemover DeadNodes(*this);
10965 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10974 /// Helper struct to parse and store a memory address as base + index + offset.
10975 /// We ignore sign extensions when it is safe to do so.
10976 /// The following two expressions are not equivalent. To differentiate we need
10977 /// to store whether there was a sign extension involved in the index
10979 /// (load (i64 add (i64 copyfromreg %c)
10980 /// (i64 signextend (add (i8 load %index)
10984 /// (load (i64 add (i64 copyfromreg %c)
10985 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
10987 struct BaseIndexOffset {
10991 bool IsIndexSignExt;
10993 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10995 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10996 bool IsIndexSignExt) :
10997 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10999 bool equalBaseIndex(const BaseIndexOffset &Other) {
11000 return Other.Base == Base && Other.Index == Index &&
11001 Other.IsIndexSignExt == IsIndexSignExt;
11004 /// Parses tree in Ptr for base, index, offset addresses.
11005 static BaseIndexOffset match(SDValue Ptr) {
11006 bool IsIndexSignExt = false;
11008 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
11009 // instruction, then it could be just the BASE or everything else we don't
11010 // know how to handle. Just use Ptr as BASE and give up.
11011 if (Ptr->getOpcode() != ISD::ADD)
11012 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11014 // We know that we have at least an ADD instruction. Try to pattern match
11015 // the simple case of BASE + OFFSET.
11016 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
11017 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
11018 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
11022 // Inside a loop the current BASE pointer is calculated using an ADD and a
11023 // MUL instruction. In this case Ptr is the actual BASE pointer.
11024 // (i64 add (i64 %array_ptr)
11025 // (i64 mul (i64 %induction_var)
11026 // (i64 %element_size)))
11027 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
11028 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11030 // Look at Base + Index + Offset cases.
11031 SDValue Base = Ptr->getOperand(0);
11032 SDValue IndexOffset = Ptr->getOperand(1);
11034 // Skip signextends.
11035 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
11036 IndexOffset = IndexOffset->getOperand(0);
11037 IsIndexSignExt = true;
11040 // Either the case of Base + Index (no offset) or something else.
11041 if (IndexOffset->getOpcode() != ISD::ADD)
11042 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
11044 // Now we have the case of Base + Index + offset.
11045 SDValue Index = IndexOffset->getOperand(0);
11046 SDValue Offset = IndexOffset->getOperand(1);
11048 if (!isa<ConstantSDNode>(Offset))
11049 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11051 // Ignore signextends.
11052 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
11053 Index = Index->getOperand(0);
11054 IsIndexSignExt = true;
11055 } else IsIndexSignExt = false;
11057 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
11058 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
11063 // This is a helper function for visitMUL to check the profitability
11064 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
11065 // MulNode is the original multiply, AddNode is (add x, c1),
11066 // and ConstNode is c2.
11068 // If the (add x, c1) has multiple uses, we could increase
11069 // the number of adds if we make this transformation.
11070 // It would only be worth doing this if we can remove a
11071 // multiply in the process. Check for that here.
11075 // We're checking for cases where we have common "c3 * A" expressions.
11076 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
11078 SDValue &ConstNode) {
11081 // If the add only has one use, this would be OK to do.
11082 if (AddNode.getNode()->hasOneUse())
11085 // Walk all the users of the constant with which we're multiplying.
11086 for (SDNode *Use : ConstNode->uses()) {
11088 if (Use == MulNode) // This use is the one we're on right now. Skip it.
11091 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
11093 SDNode *MulVar = AddNode.getOperand(0).getNode();
11095 // OtherOp is what we're multiplying against the constant.
11096 if (Use->getOperand(0) == ConstNode)
11097 OtherOp = Use->getOperand(1).getNode();
11099 OtherOp = Use->getOperand(0).getNode();
11101 // Check to see if multiply is with the same operand of our "add".
11103 // ConstNode = CONST
11104 // Use = ConstNode * A <-- visiting Use. OtherOp is A.
11106 // AddNode = (A + c1) <-- MulVar is A.
11107 // = AddNode * ConstNode <-- current visiting instruction.
11109 // If we make this transformation, we will have a common
11110 // multiply (ConstNode * A) that we can save.
11111 if (OtherOp == MulVar)
11114 // Now check to see if a future expansion will give us a common
11117 // ConstNode = CONST
11118 // AddNode = (A + c1)
11119 // ... = AddNode * ConstNode <-- current visiting instruction.
11121 // OtherOp = (A + c2)
11122 // Use = OtherOp * ConstNode <-- visiting Use.
11124 // If we make this transformation, we will have a common
11125 // multiply (CONST * A) after we also do the same transformation
11126 // to the "t2" instruction.
11127 if (OtherOp->getOpcode() == ISD::ADD &&
11128 isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
11129 OtherOp->getOperand(0).getNode() == MulVar)
11134 // Didn't find a case where this would be profitable.
11138 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
11140 ArrayRef<MemOpLink> Stores,
11141 SmallVectorImpl<SDValue> &Chains,
11143 SmallVector<SDValue, 8> BuildVector;
11145 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
11146 StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
11147 Chains.push_back(St->getChain());
11148 BuildVector.push_back(St->getValue());
11151 return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
11154 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
11155 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
11156 unsigned NumStores, bool IsConstantSrc, bool UseVector) {
11157 // Make sure we have something to merge.
11161 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11162 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11163 unsigned LatestNodeUsed = 0;
11165 for (unsigned i=0; i < NumStores; ++i) {
11166 // Find a chain for the new wide-store operand. Notice that some
11167 // of the store nodes that we found may not be selected for inclusion
11168 // in the wide store. The chain we use needs to be the chain of the
11169 // latest store node which is *used* and replaced by the wide store.
11170 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11171 LatestNodeUsed = i;
11174 SmallVector<SDValue, 8> Chains;
11176 // The latest Node in the DAG.
11177 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11178 SDLoc DL(StoreNodes[0].MemNode);
11182 bool IsVec = MemVT.isVector();
11183 unsigned Elts = NumStores;
11185 // When merging vector stores, get the total number of elements.
11186 Elts *= MemVT.getVectorNumElements();
11188 // Get the type for the merged vector store.
11189 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11190 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
11192 if (IsConstantSrc) {
11193 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
11195 SmallVector<SDValue, 8> Ops;
11196 for (unsigned i = 0; i < NumStores; ++i) {
11197 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11198 SDValue Val = St->getValue();
11199 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
11200 if (Val.getValueType() != MemVT)
11202 Ops.push_back(Val);
11203 Chains.push_back(St->getChain());
11206 // Build the extracted vector elements back into a vector.
11207 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
11210 // We should always use a vector store when merging extracted vector
11211 // elements, so this path implies a store of constants.
11212 assert(IsConstantSrc && "Merged vector elements should use vector store");
11214 unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
11215 APInt StoreInt(SizeInBits, 0);
11217 // Construct a single integer constant which is made of the smaller
11218 // constant inputs.
11219 bool IsLE = DAG.getDataLayout().isLittleEndian();
11220 for (unsigned i = 0; i < NumStores; ++i) {
11221 unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
11222 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
11223 Chains.push_back(St->getChain());
11225 SDValue Val = St->getValue();
11226 StoreInt <<= ElementSizeBytes * 8;
11227 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
11228 StoreInt |= C->getAPIntValue().zext(SizeInBits);
11229 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
11230 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
11232 llvm_unreachable("Invalid constant element type");
11236 // Create the new Load and Store operations.
11237 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11238 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
11241 assert(!Chains.empty());
11243 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11244 SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
11245 FirstInChain->getBasePtr(),
11246 FirstInChain->getPointerInfo(),
11248 FirstInChain->getAlignment());
11250 // Replace the last store with the new store
11251 CombineTo(LatestOp, NewStore);
11252 // Erase all other stores.
11253 for (unsigned i = 0; i < NumStores; ++i) {
11254 if (StoreNodes[i].MemNode == LatestOp)
11256 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11257 // ReplaceAllUsesWith will replace all uses that existed when it was
11258 // called, but graph optimizations may cause new ones to appear. For
11259 // example, the case in pr14333 looks like
11261 // St's chain -> St -> another store -> X
11263 // And the only difference from St to the other store is the chain.
11264 // When we change it's chain to be St's chain they become identical,
11265 // get CSEed and the net result is that X is now a use of St.
11266 // Since we know that St is redundant, just iterate.
11267 while (!St->use_empty())
11268 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
11269 deleteAndRecombine(St);
11275 void DAGCombiner::getStoreMergeAndAliasCandidates(
11276 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
11277 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
11278 // This holds the base pointer, index, and the offset in bytes from the base
11280 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
11282 // We must have a base and an offset.
11283 if (!BasePtr.Base.getNode())
11286 // Do not handle stores to undef base pointers.
11287 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
11290 // Walk up the chain and look for nodes with offsets from the same
11291 // base pointer. Stop when reaching an instruction with a different kind
11292 // or instruction which has a different base pointer.
11293 EVT MemVT = St->getMemoryVT();
11295 StoreSDNode *Index = St;
11298 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11299 : DAG.getSubtarget().useAA();
11302 // Look at other users of the same chain. Stores on the same chain do not
11303 // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
11304 // to be on the same chain, so don't bother looking at adjacent chains.
11306 SDValue Chain = St->getChain();
11307 for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
11308 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
11309 if (I.getOperandNo() != 0)
11312 if (OtherST->isVolatile() || OtherST->isIndexed())
11315 if (OtherST->getMemoryVT() != MemVT)
11318 BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr());
11320 if (Ptr.equalBaseIndex(BasePtr))
11321 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
11329 // If the chain has more than one use, then we can't reorder the mem ops.
11330 if (Index != St && !SDValue(Index, 0)->hasOneUse())
11333 // Find the base pointer and offset for this memory node.
11334 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
11336 // Check that the base pointer is the same as the original one.
11337 if (!Ptr.equalBaseIndex(BasePtr))
11340 // The memory operands must not be volatile.
11341 if (Index->isVolatile() || Index->isIndexed())
11345 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
11346 if (St->isTruncatingStore())
11349 // The stored memory type must be the same.
11350 if (Index->getMemoryVT() != MemVT)
11353 // We do not allow under-aligned stores in order to prevent
11354 // overriding stores. NOTE: this is a bad hack. Alignment SHOULD
11355 // be irrelevant here; what MATTERS is that we not move memory
11356 // operations that potentially overlap past each-other.
11357 if (Index->getAlignment() < MemVT.getStoreSize())
11360 // We found a potential memory operand to merge.
11361 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11363 // Find the next memory operand in the chain. If the next operand in the
11364 // chain is a store then move up and continue the scan with the next
11365 // memory operand. If the next operand is a load save it and use alias
11366 // information to check if it interferes with anything.
11367 SDNode *NextInChain = Index->getChain().getNode();
11369 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11370 // We found a store node. Use it for the next iteration.
11373 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11374 if (Ldn->isVolatile()) {
11379 // Save the load node for later. Continue the scan.
11380 AliasLoadNodes.push_back(Ldn);
11381 NextInChain = Ldn->getChain().getNode();
11391 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
11392 if (OptLevel == CodeGenOpt::None)
11395 EVT MemVT = St->getMemoryVT();
11396 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11397 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11398 Attribute::NoImplicitFloat);
11400 // This function cannot currently deal with non-byte-sized memory sizes.
11401 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11404 if (!MemVT.isSimple())
11407 // Perform an early exit check. Do not bother looking at stored values that
11408 // are not constants, loads, or extracted vector elements.
11409 SDValue StoredVal = St->getValue();
11410 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11411 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11412 isa<ConstantFPSDNode>(StoredVal);
11413 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11414 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11416 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11419 // Don't merge vectors into wider vectors if the source data comes from loads.
11420 // TODO: This restriction can be lifted by using logic similar to the
11421 // ExtractVecSrc case.
11422 if (MemVT.isVector() && IsLoadSrc)
11425 // Only look at ends of store sequences.
11426 SDValue Chain = SDValue(St, 0);
11427 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11430 // Save the LoadSDNodes that we find in the chain.
11431 // We need to make sure that these nodes do not interfere with
11432 // any of the store nodes.
11433 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11435 // Save the StoreSDNodes that we find in the chain.
11436 SmallVector<MemOpLink, 8> StoreNodes;
11438 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11440 // Check if there is anything to merge.
11441 if (StoreNodes.size() < 2)
11444 // Sort the memory operands according to their distance from the
11445 // base pointer. As a secondary criteria: make sure stores coming
11446 // later in the code come first in the list. This is important for
11447 // the non-UseAA case, because we're merging stores into the FINAL
11448 // store along a chain which potentially contains aliasing stores.
11449 // Thus, if there are multiple stores to the same address, the last
11450 // one can be considered for merging but not the others.
11451 std::sort(StoreNodes.begin(), StoreNodes.end(),
11452 [](MemOpLink LHS, MemOpLink RHS) {
11453 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11454 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11455 LHS.SequenceNum < RHS.SequenceNum);
11458 // Scan the memory operations on the chain and find the first non-consecutive
11459 // store memory address.
11460 unsigned LastConsecutiveStore = 0;
11461 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11462 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11464 // Check that the addresses are consecutive starting from the second
11465 // element in the list of stores.
11467 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11468 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11472 // Check if this store interferes with any of the loads that we found.
11473 // If we find a load that alias with this store. Stop the sequence.
11474 if (std::any_of(AliasLoadNodes.begin(), AliasLoadNodes.end(),
11475 [&](LSBaseSDNode* Ldn) {
11476 return isAlias(Ldn, StoreNodes[i].MemNode);
11480 // Mark this node as useful.
11481 LastConsecutiveStore = i;
11484 // The node with the lowest store address.
11485 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11486 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11487 unsigned FirstStoreAlign = FirstInChain->getAlignment();
11488 LLVMContext &Context = *DAG.getContext();
11489 const DataLayout &DL = DAG.getDataLayout();
11491 // Store the constants into memory as one consecutive store.
11492 if (IsConstantSrc) {
11493 unsigned LastLegalType = 0;
11494 unsigned LastLegalVectorType = 0;
11495 bool NonZero = false;
11496 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11497 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11498 SDValue StoredVal = St->getValue();
11500 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11501 NonZero |= !C->isNullValue();
11502 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11503 NonZero |= !C->getConstantFPValue()->isNullValue();
11509 // Find a legal type for the constant store.
11510 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11511 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11513 if (TLI.isTypeLegal(StoreTy) &&
11514 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11515 FirstStoreAlign, &IsFast) && IsFast) {
11516 LastLegalType = i+1;
11517 // Or check whether a truncstore is legal.
11518 } else if (TLI.getTypeAction(Context, StoreTy) ==
11519 TargetLowering::TypePromoteInteger) {
11520 EVT LegalizedStoredValueTy =
11521 TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11522 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11523 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11524 FirstStoreAS, FirstStoreAlign, &IsFast) &&
11526 LastLegalType = i + 1;
11530 // We only use vectors if the constant is known to be zero or the target
11531 // allows it and the function is not marked with the noimplicitfloat
11533 if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11536 // Find a legal type for the vector store.
11537 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11538 if (TLI.isTypeLegal(Ty) &&
11539 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11540 FirstStoreAlign, &IsFast) && IsFast)
11541 LastLegalVectorType = i + 1;
11545 // Check if we found a legal integer type to store.
11546 if (LastLegalType == 0 && LastLegalVectorType == 0)
11549 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11550 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11552 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11556 // When extracting multiple vector elements, try to store them
11557 // in one vector store rather than a sequence of scalar stores.
11558 if (IsExtractVecSrc) {
11559 unsigned NumStoresToMerge = 0;
11560 bool IsVec = MemVT.isVector();
11561 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11562 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11563 unsigned StoreValOpcode = St->getValue().getOpcode();
11564 // This restriction could be loosened.
11565 // Bail out if any stored values are not elements extracted from a vector.
11566 // It should be possible to handle mixed sources, but load sources need
11567 // more careful handling (see the block of code below that handles
11568 // consecutive loads).
11569 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11570 StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11573 // Find a legal type for the vector store.
11574 unsigned Elts = i + 1;
11576 // When merging vector stores, get the total number of elements.
11577 Elts *= MemVT.getVectorNumElements();
11579 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11581 if (TLI.isTypeLegal(Ty) &&
11582 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11583 FirstStoreAlign, &IsFast) && IsFast)
11584 NumStoresToMerge = i + 1;
11587 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11591 // Below we handle the case of multiple consecutive stores that
11592 // come from multiple consecutive loads. We merge them into a single
11593 // wide load and a single wide store.
11595 // Look for load nodes which are used by the stored values.
11596 SmallVector<MemOpLink, 8> LoadNodes;
11598 // Find acceptable loads. Loads need to have the same chain (token factor),
11599 // must not be zext, volatile, indexed, and they must be consecutive.
11600 BaseIndexOffset LdBasePtr;
11601 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11602 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11603 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11606 // Loads must only have one use.
11607 if (!Ld->hasNUsesOfValue(1, 0))
11610 // The memory operands must not be volatile.
11611 if (Ld->isVolatile() || Ld->isIndexed())
11614 // We do not accept ext loads.
11615 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11618 // The stored memory type must be the same.
11619 if (Ld->getMemoryVT() != MemVT)
11622 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11623 // If this is not the first ptr that we check.
11624 if (LdBasePtr.Base.getNode()) {
11625 // The base ptr must be the same.
11626 if (!LdPtr.equalBaseIndex(LdBasePtr))
11629 // Check that all other base pointers are the same as this one.
11633 // We found a potential memory operand to merge.
11634 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11637 if (LoadNodes.size() < 2)
11640 // If we have load/store pair instructions and we only have two values,
11642 unsigned RequiredAlignment;
11643 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11644 St->getAlignment() >= RequiredAlignment)
11647 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11648 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11649 unsigned FirstLoadAlign = FirstLoad->getAlignment();
11651 // Scan the memory operations on the chain and find the first non-consecutive
11652 // load memory address. These variables hold the index in the store node
11654 unsigned LastConsecutiveLoad = 0;
11655 // This variable refers to the size and not index in the array.
11656 unsigned LastLegalVectorType = 0;
11657 unsigned LastLegalIntegerType = 0;
11658 StartAddress = LoadNodes[0].OffsetFromBase;
11659 SDValue FirstChain = FirstLoad->getChain();
11660 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11661 // All loads must share the same chain.
11662 if (LoadNodes[i].MemNode->getChain() != FirstChain)
11665 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11666 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11668 LastConsecutiveLoad = i;
11669 // Find a legal type for the vector store.
11670 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11671 bool IsFastSt, IsFastLd;
11672 if (TLI.isTypeLegal(StoreTy) &&
11673 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11674 FirstStoreAlign, &IsFastSt) && IsFastSt &&
11675 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11676 FirstLoadAlign, &IsFastLd) && IsFastLd) {
11677 LastLegalVectorType = i + 1;
11680 // Find a legal type for the integer store.
11681 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11682 StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11683 if (TLI.isTypeLegal(StoreTy) &&
11684 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11685 FirstStoreAlign, &IsFastSt) && IsFastSt &&
11686 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11687 FirstLoadAlign, &IsFastLd) && IsFastLd)
11688 LastLegalIntegerType = i + 1;
11689 // Or check whether a truncstore and extload is legal.
11690 else if (TLI.getTypeAction(Context, StoreTy) ==
11691 TargetLowering::TypePromoteInteger) {
11692 EVT LegalizedStoredValueTy =
11693 TLI.getTypeToTransformTo(Context, StoreTy);
11694 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11695 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11696 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11697 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11698 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11699 FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11701 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11702 FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11704 LastLegalIntegerType = i+1;
11708 // Only use vector types if the vector type is larger than the integer type.
11709 // If they are the same, use integers.
11710 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11711 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11713 // We add +1 here because the LastXXX variables refer to location while
11714 // the NumElem refers to array/index size.
11715 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11716 NumElem = std::min(LastLegalType, NumElem);
11721 // Collect the chains from all merged stores.
11722 SmallVector<SDValue, 8> MergeStoreChains;
11723 MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
11725 // The latest Node in the DAG.
11726 unsigned LatestNodeUsed = 0;
11727 for (unsigned i=1; i<NumElem; ++i) {
11728 // Find a chain for the new wide-store operand. Notice that some
11729 // of the store nodes that we found may not be selected for inclusion
11730 // in the wide store. The chain we use needs to be the chain of the
11731 // latest store node which is *used* and replaced by the wide store.
11732 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11733 LatestNodeUsed = i;
11735 MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
11738 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11740 // Find if it is better to use vectors or integers to load and store
11744 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11746 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11747 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11750 SDLoc LoadDL(LoadNodes[0].MemNode);
11751 SDLoc StoreDL(StoreNodes[0].MemNode);
11753 // The merged loads are required to have the same incoming chain, so
11754 // using the first's chain is acceptable.
11755 SDValue NewLoad = DAG.getLoad(
11756 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11757 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11759 SDValue NewStoreChain =
11760 DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
11762 SDValue NewStore = DAG.getStore(
11763 NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
11764 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11766 // Transfer chain users from old loads to the new load.
11767 for (unsigned i = 0; i < NumElem; ++i) {
11768 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11769 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11770 SDValue(NewLoad.getNode(), 1));
11773 // Replace the last store with the new store.
11774 CombineTo(LatestOp, NewStore);
11775 // Erase all other stores.
11776 for (unsigned i = 0; i < NumElem ; ++i) {
11777 // Remove all Store nodes.
11778 if (StoreNodes[i].MemNode == LatestOp)
11780 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11781 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11782 deleteAndRecombine(St);
11788 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11792 // Replace the chain to avoid dependency.
11793 if (ST->isTruncatingStore()) {
11794 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11795 ST->getBasePtr(), ST->getMemoryVT(),
11796 ST->getMemOperand());
11798 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11799 ST->getMemOperand());
11802 // Create token to keep both nodes around.
11803 SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11804 MVT::Other, ST->getChain(), ReplStore);
11806 // Make sure the new and old chains are cleaned up.
11807 AddToWorklist(Token.getNode());
11809 // Don't add users to work list.
11810 return CombineTo(ST, Token, false);
11813 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
11814 SDValue Value = ST->getValue();
11815 if (Value.getOpcode() == ISD::TargetConstantFP)
11820 SDValue Chain = ST->getChain();
11821 SDValue Ptr = ST->getBasePtr();
11823 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
11825 // NOTE: If the original store is volatile, this transform must not increase
11826 // the number of stores. For example, on x86-32 an f64 can be stored in one
11827 // processor operation but an i64 (which is not legal) requires two. So the
11828 // transform should not be done in this case.
11831 switch (CFP->getSimpleValueType(0).SimpleTy) {
11833 llvm_unreachable("Unknown FP type");
11834 case MVT::f16: // We don't do this for these yet.
11840 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11841 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11843 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11844 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11846 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
11851 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11852 !ST->isVolatile()) ||
11853 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11855 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11856 getZExtValue(), SDLoc(CFP), MVT::i64);
11857 return DAG.getStore(Chain, DL, Tmp,
11858 Ptr, ST->getMemOperand());
11861 if (!ST->isVolatile() &&
11862 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11863 // Many FP stores are not made apparent until after legalize, e.g. for
11864 // argument passing. Since this is so common, custom legalize the
11865 // 64-bit integer store into two 32-bit stores.
11866 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11867 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11868 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11869 if (DAG.getDataLayout().isBigEndian())
11872 unsigned Alignment = ST->getAlignment();
11873 bool isVolatile = ST->isVolatile();
11874 bool isNonTemporal = ST->isNonTemporal();
11875 AAMDNodes AAInfo = ST->getAAInfo();
11877 SDValue St0 = DAG.getStore(Chain, DL, Lo,
11878 Ptr, ST->getPointerInfo(),
11879 isVolatile, isNonTemporal,
11880 ST->getAlignment(), AAInfo);
11881 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11882 DAG.getConstant(4, DL, Ptr.getValueType()));
11883 Alignment = MinAlign(Alignment, 4U);
11884 SDValue St1 = DAG.getStore(Chain, DL, Hi,
11885 Ptr, ST->getPointerInfo().getWithOffset(4),
11886 isVolatile, isNonTemporal,
11887 Alignment, AAInfo);
11888 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11896 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11897 StoreSDNode *ST = cast<StoreSDNode>(N);
11898 SDValue Chain = ST->getChain();
11899 SDValue Value = ST->getValue();
11900 SDValue Ptr = ST->getBasePtr();
11902 // If this is a store of a bit convert, store the input value if the
11903 // resultant store does not need a higher alignment than the original.
11904 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11905 ST->isUnindexed()) {
11906 unsigned OrigAlign = ST->getAlignment();
11907 EVT SVT = Value.getOperand(0).getValueType();
11908 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11909 SVT.getTypeForEVT(*DAG.getContext()));
11910 if (Align <= OrigAlign &&
11911 ((!LegalOperations && !ST->isVolatile()) ||
11912 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11913 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11914 Ptr, ST->getPointerInfo(), ST->isVolatile(),
11915 ST->isNonTemporal(), OrigAlign,
11919 // Turn 'store undef, Ptr' -> nothing.
11920 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11923 // Try to infer better alignment information than the store already has.
11924 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11925 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11926 if (Align > ST->getAlignment()) {
11928 DAG.getTruncStore(Chain, SDLoc(N), Value,
11929 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11930 ST->isVolatile(), ST->isNonTemporal(), Align,
11932 if (NewStore.getNode() != N)
11933 return CombineTo(ST, NewStore, true);
11938 // Try transforming a pair floating point load / store ops to integer
11939 // load / store ops.
11940 if (SDValue NewST = TransformFPLoadStorePair(N))
11943 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11944 : DAG.getSubtarget().useAA();
11946 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11947 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11950 if (UseAA && ST->isUnindexed()) {
11951 // FIXME: We should do this even without AA enabled. AA will just allow
11952 // FindBetterChain to work in more situations. The problem with this is that
11953 // any combine that expects memory operations to be on consecutive chains
11954 // first needs to be updated to look for users of the same chain.
11956 // Walk up chain skipping non-aliasing memory nodes, on this store and any
11957 // adjacent stores.
11958 if (findBetterNeighborChains(ST)) {
11959 // replaceStoreChain uses CombineTo, which handled all of the worklist
11960 // manipulation. Return the original node to not do anything else.
11961 return SDValue(ST, 0);
11965 // Try transforming N to an indexed store.
11966 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11967 return SDValue(N, 0);
11969 // FIXME: is there such a thing as a truncating indexed store?
11970 if (ST->isTruncatingStore() && ST->isUnindexed() &&
11971 Value.getValueType().isInteger()) {
11972 // See if we can simplify the input to this truncstore with knowledge that
11973 // only the low bits are being used. For example:
11974 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
11976 GetDemandedBits(Value,
11977 APInt::getLowBitsSet(
11978 Value.getValueType().getScalarType().getSizeInBits(),
11979 ST->getMemoryVT().getScalarType().getSizeInBits()));
11980 AddToWorklist(Value.getNode());
11981 if (Shorter.getNode())
11982 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11983 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11985 // Otherwise, see if we can simplify the operation with
11986 // SimplifyDemandedBits, which only works if the value has a single use.
11987 if (SimplifyDemandedBits(Value,
11988 APInt::getLowBitsSet(
11989 Value.getValueType().getScalarType().getSizeInBits(),
11990 ST->getMemoryVT().getScalarType().getSizeInBits())))
11991 return SDValue(N, 0);
11994 // If this is a load followed by a store to the same location, then the store
11996 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11997 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11998 ST->isUnindexed() && !ST->isVolatile() &&
11999 // There can't be any side effects between the load and store, such as
12000 // a call or store.
12001 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
12002 // The store is dead, remove it.
12007 // If this is a store followed by a store with the same value to the same
12008 // location, then the store is dead/noop.
12009 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
12010 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
12011 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
12012 ST1->isUnindexed() && !ST1->isVolatile()) {
12013 // The store is dead, remove it.
12018 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
12019 // truncating store. We can do this even if this is already a truncstore.
12020 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
12021 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
12022 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
12023 ST->getMemoryVT())) {
12024 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
12025 Ptr, ST->getMemoryVT(), ST->getMemOperand());
12028 // Only perform this optimization before the types are legal, because we
12029 // don't want to perform this optimization on every DAGCombine invocation.
12031 bool EverChanged = false;
12034 // There can be multiple store sequences on the same chain.
12035 // Keep trying to merge store sequences until we are unable to do so
12036 // or until we merge the last store on the chain.
12037 bool Changed = MergeConsecutiveStores(ST);
12038 EverChanged |= Changed;
12039 if (!Changed) break;
12040 } while (ST->getOpcode() != ISD::DELETED_NODE);
12043 return SDValue(N, 0);
12046 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
12048 // Make sure to do this only after attempting to merge stores in order to
12049 // avoid changing the types of some subset of stores due to visit order,
12050 // preventing their merging.
12051 if (isa<ConstantFPSDNode>(Value)) {
12052 if (SDValue NewSt = replaceStoreOfFPConstant(ST))
12056 return ReduceLoadOpStoreWidth(N);
12059 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
12060 SDValue InVec = N->getOperand(0);
12061 SDValue InVal = N->getOperand(1);
12062 SDValue EltNo = N->getOperand(2);
12065 // If the inserted element is an UNDEF, just use the input vector.
12066 if (InVal.getOpcode() == ISD::UNDEF)
12069 EVT VT = InVec.getValueType();
12071 // If we can't generate a legal BUILD_VECTOR, exit
12072 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
12075 // Check that we know which element is being inserted
12076 if (!isa<ConstantSDNode>(EltNo))
12078 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12080 // Canonicalize insert_vector_elt dag nodes.
12082 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
12083 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
12085 // Do this only if the child insert_vector node has one use; also
12086 // do this only if indices are both constants and Idx1 < Idx0.
12087 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
12088 && isa<ConstantSDNode>(InVec.getOperand(2))) {
12089 unsigned OtherElt =
12090 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
12091 if (Elt < OtherElt) {
12093 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
12094 InVec.getOperand(0), InVal, EltNo);
12095 AddToWorklist(NewOp.getNode());
12096 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
12097 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
12101 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
12102 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
12103 // vector elements.
12104 SmallVector<SDValue, 8> Ops;
12105 // Do not combine these two vectors if the output vector will not replace
12106 // the input vector.
12107 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
12108 Ops.append(InVec.getNode()->op_begin(),
12109 InVec.getNode()->op_end());
12110 } else if (InVec.getOpcode() == ISD::UNDEF) {
12111 unsigned NElts = VT.getVectorNumElements();
12112 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
12117 // Insert the element
12118 if (Elt < Ops.size()) {
12119 // All the operands of BUILD_VECTOR must have the same type;
12120 // we enforce that here.
12121 EVT OpVT = Ops[0].getValueType();
12122 if (InVal.getValueType() != OpVT)
12123 InVal = OpVT.bitsGT(InVal.getValueType()) ?
12124 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
12125 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
12129 // Return the new vector
12130 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
12133 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
12134 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
12135 EVT ResultVT = EVE->getValueType(0);
12136 EVT VecEltVT = InVecVT.getVectorElementType();
12137 unsigned Align = OriginalLoad->getAlignment();
12138 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
12139 VecEltVT.getTypeForEVT(*DAG.getContext()));
12141 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
12146 SDValue NewPtr = OriginalLoad->getBasePtr();
12148 EVT PtrType = NewPtr.getValueType();
12149 MachinePointerInfo MPI;
12151 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
12152 int Elt = ConstEltNo->getZExtValue();
12153 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
12154 Offset = DAG.getConstant(PtrOff, DL, PtrType);
12155 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
12157 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
12158 Offset = DAG.getNode(
12159 ISD::MUL, DL, PtrType, Offset,
12160 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
12161 MPI = OriginalLoad->getPointerInfo();
12163 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
12165 // The replacement we need to do here is a little tricky: we need to
12166 // replace an extractelement of a load with a load.
12167 // Use ReplaceAllUsesOfValuesWith to do the replacement.
12168 // Note that this replacement assumes that the extractvalue is the only
12169 // use of the load; that's okay because we don't want to perform this
12170 // transformation in other cases anyway.
12173 if (ResultVT.bitsGT(VecEltVT)) {
12174 // If the result type of vextract is wider than the load, then issue an
12175 // extending load instead.
12176 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
12180 Load = DAG.getExtLoad(
12181 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
12182 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
12183 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
12184 Chain = Load.getValue(1);
12186 Load = DAG.getLoad(
12187 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
12188 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
12189 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
12190 Chain = Load.getValue(1);
12191 if (ResultVT.bitsLT(VecEltVT))
12192 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
12194 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
12196 WorklistRemover DeadNodes(*this);
12197 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
12198 SDValue To[] = { Load, Chain };
12199 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
12200 // Since we're explicitly calling ReplaceAllUses, add the new node to the
12201 // worklist explicitly as well.
12202 AddToWorklist(Load.getNode());
12203 AddUsersToWorklist(Load.getNode()); // Add users too
12204 // Make sure to revisit this node to clean it up; it will usually be dead.
12205 AddToWorklist(EVE);
12207 return SDValue(EVE, 0);
12210 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
12211 // (vextract (scalar_to_vector val, 0) -> val
12212 SDValue InVec = N->getOperand(0);
12213 EVT VT = InVec.getValueType();
12214 EVT NVT = N->getValueType(0);
12216 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
12217 // Check if the result type doesn't match the inserted element type. A
12218 // SCALAR_TO_VECTOR may truncate the inserted element and the
12219 // EXTRACT_VECTOR_ELT may widen the extracted vector.
12220 SDValue InOp = InVec.getOperand(0);
12221 if (InOp.getValueType() != NVT) {
12222 assert(InOp.getValueType().isInteger() && NVT.isInteger());
12223 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
12228 SDValue EltNo = N->getOperand(1);
12229 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
12231 // extract_vector_elt (build_vector x, y), 1 -> y
12233 InVec.getOpcode() == ISD::BUILD_VECTOR &&
12234 TLI.isTypeLegal(VT) &&
12235 (InVec.hasOneUse() ||
12236 TLI.aggressivelyPreferBuildVectorSources(VT))) {
12237 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
12238 EVT InEltVT = Elt.getValueType();
12240 // Sometimes build_vector's scalar input types do not match result type.
12241 if (NVT == InEltVT)
12244 // TODO: It may be useful to truncate if free if the build_vector implicitly
12248 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
12249 // We only perform this optimization before the op legalization phase because
12250 // we may introduce new vector instructions which are not backed by TD
12251 // patterns. For example on AVX, extracting elements from a wide vector
12252 // without using extract_subvector. However, if we can find an underlying
12253 // scalar value, then we can always use that.
12254 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
12255 int NumElem = VT.getVectorNumElements();
12256 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
12257 // Find the new index to extract from.
12258 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
12260 // Extracting an undef index is undef.
12262 return DAG.getUNDEF(NVT);
12264 // Select the right vector half to extract from.
12266 if (OrigElt < NumElem) {
12267 SVInVec = InVec->getOperand(0);
12269 SVInVec = InVec->getOperand(1);
12270 OrigElt -= NumElem;
12273 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
12274 SDValue InOp = SVInVec.getOperand(OrigElt);
12275 if (InOp.getValueType() != NVT) {
12276 assert(InOp.getValueType().isInteger() && NVT.isInteger());
12277 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
12283 // FIXME: We should handle recursing on other vector shuffles and
12284 // scalar_to_vector here as well.
12286 if (!LegalOperations) {
12287 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12288 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
12289 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
12293 bool BCNumEltsChanged = false;
12294 EVT ExtVT = VT.getVectorElementType();
12297 // If the result of load has to be truncated, then it's not necessarily
12299 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
12302 if (InVec.getOpcode() == ISD::BITCAST) {
12303 // Don't duplicate a load with other uses.
12304 if (!InVec.hasOneUse())
12307 EVT BCVT = InVec.getOperand(0).getValueType();
12308 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
12310 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
12311 BCNumEltsChanged = true;
12312 InVec = InVec.getOperand(0);
12313 ExtVT = BCVT.getVectorElementType();
12316 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
12317 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
12318 ISD::isNormalLoad(InVec.getNode()) &&
12319 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
12320 SDValue Index = N->getOperand(1);
12321 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
12322 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
12326 // Perform only after legalization to ensure build_vector / vector_shuffle
12327 // optimizations have already been done.
12328 if (!LegalOperations) return SDValue();
12330 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
12331 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
12332 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
12335 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12337 LoadSDNode *LN0 = nullptr;
12338 const ShuffleVectorSDNode *SVN = nullptr;
12339 if (ISD::isNormalLoad(InVec.getNode())) {
12340 LN0 = cast<LoadSDNode>(InVec);
12341 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
12342 InVec.getOperand(0).getValueType() == ExtVT &&
12343 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
12344 // Don't duplicate a load with other uses.
12345 if (!InVec.hasOneUse())
12348 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
12349 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
12350 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
12352 // (load $addr+1*size)
12354 // Don't duplicate a load with other uses.
12355 if (!InVec.hasOneUse())
12358 // If the bit convert changed the number of elements, it is unsafe
12359 // to examine the mask.
12360 if (BCNumEltsChanged)
12363 // Select the input vector, guarding against out of range extract vector.
12364 unsigned NumElems = VT.getVectorNumElements();
12365 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
12366 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
12368 if (InVec.getOpcode() == ISD::BITCAST) {
12369 // Don't duplicate a load with other uses.
12370 if (!InVec.hasOneUse())
12373 InVec = InVec.getOperand(0);
12375 if (ISD::isNormalLoad(InVec.getNode())) {
12376 LN0 = cast<LoadSDNode>(InVec);
12377 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12378 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12382 // Make sure we found a non-volatile load and the extractelement is
12384 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12387 // If Idx was -1 above, Elt is going to be -1, so just return undef.
12389 return DAG.getUNDEF(LVT);
12391 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12397 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12398 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12399 // We perform this optimization post type-legalization because
12400 // the type-legalizer often scalarizes integer-promoted vectors.
12401 // Performing this optimization before may create bit-casts which
12402 // will be type-legalized to complex code sequences.
12403 // We perform this optimization only before the operation legalizer because we
12404 // may introduce illegal operations.
12405 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12408 unsigned NumInScalars = N->getNumOperands();
12410 EVT VT = N->getValueType(0);
12412 // Check to see if this is a BUILD_VECTOR of a bunch of values
12413 // which come from any_extend or zero_extend nodes. If so, we can create
12414 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12415 // optimizations. We do not handle sign-extend because we can't fill the sign
12417 EVT SourceType = MVT::Other;
12418 bool AllAnyExt = true;
12420 for (unsigned i = 0; i != NumInScalars; ++i) {
12421 SDValue In = N->getOperand(i);
12422 // Ignore undef inputs.
12423 if (In.getOpcode() == ISD::UNDEF) continue;
12425 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
12426 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12428 // Abort if the element is not an extension.
12429 if (!ZeroExt && !AnyExt) {
12430 SourceType = MVT::Other;
12434 // The input is a ZeroExt or AnyExt. Check the original type.
12435 EVT InTy = In.getOperand(0).getValueType();
12437 // Check that all of the widened source types are the same.
12438 if (SourceType == MVT::Other)
12441 else if (InTy != SourceType) {
12442 // Multiple income types. Abort.
12443 SourceType = MVT::Other;
12447 // Check if all of the extends are ANY_EXTENDs.
12448 AllAnyExt &= AnyExt;
12451 // In order to have valid types, all of the inputs must be extended from the
12452 // same source type and all of the inputs must be any or zero extend.
12453 // Scalar sizes must be a power of two.
12454 EVT OutScalarTy = VT.getScalarType();
12455 bool ValidTypes = SourceType != MVT::Other &&
12456 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12457 isPowerOf2_32(SourceType.getSizeInBits());
12459 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12460 // turn into a single shuffle instruction.
12464 bool isLE = DAG.getDataLayout().isLittleEndian();
12465 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12466 assert(ElemRatio > 1 && "Invalid element size ratio");
12467 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12468 DAG.getConstant(0, SDLoc(N), SourceType);
12470 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12471 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12473 // Populate the new build_vector
12474 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12475 SDValue Cast = N->getOperand(i);
12476 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12477 Cast.getOpcode() == ISD::ZERO_EXTEND ||
12478 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
12480 if (Cast.getOpcode() == ISD::UNDEF)
12481 In = DAG.getUNDEF(SourceType);
12483 In = Cast->getOperand(0);
12484 unsigned Index = isLE ? (i * ElemRatio) :
12485 (i * ElemRatio + (ElemRatio - 1));
12487 assert(Index < Ops.size() && "Invalid index");
12491 // The type of the new BUILD_VECTOR node.
12492 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12493 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12494 "Invalid vector size");
12495 // Check if the new vector type is legal.
12496 if (!isTypeLegal(VecVT)) return SDValue();
12498 // Make the new BUILD_VECTOR.
12499 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
12501 // The new BUILD_VECTOR node has the potential to be further optimized.
12502 AddToWorklist(BV.getNode());
12503 // Bitcast to the desired type.
12504 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12507 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12508 EVT VT = N->getValueType(0);
12510 unsigned NumInScalars = N->getNumOperands();
12513 EVT SrcVT = MVT::Other;
12514 unsigned Opcode = ISD::DELETED_NODE;
12515 unsigned NumDefs = 0;
12517 for (unsigned i = 0; i != NumInScalars; ++i) {
12518 SDValue In = N->getOperand(i);
12519 unsigned Opc = In.getOpcode();
12521 if (Opc == ISD::UNDEF)
12524 // If all scalar values are floats and converted from integers.
12525 if (Opcode == ISD::DELETED_NODE &&
12526 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12533 EVT InVT = In.getOperand(0).getValueType();
12535 // If all scalar values are typed differently, bail out. It's chosen to
12536 // simplify BUILD_VECTOR of integer types.
12537 if (SrcVT == MVT::Other)
12544 // If the vector has just one element defined, it's not worth to fold it into
12545 // a vectorized one.
12549 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12550 && "Should only handle conversion from integer to float.");
12551 assert(SrcVT != MVT::Other && "Cannot determine source type!");
12553 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12555 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12558 // Just because the floating-point vector type is legal does not necessarily
12559 // mean that the corresponding integer vector type is.
12560 if (!isTypeLegal(NVT))
12563 SmallVector<SDValue, 8> Opnds;
12564 for (unsigned i = 0; i != NumInScalars; ++i) {
12565 SDValue In = N->getOperand(i);
12567 if (In.getOpcode() == ISD::UNDEF)
12568 Opnds.push_back(DAG.getUNDEF(SrcVT));
12570 Opnds.push_back(In.getOperand(0));
12572 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
12573 AddToWorklist(BV.getNode());
12575 return DAG.getNode(Opcode, dl, VT, BV);
12578 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12579 unsigned NumInScalars = N->getNumOperands();
12581 EVT VT = N->getValueType(0);
12583 // A vector built entirely of undefs is undef.
12584 if (ISD::allOperandsUndef(N))
12585 return DAG.getUNDEF(VT);
12587 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12590 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12593 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12594 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12595 // at most two distinct vectors, turn this into a shuffle node.
12597 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12598 if (!isTypeLegal(VT))
12601 // May only combine to shuffle after legalize if shuffle is legal.
12602 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12605 SDValue VecIn1, VecIn2;
12606 bool UsesZeroVector = false;
12607 for (unsigned i = 0; i != NumInScalars; ++i) {
12608 SDValue Op = N->getOperand(i);
12609 // Ignore undef inputs.
12610 if (Op.getOpcode() == ISD::UNDEF) continue;
12612 // See if we can combine this build_vector into a blend with a zero vector.
12613 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12614 UsesZeroVector = true;
12618 // If this input is something other than a EXTRACT_VECTOR_ELT with a
12619 // constant index, bail out.
12620 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12621 !isa<ConstantSDNode>(Op.getOperand(1))) {
12622 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12626 // We allow up to two distinct input vectors.
12627 SDValue ExtractedFromVec = Op.getOperand(0);
12628 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12631 if (!VecIn1.getNode()) {
12632 VecIn1 = ExtractedFromVec;
12633 } else if (!VecIn2.getNode() && !UsesZeroVector) {
12634 VecIn2 = ExtractedFromVec;
12636 // Too many inputs.
12637 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12642 // If everything is good, we can make a shuffle operation.
12643 if (VecIn1.getNode()) {
12644 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12645 SmallVector<int, 8> Mask;
12646 for (unsigned i = 0; i != NumInScalars; ++i) {
12647 unsigned Opcode = N->getOperand(i).getOpcode();
12648 if (Opcode == ISD::UNDEF) {
12649 Mask.push_back(-1);
12653 // Operands can also be zero.
12654 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12655 assert(UsesZeroVector &&
12656 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12657 "Unexpected node found!");
12658 Mask.push_back(NumInScalars+i);
12662 // If extracting from the first vector, just use the index directly.
12663 SDValue Extract = N->getOperand(i);
12664 SDValue ExtVal = Extract.getOperand(1);
12665 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12666 if (Extract.getOperand(0) == VecIn1) {
12667 Mask.push_back(ExtIndex);
12671 // Otherwise, use InIdx + InputVecSize
12672 Mask.push_back(InNumElements + ExtIndex);
12675 // Avoid introducing illegal shuffles with zero.
12676 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12679 // We can't generate a shuffle node with mismatched input and output types.
12680 // Attempt to transform a single input vector to the correct type.
12681 if ((VT != VecIn1.getValueType())) {
12682 // If the input vector type has a different base type to the output
12683 // vector type, bail out.
12684 EVT VTElemType = VT.getVectorElementType();
12685 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12686 (VecIn2.getNode() &&
12687 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12690 // If the input vector is too small, widen it.
12691 // We only support widening of vectors which are half the size of the
12692 // output registers. For example XMM->YMM widening on X86 with AVX.
12693 EVT VecInT = VecIn1.getValueType();
12694 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12695 // If we only have one small input, widen it by adding undef values.
12696 if (!VecIn2.getNode())
12697 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12698 DAG.getUNDEF(VecIn1.getValueType()));
12699 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12700 // If we have two small inputs of the same type, try to concat them.
12701 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12702 VecIn2 = SDValue(nullptr, 0);
12705 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12706 // If the input vector is too large, try to split it.
12707 // We don't support having two input vectors that are too large.
12708 // If the zero vector was used, we can not split the vector,
12709 // since we'd need 3 inputs.
12710 if (UsesZeroVector || VecIn2.getNode())
12713 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12716 // Try to replace VecIn1 with two extract_subvectors
12717 // No need to update the masks, they should still be correct.
12718 VecIn2 = DAG.getNode(
12719 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12720 DAG.getConstant(VT.getVectorNumElements(), dl,
12721 TLI.getVectorIdxTy(DAG.getDataLayout())));
12722 VecIn1 = DAG.getNode(
12723 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12724 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12729 if (UsesZeroVector)
12730 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12731 DAG.getConstantFP(0.0, dl, VT);
12733 // If VecIn2 is unused then change it to undef.
12734 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12736 // Check that we were able to transform all incoming values to the same
12738 if (VecIn2.getValueType() != VecIn1.getValueType() ||
12739 VecIn1.getValueType() != VT)
12742 // Return the new VECTOR_SHUFFLE node.
12746 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12752 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12753 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12754 EVT OpVT = N->getOperand(0).getValueType();
12756 // If the operands are legal vectors, leave them alone.
12757 if (TLI.isTypeLegal(OpVT))
12761 EVT VT = N->getValueType(0);
12762 SmallVector<SDValue, 8> Ops;
12764 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12765 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12767 // Keep track of what we encounter.
12768 bool AnyInteger = false;
12769 bool AnyFP = false;
12770 for (const SDValue &Op : N->ops()) {
12771 if (ISD::BITCAST == Op.getOpcode() &&
12772 !Op.getOperand(0).getValueType().isVector())
12773 Ops.push_back(Op.getOperand(0));
12774 else if (ISD::UNDEF == Op.getOpcode())
12775 Ops.push_back(ScalarUndef);
12779 // Note whether we encounter an integer or floating point scalar.
12780 // If it's neither, bail out, it could be something weird like x86mmx.
12781 EVT LastOpVT = Ops.back().getValueType();
12782 if (LastOpVT.isFloatingPoint())
12784 else if (LastOpVT.isInteger())
12790 // If any of the operands is a floating point scalar bitcast to a vector,
12791 // use floating point types throughout, and bitcast everything.
12792 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12794 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12795 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12797 for (SDValue &Op : Ops) {
12798 if (Op.getValueType() == SVT)
12800 if (Op.getOpcode() == ISD::UNDEF)
12803 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12808 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12809 VT.getSizeInBits() / SVT.getSizeInBits());
12810 return DAG.getNode(ISD::BITCAST, DL, VT,
12811 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12814 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12815 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12816 // most two distinct vectors the same size as the result, attempt to turn this
12817 // into a legal shuffle.
12818 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12819 EVT VT = N->getValueType(0);
12820 EVT OpVT = N->getOperand(0).getValueType();
12821 int NumElts = VT.getVectorNumElements();
12822 int NumOpElts = OpVT.getVectorNumElements();
12824 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12825 SmallVector<int, 8> Mask;
12827 for (SDValue Op : N->ops()) {
12828 // Peek through any bitcast.
12829 while (Op.getOpcode() == ISD::BITCAST)
12830 Op = Op.getOperand(0);
12832 // UNDEF nodes convert to UNDEF shuffle mask values.
12833 if (Op.getOpcode() == ISD::UNDEF) {
12834 Mask.append((unsigned)NumOpElts, -1);
12838 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12841 // What vector are we extracting the subvector from and at what index?
12842 SDValue ExtVec = Op.getOperand(0);
12844 // We want the EVT of the original extraction to correctly scale the
12845 // extraction index.
12846 EVT ExtVT = ExtVec.getValueType();
12848 // Peek through any bitcast.
12849 while (ExtVec.getOpcode() == ISD::BITCAST)
12850 ExtVec = ExtVec.getOperand(0);
12852 // UNDEF nodes convert to UNDEF shuffle mask values.
12853 if (ExtVec.getOpcode() == ISD::UNDEF) {
12854 Mask.append((unsigned)NumOpElts, -1);
12858 if (!isa<ConstantSDNode>(Op.getOperand(1)))
12860 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12862 // Ensure that we are extracting a subvector from a vector the same
12863 // size as the result.
12864 if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12867 // Scale the subvector index to account for any bitcast.
12868 int NumExtElts = ExtVT.getVectorNumElements();
12869 if (0 == (NumExtElts % NumElts))
12870 ExtIdx /= (NumExtElts / NumElts);
12871 else if (0 == (NumElts % NumExtElts))
12872 ExtIdx *= (NumElts / NumExtElts);
12876 // At most we can reference 2 inputs in the final shuffle.
12877 if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) {
12879 for (int i = 0; i != NumOpElts; ++i)
12880 Mask.push_back(i + ExtIdx);
12881 } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) {
12883 for (int i = 0; i != NumOpElts; ++i)
12884 Mask.push_back(i + ExtIdx + NumElts);
12890 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
12893 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
12894 DAG.getBitcast(VT, SV1), Mask);
12897 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12898 // If we only have one input vector, we don't need to do any concatenation.
12899 if (N->getNumOperands() == 1)
12900 return N->getOperand(0);
12902 // Check if all of the operands are undefs.
12903 EVT VT = N->getValueType(0);
12904 if (ISD::allOperandsUndef(N))
12905 return DAG.getUNDEF(VT);
12907 // Optimize concat_vectors where all but the first of the vectors are undef.
12908 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12909 return Op.getOpcode() == ISD::UNDEF;
12911 SDValue In = N->getOperand(0);
12912 assert(In.getValueType().isVector() && "Must concat vectors");
12914 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12915 if (In->getOpcode() == ISD::BITCAST &&
12916 !In->getOperand(0)->getValueType(0).isVector()) {
12917 SDValue Scalar = In->getOperand(0);
12919 // If the bitcast type isn't legal, it might be a trunc of a legal type;
12920 // look through the trunc so we can still do the transform:
12921 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12922 if (Scalar->getOpcode() == ISD::TRUNCATE &&
12923 !TLI.isTypeLegal(Scalar.getValueType()) &&
12924 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12925 Scalar = Scalar->getOperand(0);
12927 EVT SclTy = Scalar->getValueType(0);
12929 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12932 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12933 VT.getSizeInBits() / SclTy.getSizeInBits());
12934 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12937 SDLoc dl = SDLoc(N);
12938 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12939 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12943 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12944 // We have already tested above for an UNDEF only concatenation.
12945 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12946 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12947 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12948 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12950 bool AllBuildVectorsOrUndefs =
12951 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12952 if (AllBuildVectorsOrUndefs) {
12953 SmallVector<SDValue, 8> Opnds;
12954 EVT SVT = VT.getScalarType();
12957 if (!SVT.isFloatingPoint()) {
12958 // If BUILD_VECTOR are from built from integer, they may have different
12959 // operand types. Get the smallest type and truncate all operands to it.
12960 bool FoundMinVT = false;
12961 for (const SDValue &Op : N->ops())
12962 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12963 EVT OpSVT = Op.getOperand(0)->getValueType(0);
12964 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12967 assert(FoundMinVT && "Concat vector type mismatch");
12970 for (const SDValue &Op : N->ops()) {
12971 EVT OpVT = Op.getValueType();
12972 unsigned NumElts = OpVT.getVectorNumElements();
12974 if (ISD::UNDEF == Op.getOpcode())
12975 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12977 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12978 if (SVT.isFloatingPoint()) {
12979 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12980 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12982 for (unsigned i = 0; i != NumElts; ++i)
12984 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12989 assert(VT.getVectorNumElements() == Opnds.size() &&
12990 "Concat vector type mismatch");
12991 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12994 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12995 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12998 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
12999 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
13000 if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
13003 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
13004 // nodes often generate nop CONCAT_VECTOR nodes.
13005 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
13006 // place the incoming vectors at the exact same location.
13007 SDValue SingleSource = SDValue();
13008 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
13010 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13011 SDValue Op = N->getOperand(i);
13013 if (Op.getOpcode() == ISD::UNDEF)
13016 // Check if this is the identity extract:
13017 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13020 // Find the single incoming vector for the extract_subvector.
13021 if (SingleSource.getNode()) {
13022 if (Op.getOperand(0) != SingleSource)
13025 SingleSource = Op.getOperand(0);
13027 // Check the source type is the same as the type of the result.
13028 // If not, this concat may extend the vector, so we can not
13029 // optimize it away.
13030 if (SingleSource.getValueType() != N->getValueType(0))
13034 unsigned IdentityIndex = i * PartNumElem;
13035 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13036 // The extract index must be constant.
13040 // Check that we are reading from the identity index.
13041 if (CS->getZExtValue() != IdentityIndex)
13045 if (SingleSource.getNode())
13046 return SingleSource;
13051 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
13052 EVT NVT = N->getValueType(0);
13053 SDValue V = N->getOperand(0);
13055 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
13057 // (extract_subvec (concat V1, V2, ...), i)
13060 // Only operand 0 is checked as 'concat' assumes all inputs of the same
13062 if (V->getOperand(0).getValueType() != NVT)
13064 unsigned Idx = N->getConstantOperandVal(1);
13065 unsigned NumElems = NVT.getVectorNumElements();
13066 assert((Idx % NumElems) == 0 &&
13067 "IDX in concat is not a multiple of the result vector length.");
13068 return V->getOperand(Idx / NumElems);
13072 if (V->getOpcode() == ISD::BITCAST)
13073 V = V.getOperand(0);
13075 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
13077 // Handle only simple case where vector being inserted and vector
13078 // being extracted are of same type, and are half size of larger vectors.
13079 EVT BigVT = V->getOperand(0).getValueType();
13080 EVT SmallVT = V->getOperand(1).getValueType();
13081 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
13084 // Only handle cases where both indexes are constants with the same type.
13085 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
13086 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
13088 if (InsIdx && ExtIdx &&
13089 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
13090 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
13092 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
13094 // indices are equal or bit offsets are equal => V1
13095 // otherwise => (extract_subvec V1, ExtIdx)
13096 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
13097 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
13098 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
13099 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
13100 DAG.getNode(ISD::BITCAST, dl,
13101 N->getOperand(0).getValueType(),
13102 V->getOperand(0)), N->getOperand(1));
13109 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
13110 SDValue V, SelectionDAG &DAG) {
13112 EVT VT = V.getValueType();
13114 switch (V.getOpcode()) {
13118 case ISD::CONCAT_VECTORS: {
13119 EVT OpVT = V->getOperand(0).getValueType();
13120 int OpSize = OpVT.getVectorNumElements();
13121 SmallBitVector OpUsedElements(OpSize, false);
13122 bool FoundSimplification = false;
13123 SmallVector<SDValue, 4> NewOps;
13124 NewOps.reserve(V->getNumOperands());
13125 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
13126 SDValue Op = V->getOperand(i);
13127 bool OpUsed = false;
13128 for (int j = 0; j < OpSize; ++j)
13129 if (UsedElements[i * OpSize + j]) {
13130 OpUsedElements[j] = true;
13134 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
13135 : DAG.getUNDEF(OpVT));
13136 FoundSimplification |= Op == NewOps.back();
13137 OpUsedElements.reset();
13139 if (FoundSimplification)
13140 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
13144 case ISD::INSERT_SUBVECTOR: {
13145 SDValue BaseV = V->getOperand(0);
13146 SDValue SubV = V->getOperand(1);
13147 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
13151 int SubSize = SubV.getValueType().getVectorNumElements();
13152 int Idx = IdxN->getZExtValue();
13153 bool SubVectorUsed = false;
13154 SmallBitVector SubUsedElements(SubSize, false);
13155 for (int i = 0; i < SubSize; ++i)
13156 if (UsedElements[i + Idx]) {
13157 SubVectorUsed = true;
13158 SubUsedElements[i] = true;
13159 UsedElements[i + Idx] = false;
13162 // Now recurse on both the base and sub vectors.
13163 SDValue SimplifiedSubV =
13165 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
13166 : DAG.getUNDEF(SubV.getValueType());
13167 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
13168 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
13169 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
13170 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
13176 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
13177 SDValue N1, SelectionDAG &DAG) {
13178 EVT VT = SVN->getValueType(0);
13179 int NumElts = VT.getVectorNumElements();
13180 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
13181 for (int M : SVN->getMask())
13182 if (M >= 0 && M < NumElts)
13183 N0UsedElements[M] = true;
13184 else if (M >= NumElts)
13185 N1UsedElements[M - NumElts] = true;
13187 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
13188 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
13189 if (S0 == N0 && S1 == N1)
13192 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
13195 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
13196 // or turn a shuffle of a single concat into simpler shuffle then concat.
13197 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
13198 EVT VT = N->getValueType(0);
13199 unsigned NumElts = VT.getVectorNumElements();
13201 SDValue N0 = N->getOperand(0);
13202 SDValue N1 = N->getOperand(1);
13203 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13205 SmallVector<SDValue, 4> Ops;
13206 EVT ConcatVT = N0.getOperand(0).getValueType();
13207 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
13208 unsigned NumConcats = NumElts / NumElemsPerConcat;
13210 // Special case: shuffle(concat(A,B)) can be more efficiently represented
13211 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
13212 // half vector elements.
13213 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
13214 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
13215 SVN->getMask().end(), [](int i) { return i == -1; })) {
13216 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
13217 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
13218 N1 = DAG.getUNDEF(ConcatVT);
13219 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
13222 // Look at every vector that's inserted. We're looking for exact
13223 // subvector-sized copies from a concatenated vector
13224 for (unsigned I = 0; I != NumConcats; ++I) {
13225 // Make sure we're dealing with a copy.
13226 unsigned Begin = I * NumElemsPerConcat;
13227 bool AllUndef = true, NoUndef = true;
13228 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
13229 if (SVN->getMaskElt(J) >= 0)
13236 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
13239 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
13240 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
13243 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
13244 if (FirstElt < N0.getNumOperands())
13245 Ops.push_back(N0.getOperand(FirstElt));
13247 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
13249 } else if (AllUndef) {
13250 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
13251 } else { // Mixed with general masks and undefs, can't do optimization.
13256 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
13259 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
13260 EVT VT = N->getValueType(0);
13261 unsigned NumElts = VT.getVectorNumElements();
13263 SDValue N0 = N->getOperand(0);
13264 SDValue N1 = N->getOperand(1);
13266 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
13268 // Canonicalize shuffle undef, undef -> undef
13269 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
13270 return DAG.getUNDEF(VT);
13272 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13274 // Canonicalize shuffle v, v -> v, undef
13276 SmallVector<int, 8> NewMask;
13277 for (unsigned i = 0; i != NumElts; ++i) {
13278 int Idx = SVN->getMaskElt(i);
13279 if (Idx >= (int)NumElts) Idx -= NumElts;
13280 NewMask.push_back(Idx);
13282 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
13286 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
13287 if (N0.getOpcode() == ISD::UNDEF) {
13288 SmallVector<int, 8> NewMask;
13289 for (unsigned i = 0; i != NumElts; ++i) {
13290 int Idx = SVN->getMaskElt(i);
13292 if (Idx >= (int)NumElts)
13295 Idx = -1; // remove reference to lhs
13297 NewMask.push_back(Idx);
13299 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
13303 // Remove references to rhs if it is undef
13304 if (N1.getOpcode() == ISD::UNDEF) {
13305 bool Changed = false;
13306 SmallVector<int, 8> NewMask;
13307 for (unsigned i = 0; i != NumElts; ++i) {
13308 int Idx = SVN->getMaskElt(i);
13309 if (Idx >= (int)NumElts) {
13313 NewMask.push_back(Idx);
13316 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
13319 // If it is a splat, check if the argument vector is another splat or a
13321 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
13322 SDNode *V = N0.getNode();
13324 // If this is a bit convert that changes the element type of the vector but
13325 // not the number of vector elements, look through it. Be careful not to
13326 // look though conversions that change things like v4f32 to v2f64.
13327 if (V->getOpcode() == ISD::BITCAST) {
13328 SDValue ConvInput = V->getOperand(0);
13329 if (ConvInput.getValueType().isVector() &&
13330 ConvInput.getValueType().getVectorNumElements() == NumElts)
13331 V = ConvInput.getNode();
13334 if (V->getOpcode() == ISD::BUILD_VECTOR) {
13335 assert(V->getNumOperands() == NumElts &&
13336 "BUILD_VECTOR has wrong number of operands");
13338 bool AllSame = true;
13339 for (unsigned i = 0; i != NumElts; ++i) {
13340 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
13341 Base = V->getOperand(i);
13345 // Splat of <u, u, u, u>, return <u, u, u, u>
13346 if (!Base.getNode())
13348 for (unsigned i = 0; i != NumElts; ++i) {
13349 if (V->getOperand(i) != Base) {
13354 // Splat of <x, x, x, x>, return <x, x, x, x>
13358 // Canonicalize any other splat as a build_vector.
13359 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
13360 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
13361 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
13362 V->getValueType(0), Ops);
13364 // We may have jumped through bitcasts, so the type of the
13365 // BUILD_VECTOR may not match the type of the shuffle.
13366 if (V->getValueType(0) != VT)
13367 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
13372 // There are various patterns used to build up a vector from smaller vectors,
13373 // subvectors, or elements. Scan chains of these and replace unused insertions
13374 // or components with undef.
13375 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13378 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13379 Level < AfterLegalizeVectorOps &&
13380 (N1.getOpcode() == ISD::UNDEF ||
13381 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13382 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13383 SDValue V = partitionShuffleOfConcats(N, DAG);
13389 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13390 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13391 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
13392 SmallVector<SDValue, 8> Ops;
13393 for (int M : SVN->getMask()) {
13394 SDValue Op = DAG.getUNDEF(VT.getScalarType());
13396 int Idx = M % NumElts;
13397 SDValue &S = (M < (int)NumElts ? N0 : N1);
13398 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
13399 Op = S.getOperand(Idx);
13400 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
13402 Op = S.getOperand(0);
13404 // Operand can't be combined - bail out.
13410 if (Ops.size() == VT.getVectorNumElements()) {
13411 // BUILD_VECTOR requires all inputs to be of the same type, find the
13412 // maximum type and extend them all.
13413 EVT SVT = VT.getScalarType();
13414 if (SVT.isInteger())
13415 for (SDValue &Op : Ops)
13416 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13417 if (SVT != VT.getScalarType())
13418 for (SDValue &Op : Ops)
13419 Op = TLI.isZExtFree(Op.getValueType(), SVT)
13420 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
13421 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
13422 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
13426 // If this shuffle only has a single input that is a bitcasted shuffle,
13427 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13428 // back to their original types.
13429 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13430 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
13431 TLI.isTypeLegal(VT)) {
13433 // Peek through the bitcast only if there is one user.
13435 while (BC0.getOpcode() == ISD::BITCAST) {
13436 if (!BC0.hasOneUse())
13438 BC0 = BC0.getOperand(0);
13441 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13443 return SmallVector<int, 8>(Mask.begin(), Mask.end());
13445 SmallVector<int, 8> NewMask;
13447 for (int s = 0; s != Scale; ++s)
13448 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13452 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13453 EVT SVT = VT.getScalarType();
13454 EVT InnerVT = BC0->getValueType(0);
13455 EVT InnerSVT = InnerVT.getScalarType();
13457 // Determine which shuffle works with the smaller scalar type.
13458 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13459 EVT ScaleSVT = ScaleVT.getScalarType();
13461 if (TLI.isTypeLegal(ScaleVT) &&
13462 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13463 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13465 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13466 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13468 // Scale the shuffle masks to the smaller scalar type.
13469 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13470 SmallVector<int, 8> InnerMask =
13471 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13472 SmallVector<int, 8> OuterMask =
13473 ScaleShuffleMask(SVN->getMask(), OuterScale);
13475 // Merge the shuffle masks.
13476 SmallVector<int, 8> NewMask;
13477 for (int M : OuterMask)
13478 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13480 // Test for shuffle mask legality over both commutations.
13481 SDValue SV0 = BC0->getOperand(0);
13482 SDValue SV1 = BC0->getOperand(1);
13483 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13485 std::swap(SV0, SV1);
13486 ShuffleVectorSDNode::commuteMask(NewMask);
13487 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13491 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
13492 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
13493 return DAG.getNode(
13494 ISD::BITCAST, SDLoc(N), VT,
13495 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13501 // Canonicalize shuffles according to rules:
13502 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13503 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13504 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13505 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13506 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
13507 TLI.isTypeLegal(VT)) {
13508 // The incoming shuffle must be of the same type as the result of the
13509 // current shuffle.
13510 assert(N1->getOperand(0).getValueType() == VT &&
13511 "Shuffle types don't match");
13513 SDValue SV0 = N1->getOperand(0);
13514 SDValue SV1 = N1->getOperand(1);
13515 bool HasSameOp0 = N0 == SV0;
13516 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
13517 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13518 // Commute the operands of this shuffle so that next rule
13520 return DAG.getCommutedVectorShuffle(*SVN);
13523 // Try to fold according to rules:
13524 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13525 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13526 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13527 // Don't try to fold shuffles with illegal type.
13528 // Only fold if this shuffle is the only user of the other shuffle.
13529 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13530 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13531 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13533 // The incoming shuffle must be of the same type as the result of the
13534 // current shuffle.
13535 assert(OtherSV->getOperand(0).getValueType() == VT &&
13536 "Shuffle types don't match");
13539 SmallVector<int, 4> Mask;
13540 // Compute the combined shuffle mask for a shuffle with SV0 as the first
13541 // operand, and SV1 as the second operand.
13542 for (unsigned i = 0; i != NumElts; ++i) {
13543 int Idx = SVN->getMaskElt(i);
13545 // Propagate Undef.
13546 Mask.push_back(Idx);
13550 SDValue CurrentVec;
13551 if (Idx < (int)NumElts) {
13552 // This shuffle index refers to the inner shuffle N0. Lookup the inner
13553 // shuffle mask to identify which vector is actually referenced.
13554 Idx = OtherSV->getMaskElt(Idx);
13556 // Propagate Undef.
13557 Mask.push_back(Idx);
13561 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13562 : OtherSV->getOperand(1);
13564 // This shuffle index references an element within N1.
13568 // Simple case where 'CurrentVec' is UNDEF.
13569 if (CurrentVec.getOpcode() == ISD::UNDEF) {
13570 Mask.push_back(-1);
13574 // Canonicalize the shuffle index. We don't know yet if CurrentVec
13575 // will be the first or second operand of the combined shuffle.
13576 Idx = Idx % NumElts;
13577 if (!SV0.getNode() || SV0 == CurrentVec) {
13578 // Ok. CurrentVec is the left hand side.
13579 // Update the mask accordingly.
13581 Mask.push_back(Idx);
13585 // Bail out if we cannot convert the shuffle pair into a single shuffle.
13586 if (SV1.getNode() && SV1 != CurrentVec)
13589 // Ok. CurrentVec is the right hand side.
13590 // Update the mask accordingly.
13592 Mask.push_back(Idx + NumElts);
13595 // Check if all indices in Mask are Undef. In case, propagate Undef.
13596 bool isUndefMask = true;
13597 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13598 isUndefMask &= Mask[i] < 0;
13601 return DAG.getUNDEF(VT);
13603 if (!SV0.getNode())
13604 SV0 = DAG.getUNDEF(VT);
13605 if (!SV1.getNode())
13606 SV1 = DAG.getUNDEF(VT);
13608 // Avoid introducing shuffles with illegal mask.
13609 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13610 ShuffleVectorSDNode::commuteMask(Mask);
13612 if (!TLI.isShuffleMaskLegal(Mask, VT))
13615 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13616 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13617 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13618 std::swap(SV0, SV1);
13621 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13622 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13623 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13624 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13630 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13631 SDValue InVal = N->getOperand(0);
13632 EVT VT = N->getValueType(0);
13634 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13635 // with a VECTOR_SHUFFLE.
13636 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13637 SDValue InVec = InVal->getOperand(0);
13638 SDValue EltNo = InVal->getOperand(1);
13640 // FIXME: We could support implicit truncation if the shuffle can be
13641 // scaled to a smaller vector scalar type.
13642 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13643 if (C0 && VT == InVec.getValueType() &&
13644 VT.getScalarType() == InVal.getValueType()) {
13645 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13646 int Elt = C0->getZExtValue();
13649 if (TLI.isShuffleMaskLegal(NewMask, VT))
13650 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13658 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13659 SDValue N0 = N->getOperand(0);
13660 SDValue N2 = N->getOperand(2);
13662 // If the input vector is a concatenation, and the insert replaces
13663 // one of the halves, we can optimize into a single concat_vectors.
13664 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13665 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13666 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13667 EVT VT = N->getValueType(0);
13669 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13670 // (concat_vectors Z, Y)
13672 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13673 N->getOperand(1), N0.getOperand(1));
13675 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13676 // (concat_vectors X, Z)
13677 if (InsIdx == VT.getVectorNumElements()/2)
13678 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13679 N0.getOperand(0), N->getOperand(1));
13685 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13686 SDValue N0 = N->getOperand(0);
13688 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13689 if (N0->getOpcode() == ISD::FP16_TO_FP)
13690 return N0->getOperand(0);
13695 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13696 SDValue N0 = N->getOperand(0);
13698 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13699 if (N0->getOpcode() == ISD::AND) {
13700 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13701 if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13702 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13710 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13711 /// with the destination vector and a zero vector.
13712 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13713 /// vector_shuffle V, Zero, <0, 4, 2, 4>
13714 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13715 EVT VT = N->getValueType(0);
13716 SDValue LHS = N->getOperand(0);
13717 SDValue RHS = N->getOperand(1);
13720 // Make sure we're not running after operation legalization where it
13721 // may have custom lowered the vector shuffles.
13722 if (LegalOperations)
13725 if (N->getOpcode() != ISD::AND)
13728 if (RHS.getOpcode() == ISD::BITCAST)
13729 RHS = RHS.getOperand(0);
13731 if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13734 EVT RVT = RHS.getValueType();
13735 unsigned NumElts = RHS.getNumOperands();
13737 // Attempt to create a valid clear mask, splitting the mask into
13738 // sub elements and checking to see if each is
13739 // all zeros or all ones - suitable for shuffle masking.
13740 auto BuildClearMask = [&](int Split) {
13741 int NumSubElts = NumElts * Split;
13742 int NumSubBits = RVT.getScalarSizeInBits() / Split;
13744 SmallVector<int, 8> Indices;
13745 for (int i = 0; i != NumSubElts; ++i) {
13746 int EltIdx = i / Split;
13747 int SubIdx = i % Split;
13748 SDValue Elt = RHS.getOperand(EltIdx);
13749 if (Elt.getOpcode() == ISD::UNDEF) {
13750 Indices.push_back(-1);
13755 if (isa<ConstantSDNode>(Elt))
13756 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13757 else if (isa<ConstantFPSDNode>(Elt))
13758 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13762 // Extract the sub element from the constant bit mask.
13763 if (DAG.getDataLayout().isBigEndian()) {
13764 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13766 Bits = Bits.lshr(SubIdx * NumSubBits);
13770 Bits = Bits.trunc(NumSubBits);
13772 if (Bits.isAllOnesValue())
13773 Indices.push_back(i);
13774 else if (Bits == 0)
13775 Indices.push_back(i + NumSubElts);
13780 // Let's see if the target supports this vector_shuffle.
13781 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13782 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13783 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13786 SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13787 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13788 DAG.getBitcast(ClearVT, LHS),
13789 Zero, &Indices[0]));
13792 // Determine maximum split level (byte level masking).
13794 if (RVT.getScalarSizeInBits() % 8 == 0)
13795 MaxSplit = RVT.getScalarSizeInBits() / 8;
13797 for (int Split = 1; Split <= MaxSplit; ++Split)
13798 if (RVT.getScalarSizeInBits() % Split == 0)
13799 if (SDValue S = BuildClearMask(Split))
13805 /// Visit a binary vector operation, like ADD.
13806 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13807 assert(N->getValueType(0).isVector() &&
13808 "SimplifyVBinOp only works on vectors!");
13810 SDValue LHS = N->getOperand(0);
13811 SDValue RHS = N->getOperand(1);
13812 SDValue Ops[] = {LHS, RHS};
13814 // See if we can constant fold the vector operation.
13815 if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
13816 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
13819 // Try to convert a constant mask AND into a shuffle clear mask.
13820 if (SDValue Shuffle = XformToShuffleWithZero(N))
13823 // Type legalization might introduce new shuffles in the DAG.
13824 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13825 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
13826 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13827 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13828 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13829 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13830 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13831 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13833 if (SVN0->getMask().equals(SVN1->getMask())) {
13834 EVT VT = N->getValueType(0);
13835 SDValue UndefVector = LHS.getOperand(1);
13836 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13837 LHS.getOperand(0), RHS.getOperand(0),
13839 AddUsersToWorklist(N);
13840 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13841 &SVN0->getMask()[0]);
13848 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13849 SDValue N1, SDValue N2){
13850 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13852 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13853 cast<CondCodeSDNode>(N0.getOperand(2))->get());
13855 // If we got a simplified select_cc node back from SimplifySelectCC, then
13856 // break it down into a new SETCC node, and a new SELECT node, and then return
13857 // the SELECT node, since we were called with a SELECT node.
13858 if (SCC.getNode()) {
13859 // Check to see if we got a select_cc back (to turn into setcc/select).
13860 // Otherwise, just return whatever node we got back, like fabs.
13861 if (SCC.getOpcode() == ISD::SELECT_CC) {
13862 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13864 SCC.getOperand(0), SCC.getOperand(1),
13865 SCC.getOperand(4));
13866 AddToWorklist(SETCC.getNode());
13867 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13868 SCC.getOperand(2), SCC.getOperand(3));
13876 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13877 /// being selected between, see if we can simplify the select. Callers of this
13878 /// should assume that TheSelect is deleted if this returns true. As such, they
13879 /// should return the appropriate thing (e.g. the node) back to the top-level of
13880 /// the DAG combiner loop to avoid it being looked at.
13881 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13884 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13885 // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13886 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13887 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13888 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13889 SDValue Sqrt = RHS;
13892 const ConstantFPSDNode *NegZero = nullptr;
13894 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13895 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13896 CmpLHS = TheSelect->getOperand(0);
13897 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13899 // SELECT or VSELECT
13900 SDValue Cmp = TheSelect->getOperand(0);
13901 if (Cmp.getOpcode() == ISD::SETCC) {
13902 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13903 CmpLHS = Cmp.getOperand(0);
13904 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13907 if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13908 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13909 CC == ISD::SETULT || CC == ISD::SETLT)) {
13910 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13911 CombineTo(TheSelect, Sqrt);
13916 // Cannot simplify select with vector condition
13917 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13919 // If this is a select from two identical things, try to pull the operation
13920 // through the select.
13921 if (LHS.getOpcode() != RHS.getOpcode() ||
13922 !LHS.hasOneUse() || !RHS.hasOneUse())
13925 // If this is a load and the token chain is identical, replace the select
13926 // of two loads with a load through a select of the address to load from.
13927 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13928 // constants have been dropped into the constant pool.
13929 if (LHS.getOpcode() == ISD::LOAD) {
13930 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13931 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13933 // Token chains must be identical.
13934 if (LHS.getOperand(0) != RHS.getOperand(0) ||
13935 // Do not let this transformation reduce the number of volatile loads.
13936 LLD->isVolatile() || RLD->isVolatile() ||
13937 // FIXME: If either is a pre/post inc/dec load,
13938 // we'd need to split out the address adjustment.
13939 LLD->isIndexed() || RLD->isIndexed() ||
13940 // If this is an EXTLOAD, the VT's must match.
13941 LLD->getMemoryVT() != RLD->getMemoryVT() ||
13942 // If this is an EXTLOAD, the kind of extension must match.
13943 (LLD->getExtensionType() != RLD->getExtensionType() &&
13944 // The only exception is if one of the extensions is anyext.
13945 LLD->getExtensionType() != ISD::EXTLOAD &&
13946 RLD->getExtensionType() != ISD::EXTLOAD) ||
13947 // FIXME: this discards src value information. This is
13948 // over-conservative. It would be beneficial to be able to remember
13949 // both potential memory locations. Since we are discarding
13950 // src value info, don't do the transformation if the memory
13951 // locations are not in the default address space.
13952 LLD->getPointerInfo().getAddrSpace() != 0 ||
13953 RLD->getPointerInfo().getAddrSpace() != 0 ||
13954 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13955 LLD->getBasePtr().getValueType()))
13958 // Check that the select condition doesn't reach either load. If so,
13959 // folding this will induce a cycle into the DAG. If not, this is safe to
13960 // xform, so create a select of the addresses.
13962 if (TheSelect->getOpcode() == ISD::SELECT) {
13963 SDNode *CondNode = TheSelect->getOperand(0).getNode();
13964 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13965 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13967 // The loads must not depend on one another.
13968 if (LLD->isPredecessorOf(RLD) ||
13969 RLD->isPredecessorOf(LLD))
13971 Addr = DAG.getSelect(SDLoc(TheSelect),
13972 LLD->getBasePtr().getValueType(),
13973 TheSelect->getOperand(0), LLD->getBasePtr(),
13974 RLD->getBasePtr());
13975 } else { // Otherwise SELECT_CC
13976 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13977 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13979 if ((LLD->hasAnyUseOfValue(1) &&
13980 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13981 (RLD->hasAnyUseOfValue(1) &&
13982 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13985 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13986 LLD->getBasePtr().getValueType(),
13987 TheSelect->getOperand(0),
13988 TheSelect->getOperand(1),
13989 LLD->getBasePtr(), RLD->getBasePtr(),
13990 TheSelect->getOperand(4));
13994 // It is safe to replace the two loads if they have different alignments,
13995 // but the new load must be the minimum (most restrictive) alignment of the
13997 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13998 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13999 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
14000 Load = DAG.getLoad(TheSelect->getValueType(0),
14002 // FIXME: Discards pointer and AA info.
14003 LLD->getChain(), Addr, MachinePointerInfo(),
14004 LLD->isVolatile(), LLD->isNonTemporal(),
14005 isInvariant, Alignment);
14007 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
14008 RLD->getExtensionType() : LLD->getExtensionType(),
14010 TheSelect->getValueType(0),
14011 // FIXME: Discards pointer and AA info.
14012 LLD->getChain(), Addr, MachinePointerInfo(),
14013 LLD->getMemoryVT(), LLD->isVolatile(),
14014 LLD->isNonTemporal(), isInvariant, Alignment);
14017 // Users of the select now use the result of the load.
14018 CombineTo(TheSelect, Load);
14020 // Users of the old loads now use the new load's chain. We know the
14021 // old-load value is dead now.
14022 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
14023 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
14030 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
14031 /// where 'cond' is the comparison specified by CC.
14032 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
14033 SDValue N2, SDValue N3,
14034 ISD::CondCode CC, bool NotExtCompare) {
14035 // (x ? y : y) -> y.
14036 if (N2 == N3) return N2;
14038 EVT VT = N2.getValueType();
14039 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
14040 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
14042 // Determine if the condition we're dealing with is constant
14043 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
14044 N0, N1, CC, DL, false);
14045 if (SCC.getNode()) AddToWorklist(SCC.getNode());
14047 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
14048 // fold select_cc true, x, y -> x
14049 // fold select_cc false, x, y -> y
14050 return !SCCC->isNullValue() ? N2 : N3;
14053 // Check to see if we can simplify the select into an fabs node
14054 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
14055 // Allow either -0.0 or 0.0
14056 if (CFP->isZero()) {
14057 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
14058 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
14059 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
14060 N2 == N3.getOperand(0))
14061 return DAG.getNode(ISD::FABS, DL, VT, N0);
14063 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
14064 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
14065 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
14066 N2.getOperand(0) == N3)
14067 return DAG.getNode(ISD::FABS, DL, VT, N3);
14071 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
14072 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
14073 // in it. This is a win when the constant is not otherwise available because
14074 // it replaces two constant pool loads with one. We only do this if the FP
14075 // type is known to be legal, because if it isn't, then we are before legalize
14076 // types an we want the other legalization to happen first (e.g. to avoid
14077 // messing with soft float) and if the ConstantFP is not legal, because if
14078 // it is legal, we may not need to store the FP constant in a constant pool.
14079 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
14080 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
14081 if (TLI.isTypeLegal(N2.getValueType()) &&
14082 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
14083 TargetLowering::Legal &&
14084 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
14085 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
14086 // If both constants have multiple uses, then we won't need to do an
14087 // extra load, they are likely around in registers for other users.
14088 (TV->hasOneUse() || FV->hasOneUse())) {
14089 Constant *Elts[] = {
14090 const_cast<ConstantFP*>(FV->getConstantFPValue()),
14091 const_cast<ConstantFP*>(TV->getConstantFPValue())
14093 Type *FPTy = Elts[0]->getType();
14094 const DataLayout &TD = DAG.getDataLayout();
14096 // Create a ConstantArray of the two constants.
14097 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
14099 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
14100 TD.getPrefTypeAlignment(FPTy));
14101 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
14103 // Get the offsets to the 0 and 1 element of the array so that we can
14104 // select between them.
14105 SDValue Zero = DAG.getIntPtrConstant(0, DL);
14106 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
14107 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
14109 SDValue Cond = DAG.getSetCC(DL,
14110 getSetCCResultType(N0.getValueType()),
14112 AddToWorklist(Cond.getNode());
14113 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
14115 AddToWorklist(CstOffset.getNode());
14116 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
14118 AddToWorklist(CPIdx.getNode());
14119 return DAG.getLoad(
14120 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
14121 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
14122 false, false, false, Alignment);
14126 // Check to see if we can perform the "gzip trick", transforming
14127 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
14128 if (isNullConstant(N3) && CC == ISD::SETLT &&
14129 (isNullConstant(N1) || // (a < 0) ? b : 0
14130 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0
14131 EVT XType = N0.getValueType();
14132 EVT AType = N2.getValueType();
14133 if (XType.bitsGE(AType)) {
14134 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
14135 // single-bit constant.
14136 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
14137 unsigned ShCtV = N2C->getAPIntValue().logBase2();
14138 ShCtV = XType.getSizeInBits() - ShCtV - 1;
14139 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
14140 getShiftAmountTy(N0.getValueType()));
14141 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
14143 AddToWorklist(Shift.getNode());
14145 if (XType.bitsGT(AType)) {
14146 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14147 AddToWorklist(Shift.getNode());
14150 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14153 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
14155 DAG.getConstant(XType.getSizeInBits() - 1,
14157 getShiftAmountTy(N0.getValueType())));
14158 AddToWorklist(Shift.getNode());
14160 if (XType.bitsGT(AType)) {
14161 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14162 AddToWorklist(Shift.getNode());
14165 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14169 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
14170 // where y is has a single bit set.
14171 // A plaintext description would be, we can turn the SELECT_CC into an AND
14172 // when the condition can be materialized as an all-ones register. Any
14173 // single bit-test can be materialized as an all-ones register with
14174 // shift-left and shift-right-arith.
14175 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
14176 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
14177 SDValue AndLHS = N0->getOperand(0);
14178 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
14179 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
14180 // Shift the tested bit over the sign bit.
14181 APInt AndMask = ConstAndRHS->getAPIntValue();
14183 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
14184 getShiftAmountTy(AndLHS.getValueType()));
14185 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
14187 // Now arithmetic right shift it all the way over, so the result is either
14188 // all-ones, or zero.
14190 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
14191 getShiftAmountTy(Shl.getValueType()));
14192 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
14194 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
14198 // fold select C, 16, 0 -> shl C, 4
14199 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
14200 TLI.getBooleanContents(N0.getValueType()) ==
14201 TargetLowering::ZeroOrOneBooleanContent) {
14203 // If the caller doesn't want us to simplify this into a zext of a compare,
14205 if (NotExtCompare && N2C->isOne())
14208 // Get a SetCC of the condition
14209 // NOTE: Don't create a SETCC if it's not legal on this target.
14210 if (!LegalOperations ||
14211 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
14213 // cast from setcc result type to select result type
14215 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
14217 if (N2.getValueType().bitsLT(SCC.getValueType()))
14218 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
14219 N2.getValueType());
14221 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14222 N2.getValueType(), SCC);
14224 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
14225 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14226 N2.getValueType(), SCC);
14229 AddToWorklist(SCC.getNode());
14230 AddToWorklist(Temp.getNode());
14235 // shl setcc result by log2 n2c
14236 return DAG.getNode(
14237 ISD::SHL, DL, N2.getValueType(), Temp,
14238 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
14239 getShiftAmountTy(Temp.getValueType())));
14243 // Check to see if this is an integer abs.
14244 // select_cc setg[te] X, 0, X, -X ->
14245 // select_cc setgt X, -1, X, -X ->
14246 // select_cc setl[te] X, 0, -X, X ->
14247 // select_cc setlt X, 1, -X, X ->
14248 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
14250 ConstantSDNode *SubC = nullptr;
14251 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
14252 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
14253 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
14254 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
14255 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
14256 (N1C->isOne() && CC == ISD::SETLT)) &&
14257 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
14258 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
14260 EVT XType = N0.getValueType();
14261 if (SubC && SubC->isNullValue() && XType.isInteger()) {
14263 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
14265 DAG.getConstant(XType.getSizeInBits() - 1, DL,
14266 getShiftAmountTy(N0.getValueType())));
14267 SDValue Add = DAG.getNode(ISD::ADD, DL,
14269 AddToWorklist(Shift.getNode());
14270 AddToWorklist(Add.getNode());
14271 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
14278 /// This is a stub for TargetLowering::SimplifySetCC.
14279 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
14280 SDValue N1, ISD::CondCode Cond,
14281 SDLoc DL, bool foldBooleans) {
14282 TargetLowering::DAGCombinerInfo
14283 DagCombineInfo(DAG, Level, false, this);
14284 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
14287 /// Given an ISD::SDIV node expressing a divide by constant, return
14288 /// a DAG expression to select that will generate the same value by multiplying
14289 /// by a magic number.
14290 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14291 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
14292 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14296 // Avoid division by zero.
14297 if (C->isNullValue())
14300 std::vector<SDNode*> Built;
14302 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14304 for (SDNode *N : Built)
14309 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
14310 /// DAG expression that will generate the same value by right shifting.
14311 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
14312 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14316 // Avoid division by zero.
14317 if (C->isNullValue())
14320 std::vector<SDNode *> Built;
14321 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
14323 for (SDNode *N : Built)
14328 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
14329 /// expression that will generate the same value by multiplying by a magic
14331 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14332 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
14333 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14337 // Avoid division by zero.
14338 if (C->isNullValue())
14341 std::vector<SDNode*> Built;
14343 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14345 for (SDNode *N : Built)
14350 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
14351 if (Level >= AfterLegalizeDAG)
14354 // Expose the DAG combiner to the target combiner implementations.
14355 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14357 unsigned Iterations = 0;
14358 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
14360 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14361 // For the reciprocal, we need to find the zero of the function:
14362 // F(X) = A X - 1 [which has a zero at X = 1/A]
14364 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
14365 // does not require additional intermediate precision]
14366 EVT VT = Op.getValueType();
14368 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
14370 AddToWorklist(Est.getNode());
14372 // Newton iterations: Est = Est + Est (1 - Arg * Est)
14373 for (unsigned i = 0; i < Iterations; ++i) {
14374 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14375 AddToWorklist(NewEst.getNode());
14377 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14378 AddToWorklist(NewEst.getNode());
14380 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14381 AddToWorklist(NewEst.getNode());
14383 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14384 AddToWorklist(Est.getNode());
14393 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14394 /// For the reciprocal sqrt, we need to find the zero of the function:
14395 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14397 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14398 /// As a result, we precompute A/2 prior to the iteration loop.
14399 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
14400 unsigned Iterations,
14401 SDNodeFlags *Flags) {
14402 EVT VT = Arg.getValueType();
14404 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14406 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14407 // this entire sequence requires only one FP constant.
14408 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14409 AddToWorklist(HalfArg.getNode());
14411 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14412 AddToWorklist(HalfArg.getNode());
14414 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14415 for (unsigned i = 0; i < Iterations; ++i) {
14416 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14417 AddToWorklist(NewEst.getNode());
14419 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14420 AddToWorklist(NewEst.getNode());
14422 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14423 AddToWorklist(NewEst.getNode());
14425 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14426 AddToWorklist(Est.getNode());
14431 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14432 /// For the reciprocal sqrt, we need to find the zero of the function:
14433 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14435 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14436 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
14437 unsigned Iterations,
14438 SDNodeFlags *Flags) {
14439 EVT VT = Arg.getValueType();
14441 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
14442 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
14444 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
14445 for (unsigned i = 0; i < Iterations; ++i) {
14446 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
14447 AddToWorklist(HalfEst.getNode());
14449 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14450 AddToWorklist(Est.getNode());
14452 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14453 AddToWorklist(Est.getNode());
14455 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags);
14456 AddToWorklist(Est.getNode());
14458 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags);
14459 AddToWorklist(Est.getNode());
14464 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14465 if (Level >= AfterLegalizeDAG)
14468 // Expose the DAG combiner to the target combiner implementations.
14469 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14470 unsigned Iterations = 0;
14471 bool UseOneConstNR = false;
14472 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
14473 AddToWorklist(Est.getNode());
14475 Est = UseOneConstNR ?
14476 BuildRsqrtNROneConst(Op, Est, Iterations, Flags) :
14477 BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags);
14485 /// Return true if base is a frame index, which is known not to alias with
14486 /// anything but itself. Provides base object and offset as results.
14487 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14488 const GlobalValue *&GV, const void *&CV) {
14489 // Assume it is a primitive operation.
14490 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14492 // If it's an adding a simple constant then integrate the offset.
14493 if (Base.getOpcode() == ISD::ADD) {
14494 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14495 Base = Base.getOperand(0);
14496 Offset += C->getZExtValue();
14500 // Return the underlying GlobalValue, and update the Offset. Return false
14501 // for GlobalAddressSDNode since the same GlobalAddress may be represented
14502 // by multiple nodes with different offsets.
14503 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14504 GV = G->getGlobal();
14505 Offset += G->getOffset();
14509 // Return the underlying Constant value, and update the Offset. Return false
14510 // for ConstantSDNodes since the same constant pool entry may be represented
14511 // by multiple nodes with different offsets.
14512 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14513 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14514 : (const void *)C->getConstVal();
14515 Offset += C->getOffset();
14518 // If it's any of the following then it can't alias with anything but itself.
14519 return isa<FrameIndexSDNode>(Base);
14522 /// Return true if there is any possibility that the two addresses overlap.
14523 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14524 // If they are the same then they must be aliases.
14525 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14527 // If they are both volatile then they cannot be reordered.
14528 if (Op0->isVolatile() && Op1->isVolatile()) return true;
14530 // If one operation reads from invariant memory, and the other may store, they
14531 // cannot alias. These should really be checking the equivalent of mayWrite,
14532 // but it only matters for memory nodes other than load /store.
14533 if (Op0->isInvariant() && Op1->writeMem())
14536 if (Op1->isInvariant() && Op0->writeMem())
14539 // Gather base node and offset information.
14540 SDValue Base1, Base2;
14541 int64_t Offset1, Offset2;
14542 const GlobalValue *GV1, *GV2;
14543 const void *CV1, *CV2;
14544 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14545 Base1, Offset1, GV1, CV1);
14546 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14547 Base2, Offset2, GV2, CV2);
14549 // If they have a same base address then check to see if they overlap.
14550 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14551 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14552 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14554 // It is possible for different frame indices to alias each other, mostly
14555 // when tail call optimization reuses return address slots for arguments.
14556 // To catch this case, look up the actual index of frame indices to compute
14557 // the real alias relationship.
14558 if (isFrameIndex1 && isFrameIndex2) {
14559 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14560 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14561 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14562 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14563 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14566 // Otherwise, if we know what the bases are, and they aren't identical, then
14567 // we know they cannot alias.
14568 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14571 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14572 // compared to the size and offset of the access, we may be able to prove they
14573 // do not alias. This check is conservative for now to catch cases created by
14574 // splitting vector types.
14575 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14576 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14577 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14578 Op1->getMemoryVT().getSizeInBits() >> 3) &&
14579 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14580 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14581 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14583 // There is no overlap between these relatively aligned accesses of similar
14584 // size, return no alias.
14585 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14586 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14590 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14592 : DAG.getSubtarget().useAA();
14594 if (CombinerAAOnlyFunc.getNumOccurrences() &&
14595 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14599 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14600 // Use alias analysis information.
14601 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14602 Op1->getSrcValueOffset());
14603 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14604 Op0->getSrcValueOffset() - MinOffset;
14605 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14606 Op1->getSrcValueOffset() - MinOffset;
14607 AliasResult AAResult =
14608 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14609 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14610 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14611 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14612 if (AAResult == NoAlias)
14616 // Otherwise we have to assume they alias.
14620 /// Walk up chain skipping non-aliasing memory nodes,
14621 /// looking for aliasing nodes and adding them to the Aliases vector.
14622 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14623 SmallVectorImpl<SDValue> &Aliases) {
14624 SmallVector<SDValue, 8> Chains; // List of chains to visit.
14625 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
14627 // Get alias information for node.
14628 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14631 Chains.push_back(OriginalChain);
14632 unsigned Depth = 0;
14634 // Look at each chain and determine if it is an alias. If so, add it to the
14635 // aliases list. If not, then continue up the chain looking for the next
14637 while (!Chains.empty()) {
14638 SDValue Chain = Chains.pop_back_val();
14640 // For TokenFactor nodes, look at each operand and only continue up the
14641 // chain until we reach the depth limit.
14643 // FIXME: The depth check could be made to return the last non-aliasing
14644 // chain we found before we hit a tokenfactor rather than the original
14646 if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
14648 Aliases.push_back(OriginalChain);
14652 // Don't bother if we've been before.
14653 if (!Visited.insert(Chain.getNode()).second)
14656 switch (Chain.getOpcode()) {
14657 case ISD::EntryToken:
14658 // Entry token is ideal chain operand, but handled in FindBetterChain.
14663 // Get alias information for Chain.
14664 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14665 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14667 // If chain is alias then stop here.
14668 if (!(IsLoad && IsOpLoad) &&
14669 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14670 Aliases.push_back(Chain);
14672 // Look further up the chain.
14673 Chains.push_back(Chain.getOperand(0));
14679 case ISD::TokenFactor:
14680 // We have to check each of the operands of the token factor for "small"
14681 // token factors, so we queue them up. Adding the operands to the queue
14682 // (stack) in reverse order maintains the original order and increases the
14683 // likelihood that getNode will find a matching token factor (CSE.)
14684 if (Chain.getNumOperands() > 16) {
14685 Aliases.push_back(Chain);
14688 for (unsigned n = Chain.getNumOperands(); n;)
14689 Chains.push_back(Chain.getOperand(--n));
14694 // For all other instructions we will just have to take what we can get.
14695 Aliases.push_back(Chain);
14700 // We need to be careful here to also search for aliases through the
14701 // value operand of a store, etc. Consider the following situation:
14703 // L1 = load Token1, %52
14704 // S1 = store Token1, L1, %51
14705 // L2 = load Token1, %52+8
14706 // S2 = store Token1, L2, %51+8
14707 // Token2 = Token(S1, S2)
14708 // L3 = load Token2, %53
14709 // S3 = store Token2, L3, %52
14710 // L4 = load Token2, %53+8
14711 // S4 = store Token2, L4, %52+8
14712 // If we search for aliases of S3 (which loads address %52), and we look
14713 // only through the chain, then we'll miss the trivial dependence on L1
14714 // (which also loads from %52). We then might change all loads and
14715 // stores to use Token1 as their chain operand, which could result in
14716 // copying %53 into %52 before copying %52 into %51 (which should
14719 // The problem is, however, that searching for such data dependencies
14720 // can become expensive, and the cost is not directly related to the
14721 // chain depth. Instead, we'll rule out such configurations here by
14722 // insisting that we've visited all chain users (except for users
14723 // of the original chain, which is not necessary). When doing this,
14724 // we need to look through nodes we don't care about (otherwise, things
14725 // like register copies will interfere with trivial cases).
14727 SmallVector<const SDNode *, 16> Worklist;
14728 for (const SDNode *N : Visited)
14729 if (N != OriginalChain.getNode())
14730 Worklist.push_back(N);
14732 while (!Worklist.empty()) {
14733 const SDNode *M = Worklist.pop_back_val();
14735 // We have already visited M, and want to make sure we've visited any uses
14736 // of M that we care about. For uses that we've not visisted, and don't
14737 // care about, queue them to the worklist.
14739 for (SDNode::use_iterator UI = M->use_begin(),
14740 UIE = M->use_end(); UI != UIE; ++UI)
14741 if (UI.getUse().getValueType() == MVT::Other &&
14742 Visited.insert(*UI).second) {
14743 if (isa<MemSDNode>(*UI)) {
14744 // We've not visited this use, and we care about it (it could have an
14745 // ordering dependency with the original node).
14747 Aliases.push_back(OriginalChain);
14751 // We've not visited this use, but we don't care about it. Mark it as
14752 // visited and enqueue it to the worklist.
14753 Worklist.push_back(*UI);
14758 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14759 /// (aliasing node.)
14760 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14761 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
14763 // Accumulate all the aliases to this node.
14764 GatherAllAliases(N, OldChain, Aliases);
14766 // If no operands then chain to entry token.
14767 if (Aliases.size() == 0)
14768 return DAG.getEntryNode();
14770 // If a single operand then chain to it. We don't need to revisit it.
14771 if (Aliases.size() == 1)
14774 // Construct a custom tailored token factor.
14775 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14778 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) {
14779 // This holds the base pointer, index, and the offset in bytes from the base
14781 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
14783 // We must have a base and an offset.
14784 if (!BasePtr.Base.getNode())
14787 // Do not handle stores to undef base pointers.
14788 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
14791 SmallVector<StoreSDNode *, 8> ChainedStores;
14792 ChainedStores.push_back(St);
14794 // Walk up the chain and look for nodes with offsets from the same
14795 // base pointer. Stop when reaching an instruction with a different kind
14796 // or instruction which has a different base pointer.
14797 StoreSDNode *Index = St;
14799 // If the chain has more than one use, then we can't reorder the mem ops.
14800 if (Index != St && !SDValue(Index, 0)->hasOneUse())
14803 if (Index->isVolatile() || Index->isIndexed())
14806 // Find the base pointer and offset for this memory node.
14807 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
14809 // Check that the base pointer is the same as the original one.
14810 if (!Ptr.equalBaseIndex(BasePtr))
14813 // Find the next memory operand in the chain. If the next operand in the
14814 // chain is a store then move up and continue the scan with the next
14815 // memory operand. If the next operand is a load save it and use alias
14816 // information to check if it interferes with anything.
14817 SDNode *NextInChain = Index->getChain().getNode();
14819 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
14820 // We found a store node. Use it for the next iteration.
14821 ChainedStores.push_back(STn);
14824 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
14825 NextInChain = Ldn->getChain().getNode();
14834 bool MadeChange = false;
14835 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
14837 for (StoreSDNode *ChainedStore : ChainedStores) {
14838 SDValue Chain = ChainedStore->getChain();
14839 SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
14841 if (Chain != BetterChain) {
14843 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
14847 // Do all replacements after finding the replacements to make to avoid making
14848 // the chains more complicated by introducing new TokenFactors.
14849 for (auto Replacement : BetterChains)
14850 replaceStoreChain(Replacement.first, Replacement.second);
14855 /// This is the entry point for the file.
14856 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14857 CodeGenOpt::Level OptLevel) {
14858 /// This is the main entry point to this class.
14859 DAGCombiner(*this, AA, OptLevel).Run(Level);