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 // (and (and x, 0), y) shouldn't either.
3104 if (!N0C && N1C->isNullValue()) {
3108 if (N0.getOpcode() == ISD::AND) {
3109 auto* N01 = N0.getOperand(1).getNode();
3110 auto* N01C = dyn_cast<ConstantSDNode>(N01);
3111 if (N01C && N01C->isNullValue()) {
3117 if (N0C && N1C && !N1C->isOpaque())
3118 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3119 // canonicalize constant to RHS
3120 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3121 !isConstantIntBuildVectorOrConstantInt(N1))
3122 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3123 // fold (and x, -1) -> x
3124 if (isAllOnesConstant(N1))
3126 // if (and x, c) is known to be zero, return 0
3127 unsigned BitWidth = VT.getScalarType().getSizeInBits();
3128 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3129 APInt::getAllOnesValue(BitWidth)))
3130 return DAG.getConstant(0, SDLoc(N), VT);
3132 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3134 // fold (and (or x, C), D) -> D if (C & D) == D
3135 if (N1C && N0.getOpcode() == ISD::OR)
3136 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3137 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3139 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3140 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3141 SDValue N0Op0 = N0.getOperand(0);
3142 APInt Mask = ~N1C->getAPIntValue();
3143 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
3144 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3145 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3146 N0.getValueType(), N0Op0);
3148 // Replace uses of the AND with uses of the Zero extend node.
3151 // We actually want to replace all uses of the any_extend with the
3152 // zero_extend, to avoid duplicating things. This will later cause this
3153 // AND to be folded.
3154 CombineTo(N0.getNode(), Zext);
3155 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3158 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3159 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3160 // already be zero by virtue of the width of the base type of the load.
3162 // the 'X' node here can either be nothing or an extract_vector_elt to catch
3164 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3165 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
3166 N0.getOpcode() == ISD::LOAD) {
3167 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3168 N0 : N0.getOperand(0) );
3170 // Get the constant (if applicable) the zero'th operand is being ANDed with.
3171 // This can be a pure constant or a vector splat, in which case we treat the
3172 // vector as a scalar and use the splat value.
3173 APInt Constant = APInt::getNullValue(1);
3174 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3175 Constant = C->getAPIntValue();
3176 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3177 APInt SplatValue, SplatUndef;
3178 unsigned SplatBitSize;
3180 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3181 SplatBitSize, HasAnyUndefs);
3183 // Undef bits can contribute to a possible optimisation if set, so
3185 SplatValue |= SplatUndef;
3187 // The splat value may be something like "0x00FFFFFF", which means 0 for
3188 // the first vector value and FF for the rest, repeating. We need a mask
3189 // that will apply equally to all members of the vector, so AND all the
3190 // lanes of the constant together.
3191 EVT VT = Vector->getValueType(0);
3192 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3194 // If the splat value has been compressed to a bitlength lower
3195 // than the size of the vector lane, we need to re-expand it to
3197 if (BitWidth > SplatBitSize)
3198 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3199 SplatBitSize < BitWidth;
3200 SplatBitSize = SplatBitSize * 2)
3201 SplatValue |= SplatValue.shl(SplatBitSize);
3203 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3204 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3205 if (SplatBitSize % BitWidth == 0) {
3206 Constant = APInt::getAllOnesValue(BitWidth);
3207 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3208 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3213 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3214 // actually legal and isn't going to get expanded, else this is a false
3216 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3217 Load->getValueType(0),
3218 Load->getMemoryVT());
3220 // Resize the constant to the same size as the original memory access before
3221 // extension. If it is still the AllOnesValue then this AND is completely
3224 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3227 switch (Load->getExtensionType()) {
3228 default: B = false; break;
3229 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3231 case ISD::NON_EXTLOAD: B = true; break;
3234 if (B && Constant.isAllOnesValue()) {
3235 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3236 // preserve semantics once we get rid of the AND.
3237 SDValue NewLoad(Load, 0);
3238 if (Load->getExtensionType() == ISD::EXTLOAD) {
3239 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3240 Load->getValueType(0), SDLoc(Load),
3241 Load->getChain(), Load->getBasePtr(),
3242 Load->getOffset(), Load->getMemoryVT(),
3243 Load->getMemOperand());
3244 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3245 if (Load->getNumValues() == 3) {
3246 // PRE/POST_INC loads have 3 values.
3247 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3248 NewLoad.getValue(2) };
3249 CombineTo(Load, To, 3, true);
3251 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3255 // Fold the AND away, taking care not to fold to the old load node if we
3257 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3259 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3263 // fold (and (load x), 255) -> (zextload x, i8)
3264 // fold (and (extload x, i16), 255) -> (zextload x, i8)
3265 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3266 if (N1C && (N0.getOpcode() == ISD::LOAD ||
3267 (N0.getOpcode() == ISD::ANY_EXTEND &&
3268 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3269 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3270 LoadSDNode *LN0 = HasAnyExt
3271 ? cast<LoadSDNode>(N0.getOperand(0))
3272 : cast<LoadSDNode>(N0);
3273 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3274 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3275 auto NarrowLoad = false;
3276 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3277 EVT ExtVT, LoadedVT;
3278 if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3282 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3283 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3284 LN0->getMemOperand());
3286 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3287 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3289 EVT PtrType = LN0->getOperand(1).getValueType();
3291 unsigned Alignment = LN0->getAlignment();
3292 SDValue NewPtr = LN0->getBasePtr();
3294 // For big endian targets, we need to add an offset to the pointer
3295 // to load the correct bytes. For little endian systems, we merely
3296 // need to read fewer bytes from the same pointer.
3297 if (DAG.getDataLayout().isBigEndian()) {
3298 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3299 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3300 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3302 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3303 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3304 Alignment = MinAlign(Alignment, PtrOff);
3307 AddToWorklist(NewPtr.getNode());
3310 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3311 LN0->getChain(), NewPtr,
3312 LN0->getPointerInfo(),
3313 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3314 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3316 CombineTo(LN0, Load, Load.getValue(1));
3317 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3323 if (SDValue Combined = visitANDLike(N0, N1, N))
3326 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3327 if (N0.getOpcode() == N1.getOpcode())
3328 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3331 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3332 // fold (and (sra)) -> (and (srl)) when possible.
3333 if (!VT.isVector() &&
3334 SimplifyDemandedBits(SDValue(N, 0)))
3335 return SDValue(N, 0);
3337 // fold (zext_inreg (extload x)) -> (zextload x)
3338 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3339 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3340 EVT MemVT = LN0->getMemoryVT();
3341 // If we zero all the possible extended bits, then we can turn this into
3342 // a zextload if we are running before legalize or the operation is legal.
3343 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3344 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3345 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3346 ((!LegalOperations && !LN0->isVolatile()) ||
3347 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3348 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3349 LN0->getChain(), LN0->getBasePtr(),
3350 MemVT, LN0->getMemOperand());
3352 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3353 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3356 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3357 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3359 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3360 EVT MemVT = LN0->getMemoryVT();
3361 // If we zero all the possible extended bits, then we can turn this into
3362 // a zextload if we are running before legalize or the operation is legal.
3363 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3364 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3365 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3366 ((!LegalOperations && !LN0->isVolatile()) ||
3367 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3368 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3369 LN0->getChain(), LN0->getBasePtr(),
3370 MemVT, LN0->getMemOperand());
3372 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3373 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3376 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3377 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3378 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3379 N0.getOperand(1), false);
3380 if (BSwap.getNode())
3387 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3388 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3389 bool DemandHighBits) {
3390 if (!LegalOperations)
3393 EVT VT = N->getValueType(0);
3394 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3396 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3399 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3400 bool LookPassAnd0 = false;
3401 bool LookPassAnd1 = false;
3402 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3404 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3406 if (N0.getOpcode() == ISD::AND) {
3407 if (!N0.getNode()->hasOneUse())
3409 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3410 if (!N01C || N01C->getZExtValue() != 0xFF00)
3412 N0 = N0.getOperand(0);
3413 LookPassAnd0 = true;
3416 if (N1.getOpcode() == ISD::AND) {
3417 if (!N1.getNode()->hasOneUse())
3419 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3420 if (!N11C || N11C->getZExtValue() != 0xFF)
3422 N1 = N1.getOperand(0);
3423 LookPassAnd1 = true;
3426 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3428 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3430 if (!N0.getNode()->hasOneUse() ||
3431 !N1.getNode()->hasOneUse())
3434 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3435 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3438 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3441 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3442 SDValue N00 = N0->getOperand(0);
3443 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3444 if (!N00.getNode()->hasOneUse())
3446 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3447 if (!N001C || N001C->getZExtValue() != 0xFF)
3449 N00 = N00.getOperand(0);
3450 LookPassAnd0 = true;
3453 SDValue N10 = N1->getOperand(0);
3454 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3455 if (!N10.getNode()->hasOneUse())
3457 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3458 if (!N101C || N101C->getZExtValue() != 0xFF00)
3460 N10 = N10.getOperand(0);
3461 LookPassAnd1 = true;
3467 // Make sure everything beyond the low halfword gets set to zero since the SRL
3468 // 16 will clear the top bits.
3469 unsigned OpSizeInBits = VT.getSizeInBits();
3470 if (DemandHighBits && OpSizeInBits > 16) {
3471 // If the left-shift isn't masked out then the only way this is a bswap is
3472 // if all bits beyond the low 8 are 0. In that case the entire pattern
3473 // reduces to a left shift anyway: leave it for other parts of the combiner.
3477 // However, if the right shift isn't masked out then it might be because
3478 // it's not needed. See if we can spot that too.
3479 if (!LookPassAnd1 &&
3480 !DAG.MaskedValueIsZero(
3481 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3485 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3486 if (OpSizeInBits > 16) {
3488 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3489 DAG.getConstant(OpSizeInBits - 16, DL,
3490 getShiftAmountTy(VT)));
3495 /// Return true if the specified node is an element that makes up a 32-bit
3496 /// packed halfword byteswap.
3497 /// ((x & 0x000000ff) << 8) |
3498 /// ((x & 0x0000ff00) >> 8) |
3499 /// ((x & 0x00ff0000) << 8) |
3500 /// ((x & 0xff000000) >> 8)
3501 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3502 if (!N.getNode()->hasOneUse())
3505 unsigned Opc = N.getOpcode();
3506 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3509 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3514 switch (N1C->getZExtValue()) {
3517 case 0xFF: Num = 0; break;
3518 case 0xFF00: Num = 1; break;
3519 case 0xFF0000: Num = 2; break;
3520 case 0xFF000000: Num = 3; break;
3523 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3524 SDValue N0 = N.getOperand(0);
3525 if (Opc == ISD::AND) {
3526 if (Num == 0 || Num == 2) {
3528 // (x >> 8) & 0xff0000
3529 if (N0.getOpcode() != ISD::SRL)
3531 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3532 if (!C || C->getZExtValue() != 8)
3535 // (x << 8) & 0xff00
3536 // (x << 8) & 0xff000000
3537 if (N0.getOpcode() != ISD::SHL)
3539 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3540 if (!C || C->getZExtValue() != 8)
3543 } else if (Opc == ISD::SHL) {
3545 // (x & 0xff0000) << 8
3546 if (Num != 0 && Num != 2)
3548 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3549 if (!C || C->getZExtValue() != 8)
3551 } else { // Opc == ISD::SRL
3552 // (x & 0xff00) >> 8
3553 // (x & 0xff000000) >> 8
3554 if (Num != 1 && Num != 3)
3556 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3557 if (!C || C->getZExtValue() != 8)
3564 Parts[Num] = N0.getOperand(0).getNode();
3568 /// Match a 32-bit packed halfword bswap. That is
3569 /// ((x & 0x000000ff) << 8) |
3570 /// ((x & 0x0000ff00) >> 8) |
3571 /// ((x & 0x00ff0000) << 8) |
3572 /// ((x & 0xff000000) >> 8)
3573 /// => (rotl (bswap x), 16)
3574 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3575 if (!LegalOperations)
3578 EVT VT = N->getValueType(0);
3581 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3585 // (or (or (and), (and)), (or (and), (and)))
3586 // (or (or (or (and), (and)), (and)), (and))
3587 if (N0.getOpcode() != ISD::OR)
3589 SDValue N00 = N0.getOperand(0);
3590 SDValue N01 = N0.getOperand(1);
3591 SDNode *Parts[4] = {};
3593 if (N1.getOpcode() == ISD::OR &&
3594 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3595 // (or (or (and), (and)), (or (and), (and)))
3596 SDValue N000 = N00.getOperand(0);
3597 if (!isBSwapHWordElement(N000, Parts))
3600 SDValue N001 = N00.getOperand(1);
3601 if (!isBSwapHWordElement(N001, Parts))
3603 SDValue N010 = N01.getOperand(0);
3604 if (!isBSwapHWordElement(N010, Parts))
3606 SDValue N011 = N01.getOperand(1);
3607 if (!isBSwapHWordElement(N011, Parts))
3610 // (or (or (or (and), (and)), (and)), (and))
3611 if (!isBSwapHWordElement(N1, Parts))
3613 if (!isBSwapHWordElement(N01, Parts))
3615 if (N00.getOpcode() != ISD::OR)
3617 SDValue N000 = N00.getOperand(0);
3618 if (!isBSwapHWordElement(N000, Parts))
3620 SDValue N001 = N00.getOperand(1);
3621 if (!isBSwapHWordElement(N001, Parts))
3625 // Make sure the parts are all coming from the same node.
3626 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3630 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3631 SDValue(Parts[0], 0));
3633 // Result of the bswap should be rotated by 16. If it's not legal, then
3634 // do (x << 16) | (x >> 16).
3635 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3636 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3637 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3638 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3639 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3640 return DAG.getNode(ISD::OR, DL, VT,
3641 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3642 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3645 /// This contains all DAGCombine rules which reduce two values combined by
3646 /// an Or operation to a single value \see visitANDLike().
3647 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3648 EVT VT = N1.getValueType();
3649 // fold (or x, undef) -> -1
3650 if (!LegalOperations &&
3651 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3652 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3653 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3654 SDLoc(LocReference), VT);
3656 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3657 SDValue LL, LR, RL, RR, CC0, CC1;
3658 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3659 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3660 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3662 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3663 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3664 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3665 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3666 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3667 LR.getValueType(), LL, RL);
3668 AddToWorklist(ORNode.getNode());
3669 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3671 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3672 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3673 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3674 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3675 LR.getValueType(), LL, RL);
3676 AddToWorklist(ANDNode.getNode());
3677 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3680 // canonicalize equivalent to ll == rl
3681 if (LL == RR && LR == RL) {
3682 Op1 = ISD::getSetCCSwappedOperands(Op1);
3685 if (LL == RL && LR == RR) {
3686 bool isInteger = LL.getValueType().isInteger();
3687 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3688 if (Result != ISD::SETCC_INVALID &&
3689 (!LegalOperations ||
3690 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3691 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3692 EVT CCVT = getSetCCResultType(LL.getValueType());
3693 if (N0.getValueType() == CCVT ||
3694 (!LegalOperations && N0.getValueType() == MVT::i1))
3695 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3701 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3702 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3703 // Don't increase # computations.
3704 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3705 // We can only do this xform if we know that bits from X that are set in C2
3706 // but not in C1 are already zero. Likewise for Y.
3707 if (const ConstantSDNode *N0O1C =
3708 getAsNonOpaqueConstant(N0.getOperand(1))) {
3709 if (const ConstantSDNode *N1O1C =
3710 getAsNonOpaqueConstant(N1.getOperand(1))) {
3711 // We can only do this xform if we know that bits from X that are set in
3712 // C2 but not in C1 are already zero. Likewise for Y.
3713 const APInt &LHSMask = N0O1C->getAPIntValue();
3714 const APInt &RHSMask = N1O1C->getAPIntValue();
3716 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3717 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3718 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3719 N0.getOperand(0), N1.getOperand(0));
3720 SDLoc DL(LocReference);
3721 return DAG.getNode(ISD::AND, DL, VT, X,
3722 DAG.getConstant(LHSMask | RHSMask, DL, VT));
3728 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3729 if (N0.getOpcode() == ISD::AND &&
3730 N1.getOpcode() == ISD::AND &&
3731 N0.getOperand(0) == N1.getOperand(0) &&
3732 // Don't increase # computations.
3733 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3734 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3735 N0.getOperand(1), N1.getOperand(1));
3736 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3742 SDValue DAGCombiner::visitOR(SDNode *N) {
3743 SDValue N0 = N->getOperand(0);
3744 SDValue N1 = N->getOperand(1);
3745 EVT VT = N1.getValueType();
3748 if (VT.isVector()) {
3749 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3752 // fold (or x, 0) -> x, vector edition
3753 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3755 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3758 // fold (or x, -1) -> -1, vector edition
3759 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3760 // do not return N0, because undef node may exist in N0
3761 return DAG.getConstant(
3762 APInt::getAllOnesValue(
3763 N0.getValueType().getScalarType().getSizeInBits()),
3764 SDLoc(N), N0.getValueType());
3765 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3766 // do not return N1, because undef node may exist in N1
3767 return DAG.getConstant(
3768 APInt::getAllOnesValue(
3769 N1.getValueType().getScalarType().getSizeInBits()),
3770 SDLoc(N), N1.getValueType());
3772 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3773 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3774 // Do this only if the resulting shuffle is legal.
3775 if (isa<ShuffleVectorSDNode>(N0) &&
3776 isa<ShuffleVectorSDNode>(N1) &&
3777 // Avoid folding a node with illegal type.
3778 TLI.isTypeLegal(VT) &&
3779 N0->getOperand(1) == N1->getOperand(1) &&
3780 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3781 bool CanFold = true;
3782 unsigned NumElts = VT.getVectorNumElements();
3783 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3784 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3785 // We construct two shuffle masks:
3786 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3787 // and N1 as the second operand.
3788 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3789 // and N0 as the second operand.
3790 // We do this because OR is commutable and therefore there might be
3791 // two ways to fold this node into a shuffle.
3792 SmallVector<int,4> Mask1;
3793 SmallVector<int,4> Mask2;
3795 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3796 int M0 = SV0->getMaskElt(i);
3797 int M1 = SV1->getMaskElt(i);
3799 // Both shuffle indexes are undef. Propagate Undef.
3800 if (M0 < 0 && M1 < 0) {
3801 Mask1.push_back(M0);
3802 Mask2.push_back(M0);
3806 if (M0 < 0 || M1 < 0 ||
3807 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3808 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3813 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3814 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3818 // Fold this sequence only if the resulting shuffle is 'legal'.
3819 if (TLI.isShuffleMaskLegal(Mask1, VT))
3820 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3821 N1->getOperand(0), &Mask1[0]);
3822 if (TLI.isShuffleMaskLegal(Mask2, VT))
3823 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3824 N0->getOperand(0), &Mask2[0]);
3829 // fold (or c1, c2) -> c1|c2
3830 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3831 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3832 if (N0C && N1C && !N1C->isOpaque())
3833 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3834 // canonicalize constant to RHS
3835 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3836 !isConstantIntBuildVectorOrConstantInt(N1))
3837 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3838 // fold (or x, 0) -> x
3839 if (isNullConstant(N1))
3841 // fold (or x, -1) -> -1
3842 if (isAllOnesConstant(N1))
3844 // fold (or x, c) -> c iff (x & ~c) == 0
3845 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3848 if (SDValue Combined = visitORLike(N0, N1, N))
3851 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3852 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3854 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3858 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3860 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3861 // iff (c1 & c2) == 0.
3862 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3863 isa<ConstantSDNode>(N0.getOperand(1))) {
3864 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3865 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3866 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3869 ISD::AND, SDLoc(N), VT,
3870 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3874 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3875 if (N0.getOpcode() == N1.getOpcode())
3876 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3879 // See if this is some rotate idiom.
3880 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3881 return SDValue(Rot, 0);
3883 // Simplify the operands using demanded-bits information.
3884 if (!VT.isVector() &&
3885 SimplifyDemandedBits(SDValue(N, 0)))
3886 return SDValue(N, 0);
3891 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3892 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3893 if (Op.getOpcode() == ISD::AND) {
3894 if (isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
3895 Mask = Op.getOperand(1);
3896 Op = Op.getOperand(0);
3902 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3910 // Return true if we can prove that, whenever Neg and Pos are both in the
3911 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that
3912 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3914 // (or (shift1 X, Neg), (shift2 X, Pos))
3916 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3917 // in direction shift1 by Neg. The range [0, EltSize) means that we only need
3918 // to consider shift amounts with defined behavior.
3919 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
3920 // If EltSize is a power of 2 then:
3922 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
3923 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
3925 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
3926 // for the stronger condition:
3928 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A]
3930 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
3931 // we can just replace Neg with Neg' for the rest of the function.
3933 // In other cases we check for the even stronger condition:
3935 // Neg == EltSize - Pos [B]
3937 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3938 // behavior if Pos == 0 (and consequently Neg == EltSize).
3940 // We could actually use [A] whenever EltSize is a power of 2, but the
3941 // only extra cases that it would match are those uninteresting ones
3942 // where Neg and Pos are never in range at the same time. E.g. for
3943 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3944 // as well as (sub 32, Pos), but:
3946 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3948 // always invokes undefined behavior for 32-bit X.
3950 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
3951 unsigned MaskLoBits = 0;
3952 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
3953 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
3954 if (NegC->getAPIntValue() == EltSize - 1) {
3955 Neg = Neg.getOperand(0);
3956 MaskLoBits = Log2_64(EltSize);
3961 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3962 if (Neg.getOpcode() != ISD::SUB)
3964 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
3967 SDValue NegOp1 = Neg.getOperand(1);
3969 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
3970 // Pos'. The truncation is redundant for the purpose of the equality.
3971 if (MaskLoBits && Pos.getOpcode() == ISD::AND)
3972 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3973 if (PosC->getAPIntValue() == EltSize - 1)
3974 Pos = Pos.getOperand(0);
3976 // The condition we need is now:
3978 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
3980 // If NegOp1 == Pos then we need:
3982 // EltSize & Mask == NegC & Mask
3984 // (because "x & Mask" is a truncation and distributes through subtraction).
3987 Width = NegC->getAPIntValue();
3989 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3990 // Then the condition we want to prove becomes:
3992 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
3994 // which, again because "x & Mask" is a truncation, becomes:
3996 // NegC & Mask == (EltSize - PosC) & Mask
3997 // EltSize & Mask == (NegC + PosC) & Mask
3998 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
3999 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4000 Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4006 // Now we just need to check that EltSize & Mask == Width & Mask.
4008 // EltSize & Mask is 0 since Mask is EltSize - 1.
4009 return Width.getLoBits(MaskLoBits) == 0;
4010 return Width == EltSize;
4013 // A subroutine of MatchRotate used once we have found an OR of two opposite
4014 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
4015 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4016 // former being preferred if supported. InnerPos and InnerNeg are Pos and
4017 // Neg with outer conversions stripped away.
4018 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4019 SDValue Neg, SDValue InnerPos,
4020 SDValue InnerNeg, unsigned PosOpcode,
4021 unsigned NegOpcode, SDLoc DL) {
4022 // fold (or (shl x, (*ext y)),
4023 // (srl x, (*ext (sub 32, y)))) ->
4024 // (rotl x, y) or (rotr x, (sub 32, y))
4026 // fold (or (shl x, (*ext (sub 32, y))),
4027 // (srl x, (*ext y))) ->
4028 // (rotr x, y) or (rotl x, (sub 32, y))
4029 EVT VT = Shifted.getValueType();
4030 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4031 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4032 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4033 HasPos ? Pos : Neg).getNode();
4039 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
4040 // idioms for rotate, and if the target supports rotation instructions, generate
4042 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
4043 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
4044 EVT VT = LHS.getValueType();
4045 if (!TLI.isTypeLegal(VT)) return nullptr;
4047 // The target must have at least one rotate flavor.
4048 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4049 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4050 if (!HasROTL && !HasROTR) return nullptr;
4052 // Match "(X shl/srl V1) & V2" where V2 may not be present.
4053 SDValue LHSShift; // The shift.
4054 SDValue LHSMask; // AND value if any.
4055 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4056 return nullptr; // Not part of a rotate.
4058 SDValue RHSShift; // The shift.
4059 SDValue RHSMask; // AND value if any.
4060 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4061 return nullptr; // Not part of a rotate.
4063 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4064 return nullptr; // Not shifting the same value.
4066 if (LHSShift.getOpcode() == RHSShift.getOpcode())
4067 return nullptr; // Shifts must disagree.
4069 // Canonicalize shl to left side in a shl/srl pair.
4070 if (RHSShift.getOpcode() == ISD::SHL) {
4071 std::swap(LHS, RHS);
4072 std::swap(LHSShift, RHSShift);
4073 std::swap(LHSMask, RHSMask);
4076 unsigned EltSizeInBits = VT.getScalarSizeInBits();
4077 SDValue LHSShiftArg = LHSShift.getOperand(0);
4078 SDValue LHSShiftAmt = LHSShift.getOperand(1);
4079 SDValue RHSShiftArg = RHSShift.getOperand(0);
4080 SDValue RHSShiftAmt = RHSShift.getOperand(1);
4082 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4083 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4084 if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4085 uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4086 uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4087 if ((LShVal + RShVal) != EltSizeInBits)
4090 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4091 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4093 // If there is an AND of either shifted operand, apply it to the result.
4094 if (LHSMask.getNode() || RHSMask.getNode()) {
4095 APInt AllBits = APInt::getAllOnesValue(EltSizeInBits);
4096 SDValue Mask = DAG.getConstant(AllBits, DL, VT);
4098 if (LHSMask.getNode()) {
4099 APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4100 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4101 DAG.getNode(ISD::OR, DL, VT, LHSMask,
4102 DAG.getConstant(RHSBits, DL, VT)));
4104 if (RHSMask.getNode()) {
4105 APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4106 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4107 DAG.getNode(ISD::OR, DL, VT, RHSMask,
4108 DAG.getConstant(LHSBits, DL, VT)));
4111 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4114 return Rot.getNode();
4117 // If there is a mask here, and we have a variable shift, we can't be sure
4118 // that we're masking out the right stuff.
4119 if (LHSMask.getNode() || RHSMask.getNode())
4122 // If the shift amount is sign/zext/any-extended just peel it off.
4123 SDValue LExtOp0 = LHSShiftAmt;
4124 SDValue RExtOp0 = RHSShiftAmt;
4125 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4126 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4127 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4128 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4129 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4130 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4131 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4132 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4133 LExtOp0 = LHSShiftAmt.getOperand(0);
4134 RExtOp0 = RHSShiftAmt.getOperand(0);
4137 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4138 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4142 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4143 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4150 SDValue DAGCombiner::visitXOR(SDNode *N) {
4151 SDValue N0 = N->getOperand(0);
4152 SDValue N1 = N->getOperand(1);
4153 EVT VT = N0.getValueType();
4156 if (VT.isVector()) {
4157 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4160 // fold (xor x, 0) -> x, vector edition
4161 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4163 if (ISD::isBuildVectorAllZeros(N1.getNode()))
4167 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4168 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
4169 return DAG.getConstant(0, SDLoc(N), VT);
4170 // fold (xor x, undef) -> undef
4171 if (N0.getOpcode() == ISD::UNDEF)
4173 if (N1.getOpcode() == ISD::UNDEF)
4175 // fold (xor c1, c2) -> c1^c2
4176 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4177 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4179 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4180 // canonicalize constant to RHS
4181 if (isConstantIntBuildVectorOrConstantInt(N0) &&
4182 !isConstantIntBuildVectorOrConstantInt(N1))
4183 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4184 // fold (xor x, 0) -> x
4185 if (isNullConstant(N1))
4188 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4191 // fold !(x cc y) -> (x !cc y)
4192 SDValue LHS, RHS, CC;
4193 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4194 bool isInt = LHS.getValueType().isInteger();
4195 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4198 if (!LegalOperations ||
4199 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4200 switch (N0.getOpcode()) {
4202 llvm_unreachable("Unhandled SetCC Equivalent!");
4204 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4205 case ISD::SELECT_CC:
4206 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4207 N0.getOperand(3), NotCC);
4212 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4213 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4214 N0.getNode()->hasOneUse() &&
4215 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4216 SDValue V = N0.getOperand(0);
4218 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4219 DAG.getConstant(1, DL, V.getValueType()));
4220 AddToWorklist(V.getNode());
4221 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4224 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4225 if (isOneConstant(N1) && VT == MVT::i1 &&
4226 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4227 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4228 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4229 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4230 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4231 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4232 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4233 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4236 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4237 if (isAllOnesConstant(N1) &&
4238 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4239 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4240 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4241 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4242 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4243 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4244 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4245 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4248 // fold (xor (and x, y), y) -> (and (not x), y)
4249 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4250 N0->getOperand(1) == N1) {
4251 SDValue X = N0->getOperand(0);
4252 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4253 AddToWorklist(NotX.getNode());
4254 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4256 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4257 if (N1C && N0.getOpcode() == ISD::XOR) {
4258 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4260 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4261 DAG.getConstant(N1C->getAPIntValue() ^
4262 N00C->getAPIntValue(), DL, VT));
4264 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4266 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4267 DAG.getConstant(N1C->getAPIntValue() ^
4268 N01C->getAPIntValue(), DL, VT));
4271 // fold (xor x, x) -> 0
4273 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4275 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4276 // Here is a concrete example of this equivalence:
4278 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
4279 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4283 // i16 ~1 == 0b1111111111111110
4284 // i16 rol(~1, 14) == 0b1011111111111111
4286 // Some additional tips to help conceptualize this transform:
4287 // - Try to see the operation as placing a single zero in a value of all ones.
4288 // - There exists no value for x which would allow the result to contain zero.
4289 // - Values of x larger than the bitwidth are undefined and do not require a
4290 // consistent result.
4291 // - Pushing the zero left requires shifting one bits in from the right.
4292 // A rotate left of ~1 is a nice way of achieving the desired result.
4293 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4294 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4296 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4300 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4301 if (N0.getOpcode() == N1.getOpcode())
4302 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4305 // Simplify the expression using non-local knowledge.
4306 if (!VT.isVector() &&
4307 SimplifyDemandedBits(SDValue(N, 0)))
4308 return SDValue(N, 0);
4313 /// Handle transforms common to the three shifts, when the shift amount is a
4315 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4316 SDNode *LHS = N->getOperand(0).getNode();
4317 if (!LHS->hasOneUse()) return SDValue();
4319 // We want to pull some binops through shifts, so that we have (and (shift))
4320 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4321 // thing happens with address calculations, so it's important to canonicalize
4323 bool HighBitSet = false; // Can we transform this if the high bit is set?
4325 switch (LHS->getOpcode()) {
4326 default: return SDValue();
4329 HighBitSet = false; // We can only transform sra if the high bit is clear.
4332 HighBitSet = true; // We can only transform sra if the high bit is set.
4335 if (N->getOpcode() != ISD::SHL)
4336 return SDValue(); // only shl(add) not sr[al](add).
4337 HighBitSet = false; // We can only transform sra if the high bit is clear.
4341 // We require the RHS of the binop to be a constant and not opaque as well.
4342 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4343 if (!BinOpCst) return SDValue();
4345 // FIXME: disable this unless the input to the binop is a shift by a constant.
4346 // If it is not a shift, it pessimizes some common cases like:
4348 // void foo(int *X, int i) { X[i & 1235] = 1; }
4349 // int bar(int *X, int i) { return X[i & 255]; }
4350 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4351 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4352 BinOpLHSVal->getOpcode() != ISD::SRA &&
4353 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4354 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4357 EVT VT = N->getValueType(0);
4359 // If this is a signed shift right, and the high bit is modified by the
4360 // logical operation, do not perform the transformation. The highBitSet
4361 // boolean indicates the value of the high bit of the constant which would
4362 // cause it to be modified for this operation.
4363 if (N->getOpcode() == ISD::SRA) {
4364 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4365 if (BinOpRHSSignSet != HighBitSet)
4369 if (!TLI.isDesirableToCommuteWithShift(LHS))
4372 // Fold the constants, shifting the binop RHS by the shift amount.
4373 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4375 LHS->getOperand(1), N->getOperand(1));
4376 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4378 // Create the new shift.
4379 SDValue NewShift = DAG.getNode(N->getOpcode(),
4380 SDLoc(LHS->getOperand(0)),
4381 VT, LHS->getOperand(0), N->getOperand(1));
4383 // Create the new binop.
4384 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4387 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4388 assert(N->getOpcode() == ISD::TRUNCATE);
4389 assert(N->getOperand(0).getOpcode() == ISD::AND);
4391 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4392 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4393 SDValue N01 = N->getOperand(0).getOperand(1);
4395 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4396 if (!N01C->isOpaque()) {
4397 EVT TruncVT = N->getValueType(0);
4398 SDValue N00 = N->getOperand(0).getOperand(0);
4399 APInt TruncC = N01C->getAPIntValue();
4400 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4403 return DAG.getNode(ISD::AND, DL, TruncVT,
4404 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4405 DAG.getConstant(TruncC, DL, TruncVT));
4413 SDValue DAGCombiner::visitRotate(SDNode *N) {
4414 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4415 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4416 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4417 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4418 if (NewOp1.getNode())
4419 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4420 N->getOperand(0), NewOp1);
4425 SDValue DAGCombiner::visitSHL(SDNode *N) {
4426 SDValue N0 = N->getOperand(0);
4427 SDValue N1 = N->getOperand(1);
4428 EVT VT = N0.getValueType();
4429 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4432 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4433 if (VT.isVector()) {
4434 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4437 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4438 // If setcc produces all-one true value then:
4439 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4440 if (N1CV && N1CV->isConstant()) {
4441 if (N0.getOpcode() == ISD::AND) {
4442 SDValue N00 = N0->getOperand(0);
4443 SDValue N01 = N0->getOperand(1);
4444 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4446 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4447 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4448 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4449 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4451 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4454 N1C = isConstOrConstSplat(N1);
4459 // fold (shl c1, c2) -> c1<<c2
4460 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4461 if (N0C && N1C && !N1C->isOpaque())
4462 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4463 // fold (shl 0, x) -> 0
4464 if (isNullConstant(N0))
4466 // fold (shl x, c >= size(x)) -> undef
4467 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4468 return DAG.getUNDEF(VT);
4469 // fold (shl x, 0) -> x
4470 if (N1C && N1C->isNullValue())
4472 // fold (shl undef, x) -> 0
4473 if (N0.getOpcode() == ISD::UNDEF)
4474 return DAG.getConstant(0, SDLoc(N), VT);
4475 // if (shl x, c) is known to be zero, return 0
4476 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4477 APInt::getAllOnesValue(OpSizeInBits)))
4478 return DAG.getConstant(0, SDLoc(N), VT);
4479 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4480 if (N1.getOpcode() == ISD::TRUNCATE &&
4481 N1.getOperand(0).getOpcode() == ISD::AND) {
4482 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4483 if (NewOp1.getNode())
4484 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4487 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4488 return SDValue(N, 0);
4490 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4491 if (N1C && N0.getOpcode() == ISD::SHL) {
4492 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4493 uint64_t c1 = N0C1->getZExtValue();
4494 uint64_t c2 = N1C->getZExtValue();
4496 if (c1 + c2 >= OpSizeInBits)
4497 return DAG.getConstant(0, DL, VT);
4498 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4499 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4503 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4504 // For this to be valid, the second form must not preserve any of the bits
4505 // that are shifted out by the inner shift in the first form. This means
4506 // the outer shift size must be >= the number of bits added by the ext.
4507 // As a corollary, we don't care what kind of ext it is.
4508 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4509 N0.getOpcode() == ISD::ANY_EXTEND ||
4510 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4511 N0.getOperand(0).getOpcode() == ISD::SHL) {
4512 SDValue N0Op0 = N0.getOperand(0);
4513 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4514 uint64_t c1 = N0Op0C1->getZExtValue();
4515 uint64_t c2 = N1C->getZExtValue();
4516 EVT InnerShiftVT = N0Op0.getValueType();
4517 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4518 if (c2 >= OpSizeInBits - InnerShiftSize) {
4520 if (c1 + c2 >= OpSizeInBits)
4521 return DAG.getConstant(0, DL, VT);
4522 return DAG.getNode(ISD::SHL, DL, VT,
4523 DAG.getNode(N0.getOpcode(), DL, VT,
4524 N0Op0->getOperand(0)),
4525 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4530 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4531 // Only fold this if the inner zext has no other uses to avoid increasing
4532 // the total number of instructions.
4533 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4534 N0.getOperand(0).getOpcode() == ISD::SRL) {
4535 SDValue N0Op0 = N0.getOperand(0);
4536 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4537 uint64_t c1 = N0Op0C1->getZExtValue();
4538 if (c1 < VT.getScalarSizeInBits()) {
4539 uint64_t c2 = N1C->getZExtValue();
4541 SDValue NewOp0 = N0.getOperand(0);
4542 EVT CountVT = NewOp0.getOperand(1).getValueType();
4544 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4546 DAG.getConstant(c2, DL, CountVT));
4547 AddToWorklist(NewSHL.getNode());
4548 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4554 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
4555 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2
4556 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4557 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4558 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4559 uint64_t C1 = N0C1->getZExtValue();
4560 uint64_t C2 = N1C->getZExtValue();
4563 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4564 DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4565 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4566 DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4570 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4571 // (and (srl x, (sub c1, c2), MASK)
4572 // Only fold this if the inner shift has no other uses -- if it does, folding
4573 // this will increase the total number of instructions.
4574 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4575 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4576 uint64_t c1 = N0C1->getZExtValue();
4577 if (c1 < OpSizeInBits) {
4578 uint64_t c2 = N1C->getZExtValue();
4579 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4582 Mask = Mask.shl(c2 - c1);
4584 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4585 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4587 Mask = Mask.lshr(c1 - c2);
4589 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4590 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4593 return DAG.getNode(ISD::AND, DL, VT, Shift,
4594 DAG.getConstant(Mask, DL, VT));
4598 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4599 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4600 unsigned BitSize = VT.getScalarSizeInBits();
4602 SDValue HiBitsMask =
4603 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4604 BitSize - N1C->getZExtValue()),
4606 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4610 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4611 // Variant of version done on multiply, except mul by a power of 2 is turned
4614 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4615 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4616 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4617 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4618 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4619 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4622 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4623 if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4624 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4625 if (SDValue Folded =
4626 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4627 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4631 if (N1C && !N1C->isOpaque())
4632 if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4638 SDValue DAGCombiner::visitSRA(SDNode *N) {
4639 SDValue N0 = N->getOperand(0);
4640 SDValue N1 = N->getOperand(1);
4641 EVT VT = N0.getValueType();
4642 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4645 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4646 if (VT.isVector()) {
4647 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4650 N1C = isConstOrConstSplat(N1);
4653 // fold (sra c1, c2) -> (sra c1, c2)
4654 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4655 if (N0C && N1C && !N1C->isOpaque())
4656 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4657 // fold (sra 0, x) -> 0
4658 if (isNullConstant(N0))
4660 // fold (sra -1, x) -> -1
4661 if (isAllOnesConstant(N0))
4663 // fold (sra x, (setge c, size(x))) -> undef
4664 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4665 return DAG.getUNDEF(VT);
4666 // fold (sra x, 0) -> x
4667 if (N1C && N1C->isNullValue())
4669 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4671 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4672 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4673 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4675 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4676 ExtVT, VT.getVectorNumElements());
4677 if ((!LegalOperations ||
4678 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4679 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4680 N0.getOperand(0), DAG.getValueType(ExtVT));
4683 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4684 if (N1C && N0.getOpcode() == ISD::SRA) {
4685 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4686 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4687 if (Sum >= OpSizeInBits)
4688 Sum = OpSizeInBits - 1;
4690 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4691 DAG.getConstant(Sum, DL, N1.getValueType()));
4695 // fold (sra (shl X, m), (sub result_size, n))
4696 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4697 // result_size - n != m.
4698 // If truncate is free for the target sext(shl) is likely to result in better
4700 if (N0.getOpcode() == ISD::SHL && N1C) {
4701 // Get the two constanst of the shifts, CN0 = m, CN = n.
4702 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4704 LLVMContext &Ctx = *DAG.getContext();
4705 // Determine what the truncate's result bitsize and type would be.
4706 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4709 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4711 // Determine the residual right-shift amount.
4712 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4714 // If the shift is not a no-op (in which case this should be just a sign
4715 // extend already), the truncated to type is legal, sign_extend is legal
4716 // on that type, and the truncate to that type is both legal and free,
4717 // perform the transform.
4718 if ((ShiftAmt > 0) &&
4719 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4720 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4721 TLI.isTruncateFree(VT, TruncVT)) {
4724 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4725 getShiftAmountTy(N0.getOperand(0).getValueType()));
4726 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4727 N0.getOperand(0), Amt);
4728 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4730 return DAG.getNode(ISD::SIGN_EXTEND, DL,
4731 N->getValueType(0), Trunc);
4736 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4737 if (N1.getOpcode() == ISD::TRUNCATE &&
4738 N1.getOperand(0).getOpcode() == ISD::AND) {
4739 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4740 if (NewOp1.getNode())
4741 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4744 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4745 // if c1 is equal to the number of bits the trunc removes
4746 if (N0.getOpcode() == ISD::TRUNCATE &&
4747 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4748 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4749 N0.getOperand(0).hasOneUse() &&
4750 N0.getOperand(0).getOperand(1).hasOneUse() &&
4752 SDValue N0Op0 = N0.getOperand(0);
4753 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4754 unsigned LargeShiftVal = LargeShift->getZExtValue();
4755 EVT LargeVT = N0Op0.getValueType();
4757 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4760 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4761 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4762 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4763 N0Op0.getOperand(0), Amt);
4764 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4769 // Simplify, based on bits shifted out of the LHS.
4770 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4771 return SDValue(N, 0);
4774 // If the sign bit is known to be zero, switch this to a SRL.
4775 if (DAG.SignBitIsZero(N0))
4776 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4778 if (N1C && !N1C->isOpaque())
4779 if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4785 SDValue DAGCombiner::visitSRL(SDNode *N) {
4786 SDValue N0 = N->getOperand(0);
4787 SDValue N1 = N->getOperand(1);
4788 EVT VT = N0.getValueType();
4789 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4792 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4793 if (VT.isVector()) {
4794 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4797 N1C = isConstOrConstSplat(N1);
4800 // fold (srl c1, c2) -> c1 >>u c2
4801 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4802 if (N0C && N1C && !N1C->isOpaque())
4803 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4804 // fold (srl 0, x) -> 0
4805 if (isNullConstant(N0))
4807 // fold (srl x, c >= size(x)) -> undef
4808 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4809 return DAG.getUNDEF(VT);
4810 // fold (srl x, 0) -> x
4811 if (N1C && N1C->isNullValue())
4813 // if (srl x, c) is known to be zero, return 0
4814 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4815 APInt::getAllOnesValue(OpSizeInBits)))
4816 return DAG.getConstant(0, SDLoc(N), VT);
4818 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4819 if (N1C && N0.getOpcode() == ISD::SRL) {
4820 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4821 uint64_t c1 = N01C->getZExtValue();
4822 uint64_t c2 = N1C->getZExtValue();
4824 if (c1 + c2 >= OpSizeInBits)
4825 return DAG.getConstant(0, DL, VT);
4826 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4827 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4831 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4832 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4833 N0.getOperand(0).getOpcode() == ISD::SRL &&
4834 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4836 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4837 uint64_t c2 = N1C->getZExtValue();
4838 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4839 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4840 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4841 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4842 if (c1 + OpSizeInBits == InnerShiftSize) {
4844 if (c1 + c2 >= InnerShiftSize)
4845 return DAG.getConstant(0, DL, VT);
4846 return DAG.getNode(ISD::TRUNCATE, DL, VT,
4847 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4848 N0.getOperand(0)->getOperand(0),
4849 DAG.getConstant(c1 + c2, DL,
4854 // fold (srl (shl x, c), c) -> (and x, cst2)
4855 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4856 unsigned BitSize = N0.getScalarValueSizeInBits();
4857 if (BitSize <= 64) {
4858 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4860 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4861 DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4865 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4866 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4867 // Shifting in all undef bits?
4868 EVT SmallVT = N0.getOperand(0).getValueType();
4869 unsigned BitSize = SmallVT.getScalarSizeInBits();
4870 if (N1C->getZExtValue() >= BitSize)
4871 return DAG.getUNDEF(VT);
4873 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4874 uint64_t ShiftAmt = N1C->getZExtValue();
4876 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4878 DAG.getConstant(ShiftAmt, DL0,
4879 getShiftAmountTy(SmallVT)));
4880 AddToWorklist(SmallShift.getNode());
4881 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4883 return DAG.getNode(ISD::AND, DL, VT,
4884 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4885 DAG.getConstant(Mask, DL, VT));
4889 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4890 // bit, which is unmodified by sra.
4891 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4892 if (N0.getOpcode() == ISD::SRA)
4893 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4896 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4897 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4898 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4899 APInt KnownZero, KnownOne;
4900 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4902 // If any of the input bits are KnownOne, then the input couldn't be all
4903 // zeros, thus the result of the srl will always be zero.
4904 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4906 // If all of the bits input the to ctlz node are known to be zero, then
4907 // the result of the ctlz is "32" and the result of the shift is one.
4908 APInt UnknownBits = ~KnownZero;
4909 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4911 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4912 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4913 // Okay, we know that only that the single bit specified by UnknownBits
4914 // could be set on input to the CTLZ node. If this bit is set, the SRL
4915 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4916 // to an SRL/XOR pair, which is likely to simplify more.
4917 unsigned ShAmt = UnknownBits.countTrailingZeros();
4918 SDValue Op = N0.getOperand(0);
4922 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4923 DAG.getConstant(ShAmt, DL,
4924 getShiftAmountTy(Op.getValueType())));
4925 AddToWorklist(Op.getNode());
4929 return DAG.getNode(ISD::XOR, DL, VT,
4930 Op, DAG.getConstant(1, DL, VT));
4934 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4935 if (N1.getOpcode() == ISD::TRUNCATE &&
4936 N1.getOperand(0).getOpcode() == ISD::AND) {
4937 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4938 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4941 // fold operands of srl based on knowledge that the low bits are not
4943 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4944 return SDValue(N, 0);
4946 if (N1C && !N1C->isOpaque())
4947 if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4950 // Attempt to convert a srl of a load into a narrower zero-extending load.
4951 if (SDValue NarrowLoad = ReduceLoadWidth(N))
4954 // Here is a common situation. We want to optimize:
4957 // %b = and i32 %a, 2
4958 // %c = srl i32 %b, 1
4959 // brcond i32 %c ...
4965 // %c = setcc eq %b, 0
4968 // However when after the source operand of SRL is optimized into AND, the SRL
4969 // itself may not be optimized further. Look for it and add the BRCOND into
4971 if (N->hasOneUse()) {
4972 SDNode *Use = *N->use_begin();
4973 if (Use->getOpcode() == ISD::BRCOND)
4975 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4976 // Also look pass the truncate.
4977 Use = *Use->use_begin();
4978 if (Use->getOpcode() == ISD::BRCOND)
4986 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4987 SDValue N0 = N->getOperand(0);
4988 EVT VT = N->getValueType(0);
4990 // fold (bswap c1) -> c2
4991 if (isConstantIntBuildVectorOrConstantInt(N0))
4992 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4993 // fold (bswap (bswap x)) -> x
4994 if (N0.getOpcode() == ISD::BSWAP)
4995 return N0->getOperand(0);
4999 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
5000 SDValue N0 = N->getOperand(0);
5001 EVT VT = N->getValueType(0);
5003 // fold (ctlz c1) -> c2
5004 if (isConstantIntBuildVectorOrConstantInt(N0))
5005 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
5009 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
5010 SDValue N0 = N->getOperand(0);
5011 EVT VT = N->getValueType(0);
5013 // fold (ctlz_zero_undef c1) -> c2
5014 if (isConstantIntBuildVectorOrConstantInt(N0))
5015 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5019 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
5020 SDValue N0 = N->getOperand(0);
5021 EVT VT = N->getValueType(0);
5023 // fold (cttz c1) -> c2
5024 if (isConstantIntBuildVectorOrConstantInt(N0))
5025 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
5029 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
5030 SDValue N0 = N->getOperand(0);
5031 EVT VT = N->getValueType(0);
5033 // fold (cttz_zero_undef c1) -> c2
5034 if (isConstantIntBuildVectorOrConstantInt(N0))
5035 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5039 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
5040 SDValue N0 = N->getOperand(0);
5041 EVT VT = N->getValueType(0);
5043 // fold (ctpop c1) -> c2
5044 if (isConstantIntBuildVectorOrConstantInt(N0))
5045 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
5050 /// \brief Generate Min/Max node
5051 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
5052 SDValue True, SDValue False,
5053 ISD::CondCode CC, const TargetLowering &TLI,
5054 SelectionDAG &DAG) {
5055 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
5065 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
5066 if (TLI.isOperationLegal(Opcode, VT))
5067 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5076 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
5077 if (TLI.isOperationLegal(Opcode, VT))
5078 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5086 SDValue DAGCombiner::visitSELECT(SDNode *N) {
5087 SDValue N0 = N->getOperand(0);
5088 SDValue N1 = N->getOperand(1);
5089 SDValue N2 = N->getOperand(2);
5090 EVT VT = N->getValueType(0);
5091 EVT VT0 = N0.getValueType();
5093 // fold (select C, X, X) -> X
5096 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
5097 // fold (select true, X, Y) -> X
5098 // fold (select false, X, Y) -> Y
5099 return !N0C->isNullValue() ? N1 : N2;
5101 // fold (select C, 1, X) -> (or C, X)
5102 if (VT == MVT::i1 && isOneConstant(N1))
5103 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5104 // fold (select C, 0, 1) -> (xor C, 1)
5105 // We can't do this reliably if integer based booleans have different contents
5106 // to floating point based booleans. This is because we can't tell whether we
5107 // have an integer-based boolean or a floating-point-based boolean unless we
5108 // can find the SETCC that produced it and inspect its operands. This is
5109 // fairly easy if C is the SETCC node, but it can potentially be
5110 // undiscoverable (or not reasonably discoverable). For example, it could be
5111 // in another basic block or it could require searching a complicated
5113 if (VT.isInteger() &&
5114 (VT0 == MVT::i1 || (VT0.isInteger() &&
5115 TLI.getBooleanContents(false, false) ==
5116 TLI.getBooleanContents(false, true) &&
5117 TLI.getBooleanContents(false, false) ==
5118 TargetLowering::ZeroOrOneBooleanContent)) &&
5119 isNullConstant(N1) && isOneConstant(N2)) {
5123 return DAG.getNode(ISD::XOR, DL, VT0,
5124 N0, DAG.getConstant(1, DL, VT0));
5127 XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
5128 N0, DAG.getConstant(1, DL0, VT0));
5129 AddToWorklist(XORNode.getNode());
5131 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
5132 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
5134 // fold (select C, 0, X) -> (and (not C), X)
5135 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
5136 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5137 AddToWorklist(NOTNode.getNode());
5138 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
5140 // fold (select C, X, 1) -> (or (not C), X)
5141 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
5142 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5143 AddToWorklist(NOTNode.getNode());
5144 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
5146 // fold (select C, X, 0) -> (and C, X)
5147 if (VT == MVT::i1 && isNullConstant(N2))
5148 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5149 // fold (select X, X, Y) -> (or X, Y)
5150 // fold (select X, 1, Y) -> (or X, Y)
5151 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5152 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5153 // fold (select X, Y, X) -> (and X, Y)
5154 // fold (select X, Y, 0) -> (and X, Y)
5155 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5156 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5158 // If we can fold this based on the true/false value, do so.
5159 if (SimplifySelectOps(N, N1, N2))
5160 return SDValue(N, 0); // Don't revisit N.
5162 if (VT0 == MVT::i1) {
5163 // The code in this block deals with the following 2 equivalences:
5164 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5165 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5166 // The target can specify its prefered form with the
5167 // shouldNormalizeToSelectSequence() callback. However we always transform
5168 // to the right anyway if we find the inner select exists in the DAG anyway
5169 // and we always transform to the left side if we know that we can further
5170 // optimize the combination of the conditions.
5171 bool normalizeToSequence
5172 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5173 // select (and Cond0, Cond1), X, Y
5174 // -> select Cond0, (select Cond1, X, Y), Y
5175 if (N0->getOpcode() == ISD::AND && 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,
5184 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5185 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5186 SDValue Cond0 = N0->getOperand(0);
5187 SDValue Cond1 = N0->getOperand(1);
5188 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5189 N1.getValueType(), Cond1, N1, N2);
5190 if (normalizeToSequence || !InnerSelect.use_empty())
5191 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5195 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5196 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5197 SDValue N1_0 = N1->getOperand(0);
5198 SDValue N1_1 = N1->getOperand(1);
5199 SDValue N1_2 = N1->getOperand(2);
5200 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5201 // Create the actual and node if we can generate good code for it.
5202 if (!normalizeToSequence) {
5203 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5205 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5208 // Otherwise see if we can optimize the "and" to a better pattern.
5209 if (SDValue Combined = visitANDLike(N0, N1_0, N))
5210 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5214 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5215 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5216 SDValue N2_0 = N2->getOperand(0);
5217 SDValue N2_1 = N2->getOperand(1);
5218 SDValue N2_2 = N2->getOperand(2);
5219 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5220 // Create the actual or node if we can generate good code for it.
5221 if (!normalizeToSequence) {
5222 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5224 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5227 // Otherwise see if we can optimize to a better pattern.
5228 if (SDValue Combined = visitORLike(N0, N2_0, N))
5229 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5235 // fold selects based on a setcc into other things, such as min/max/abs
5236 if (N0.getOpcode() == ISD::SETCC) {
5237 // select x, y (fcmp lt x, y) -> fminnum x, y
5238 // select x, y (fcmp gt x, y) -> fmaxnum x, y
5240 // This is OK if we don't care about what happens if either operand is a
5244 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5245 // no signed zeros as well as no nans.
5246 const TargetOptions &Options = DAG.getTarget().Options;
5247 if (Options.UnsafeFPMath &&
5248 VT.isFloatingPoint() && N0.hasOneUse() &&
5249 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5250 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5252 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5253 N0.getOperand(1), N1, N2, CC,
5258 if ((!LegalOperations &&
5259 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5260 TLI.isOperationLegal(ISD::SELECT_CC, VT))
5261 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5262 N0.getOperand(0), N0.getOperand(1),
5263 N1, N2, N0.getOperand(2));
5264 return SimplifySelect(SDLoc(N), N0, N1, N2);
5271 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5274 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5276 // Split the inputs.
5277 SDValue Lo, Hi, LL, LH, RL, RH;
5278 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5279 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5281 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5282 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5284 return std::make_pair(Lo, Hi);
5287 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5288 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5289 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5291 SDValue Cond = N->getOperand(0);
5292 SDValue LHS = N->getOperand(1);
5293 SDValue RHS = N->getOperand(2);
5294 EVT VT = N->getValueType(0);
5295 int NumElems = VT.getVectorNumElements();
5296 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5297 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5298 Cond.getOpcode() == ISD::BUILD_VECTOR);
5300 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5301 // binary ones here.
5302 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5305 // We're sure we have an even number of elements due to the
5306 // concat_vectors we have as arguments to vselect.
5307 // Skip BV elements until we find one that's not an UNDEF
5308 // After we find an UNDEF element, keep looping until we get to half the
5309 // length of the BV and see if all the non-undef nodes are the same.
5310 ConstantSDNode *BottomHalf = nullptr;
5311 for (int i = 0; i < NumElems / 2; ++i) {
5312 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5315 if (BottomHalf == nullptr)
5316 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5317 else if (Cond->getOperand(i).getNode() != BottomHalf)
5321 // Do the same for the second half of the BuildVector
5322 ConstantSDNode *TopHalf = nullptr;
5323 for (int i = NumElems / 2; i < NumElems; ++i) {
5324 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5327 if (TopHalf == nullptr)
5328 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5329 else if (Cond->getOperand(i).getNode() != TopHalf)
5333 assert(TopHalf && BottomHalf &&
5334 "One half of the selector was all UNDEFs and the other was all the "
5335 "same value. This should have been addressed before this function.");
5337 ISD::CONCAT_VECTORS, dl, VT,
5338 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5339 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5342 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5344 if (Level >= AfterLegalizeTypes)
5347 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5348 SDValue Mask = MSC->getMask();
5349 SDValue Data = MSC->getValue();
5352 // If the MSCATTER data type requires splitting and the mask is provided by a
5353 // SETCC, then split both nodes and its operands before legalization. This
5354 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5355 // and enables future optimizations (e.g. min/max pattern matching on X86).
5356 if (Mask.getOpcode() != ISD::SETCC)
5359 // Check if any splitting is required.
5360 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5361 TargetLowering::TypeSplitVector)
5363 SDValue MaskLo, MaskHi, Lo, Hi;
5364 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5367 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5369 SDValue Chain = MSC->getChain();
5371 EVT MemoryVT = MSC->getMemoryVT();
5372 unsigned Alignment = MSC->getOriginalAlignment();
5374 EVT LoMemVT, HiMemVT;
5375 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5377 SDValue DataLo, DataHi;
5378 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5380 SDValue BasePtr = MSC->getBasePtr();
5381 SDValue IndexLo, IndexHi;
5382 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5384 MachineMemOperand *MMO = DAG.getMachineFunction().
5385 getMachineMemOperand(MSC->getPointerInfo(),
5386 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5387 Alignment, MSC->getAAInfo(), MSC->getRanges());
5389 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5390 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5393 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5394 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5397 AddToWorklist(Lo.getNode());
5398 AddToWorklist(Hi.getNode());
5400 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5403 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5405 if (Level >= AfterLegalizeTypes)
5408 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5409 SDValue Mask = MST->getMask();
5410 SDValue Data = MST->getValue();
5413 // If the MSTORE data type requires splitting and the mask is provided by a
5414 // SETCC, then split both nodes and its operands before legalization. This
5415 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5416 // and enables future optimizations (e.g. min/max pattern matching on X86).
5417 if (Mask.getOpcode() == ISD::SETCC) {
5419 // Check if any splitting is required.
5420 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5421 TargetLowering::TypeSplitVector)
5424 SDValue MaskLo, MaskHi, Lo, Hi;
5425 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5428 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5430 SDValue Chain = MST->getChain();
5431 SDValue Ptr = MST->getBasePtr();
5433 EVT MemoryVT = MST->getMemoryVT();
5434 unsigned Alignment = MST->getOriginalAlignment();
5436 // if Alignment is equal to the vector size,
5437 // take the half of it for the second part
5438 unsigned SecondHalfAlignment =
5439 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5440 Alignment/2 : Alignment;
5442 EVT LoMemVT, HiMemVT;
5443 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5445 SDValue DataLo, DataHi;
5446 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5448 MachineMemOperand *MMO = DAG.getMachineFunction().
5449 getMachineMemOperand(MST->getPointerInfo(),
5450 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5451 Alignment, MST->getAAInfo(), MST->getRanges());
5453 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5454 MST->isTruncatingStore());
5456 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5457 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5458 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5460 MMO = DAG.getMachineFunction().
5461 getMachineMemOperand(MST->getPointerInfo(),
5462 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5463 SecondHalfAlignment, MST->getAAInfo(),
5466 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5467 MST->isTruncatingStore());
5469 AddToWorklist(Lo.getNode());
5470 AddToWorklist(Hi.getNode());
5472 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5477 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5479 if (Level >= AfterLegalizeTypes)
5482 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5483 SDValue Mask = MGT->getMask();
5486 // If the MGATHER result requires splitting and the mask is provided by a
5487 // SETCC, then split both nodes and its operands before legalization. This
5488 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5489 // and enables future optimizations (e.g. min/max pattern matching on X86).
5491 if (Mask.getOpcode() != ISD::SETCC)
5494 EVT VT = N->getValueType(0);
5496 // Check if any splitting is required.
5497 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5498 TargetLowering::TypeSplitVector)
5501 SDValue MaskLo, MaskHi, Lo, Hi;
5502 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5504 SDValue Src0 = MGT->getValue();
5505 SDValue Src0Lo, Src0Hi;
5506 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5509 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5511 SDValue Chain = MGT->getChain();
5512 EVT MemoryVT = MGT->getMemoryVT();
5513 unsigned Alignment = MGT->getOriginalAlignment();
5515 EVT LoMemVT, HiMemVT;
5516 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5518 SDValue BasePtr = MGT->getBasePtr();
5519 SDValue Index = MGT->getIndex();
5520 SDValue IndexLo, IndexHi;
5521 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5523 MachineMemOperand *MMO = DAG.getMachineFunction().
5524 getMachineMemOperand(MGT->getPointerInfo(),
5525 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5526 Alignment, MGT->getAAInfo(), MGT->getRanges());
5528 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5529 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5532 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5533 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5536 AddToWorklist(Lo.getNode());
5537 AddToWorklist(Hi.getNode());
5539 // Build a factor node to remember that this load is independent of the
5541 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5544 // Legalized the chain result - switch anything that used the old chain to
5546 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5548 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5550 SDValue RetOps[] = { GatherRes, Chain };
5551 return DAG.getMergeValues(RetOps, DL);
5554 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5556 if (Level >= AfterLegalizeTypes)
5559 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5560 SDValue Mask = MLD->getMask();
5563 // If the MLOAD result requires splitting and the mask is provided by a
5564 // SETCC, then split both nodes and its operands before legalization. This
5565 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5566 // and enables future optimizations (e.g. min/max pattern matching on X86).
5568 if (Mask.getOpcode() == ISD::SETCC) {
5569 EVT VT = N->getValueType(0);
5571 // Check if any splitting is required.
5572 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5573 TargetLowering::TypeSplitVector)
5576 SDValue MaskLo, MaskHi, Lo, Hi;
5577 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5579 SDValue Src0 = MLD->getSrc0();
5580 SDValue Src0Lo, Src0Hi;
5581 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5584 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5586 SDValue Chain = MLD->getChain();
5587 SDValue Ptr = MLD->getBasePtr();
5588 EVT MemoryVT = MLD->getMemoryVT();
5589 unsigned Alignment = MLD->getOriginalAlignment();
5591 // if Alignment is equal to the vector size,
5592 // take the half of it for the second part
5593 unsigned SecondHalfAlignment =
5594 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5595 Alignment/2 : Alignment;
5597 EVT LoMemVT, HiMemVT;
5598 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5600 MachineMemOperand *MMO = DAG.getMachineFunction().
5601 getMachineMemOperand(MLD->getPointerInfo(),
5602 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5603 Alignment, MLD->getAAInfo(), MLD->getRanges());
5605 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5608 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5609 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5610 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5612 MMO = DAG.getMachineFunction().
5613 getMachineMemOperand(MLD->getPointerInfo(),
5614 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5615 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5617 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5620 AddToWorklist(Lo.getNode());
5621 AddToWorklist(Hi.getNode());
5623 // Build a factor node to remember that this load is independent of the
5625 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5628 // Legalized the chain result - switch anything that used the old chain to
5630 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5632 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5634 SDValue RetOps[] = { LoadRes, Chain };
5635 return DAG.getMergeValues(RetOps, DL);
5640 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5641 SDValue N0 = N->getOperand(0);
5642 SDValue N1 = N->getOperand(1);
5643 SDValue N2 = N->getOperand(2);
5646 // Canonicalize integer abs.
5647 // vselect (setg[te] X, 0), X, -X ->
5648 // vselect (setgt X, -1), X, -X ->
5649 // vselect (setl[te] X, 0), -X, X ->
5650 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5651 if (N0.getOpcode() == ISD::SETCC) {
5652 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5653 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5655 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5657 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5658 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5659 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5660 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5661 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5662 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5663 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5666 EVT VT = LHS.getValueType();
5667 SDValue Shift = DAG.getNode(
5668 ISD::SRA, DL, VT, LHS,
5669 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5670 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5671 AddToWorklist(Shift.getNode());
5672 AddToWorklist(Add.getNode());
5673 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5677 if (SimplifySelectOps(N, N1, N2))
5678 return SDValue(N, 0); // Don't revisit N.
5680 // If the VSELECT result requires splitting and the mask is provided by a
5681 // SETCC, then split both nodes and its operands before legalization. This
5682 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5683 // and enables future optimizations (e.g. min/max pattern matching on X86).
5684 if (N0.getOpcode() == ISD::SETCC) {
5685 EVT VT = N->getValueType(0);
5687 // Check if any splitting is required.
5688 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5689 TargetLowering::TypeSplitVector)
5692 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5693 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5694 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5695 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5697 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5698 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5700 // Add the new VSELECT nodes to the work list in case they need to be split
5702 AddToWorklist(Lo.getNode());
5703 AddToWorklist(Hi.getNode());
5705 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5708 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5709 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5711 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5712 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5715 // The ConvertSelectToConcatVector function is assuming both the above
5716 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5718 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5719 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5720 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5721 if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5728 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5729 SDValue N0 = N->getOperand(0);
5730 SDValue N1 = N->getOperand(1);
5731 SDValue N2 = N->getOperand(2);
5732 SDValue N3 = N->getOperand(3);
5733 SDValue N4 = N->getOperand(4);
5734 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5736 // fold select_cc lhs, rhs, x, x, cc -> x
5740 // Determine if the condition we're dealing with is constant
5741 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5742 N0, N1, CC, SDLoc(N), false);
5743 if (SCC.getNode()) {
5744 AddToWorklist(SCC.getNode());
5746 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5747 if (!SCCC->isNullValue())
5748 return N2; // cond always true -> true val
5750 return N3; // cond always false -> false val
5751 } else if (SCC->getOpcode() == ISD::UNDEF) {
5752 // When the condition is UNDEF, just return the first operand. This is
5753 // coherent the DAG creation, no setcc node is created in this case
5755 } else if (SCC.getOpcode() == ISD::SETCC) {
5756 // Fold to a simpler select_cc
5757 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5758 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5763 // If we can fold this based on the true/false value, do so.
5764 if (SimplifySelectOps(N, N2, N3))
5765 return SDValue(N, 0); // Don't revisit N.
5767 // fold select_cc into other things, such as min/max/abs
5768 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5771 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5772 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5773 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5777 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
5778 SDValue LHS = N->getOperand(0);
5779 SDValue RHS = N->getOperand(1);
5780 SDValue Carry = N->getOperand(2);
5781 SDValue Cond = N->getOperand(3);
5783 // If Carry is false, fold to a regular SETCC.
5784 if (Carry.getOpcode() == ISD::CARRY_FALSE)
5785 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
5790 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5791 /// a build_vector of constants.
5792 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5793 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5794 /// Vector extends are not folded if operations are legal; this is to
5795 /// avoid introducing illegal build_vector dag nodes.
5796 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5797 SelectionDAG &DAG, bool LegalTypes,
5798 bool LegalOperations) {
5799 unsigned Opcode = N->getOpcode();
5800 SDValue N0 = N->getOperand(0);
5801 EVT VT = N->getValueType(0);
5803 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5804 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5805 && "Expected EXTEND dag node in input!");
5807 // fold (sext c1) -> c1
5808 // fold (zext c1) -> c1
5809 // fold (aext c1) -> c1
5810 if (isa<ConstantSDNode>(N0))
5811 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5813 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5814 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5815 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5816 EVT SVT = VT.getScalarType();
5817 if (!(VT.isVector() &&
5818 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5819 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5822 // We can fold this node into a build_vector.
5823 unsigned VTBits = SVT.getSizeInBits();
5824 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5825 SmallVector<SDValue, 8> Elts;
5826 unsigned NumElts = VT.getVectorNumElements();
5829 for (unsigned i=0; i != NumElts; ++i) {
5830 SDValue Op = N0->getOperand(i);
5831 if (Op->getOpcode() == ISD::UNDEF) {
5832 Elts.push_back(DAG.getUNDEF(SVT));
5837 // Get the constant value and if needed trunc it to the size of the type.
5838 // Nodes like build_vector might have constants wider than the scalar type.
5839 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5840 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5841 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5843 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5846 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5849 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5850 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5851 // transformation. Returns true if extension are possible and the above
5852 // mentioned transformation is profitable.
5853 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5855 SmallVectorImpl<SDNode *> &ExtendNodes,
5856 const TargetLowering &TLI) {
5857 bool HasCopyToRegUses = false;
5858 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5859 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5860 UE = N0.getNode()->use_end();
5865 if (UI.getUse().getResNo() != N0.getResNo())
5867 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5868 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5869 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5870 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5871 // Sign bits will be lost after a zext.
5874 for (unsigned i = 0; i != 2; ++i) {
5875 SDValue UseOp = User->getOperand(i);
5878 if (!isa<ConstantSDNode>(UseOp))
5883 ExtendNodes.push_back(User);
5886 // If truncates aren't free and there are users we can't
5887 // extend, it isn't worthwhile.
5890 // Remember if this value is live-out.
5891 if (User->getOpcode() == ISD::CopyToReg)
5892 HasCopyToRegUses = true;
5895 if (HasCopyToRegUses) {
5896 bool BothLiveOut = false;
5897 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5899 SDUse &Use = UI.getUse();
5900 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5906 // Both unextended and extended values are live out. There had better be
5907 // a good reason for the transformation.
5908 return ExtendNodes.size();
5913 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5914 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5915 ISD::NodeType ExtType) {
5916 // Extend SetCC uses if necessary.
5917 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5918 SDNode *SetCC = SetCCs[i];
5919 SmallVector<SDValue, 4> Ops;
5921 for (unsigned j = 0; j != 2; ++j) {
5922 SDValue SOp = SetCC->getOperand(j);
5924 Ops.push_back(ExtLoad);
5926 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5929 Ops.push_back(SetCC->getOperand(2));
5930 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5934 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5935 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5936 SDValue N0 = N->getOperand(0);
5937 EVT DstVT = N->getValueType(0);
5938 EVT SrcVT = N0.getValueType();
5940 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5941 N->getOpcode() == ISD::ZERO_EXTEND) &&
5942 "Unexpected node type (not an extend)!");
5944 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5945 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5946 // (v8i32 (sext (v8i16 (load x))))
5948 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5949 // (v4i32 (sextload (x + 16)))))
5950 // Where uses of the original load, i.e.:
5952 // are replaced with:
5954 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5955 // (v4i32 (sextload (x + 16)))))))
5957 // This combine is only applicable to illegal, but splittable, vectors.
5958 // All legal types, and illegal non-vector types, are handled elsewhere.
5959 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5961 if (N0->getOpcode() != ISD::LOAD)
5964 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5966 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5967 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5968 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5971 SmallVector<SDNode *, 4> SetCCs;
5972 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5975 ISD::LoadExtType ExtType =
5976 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5978 // Try to split the vector types to get down to legal types.
5979 EVT SplitSrcVT = SrcVT;
5980 EVT SplitDstVT = DstVT;
5981 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5982 SplitSrcVT.getVectorNumElements() > 1) {
5983 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5984 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5987 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5991 const unsigned NumSplits =
5992 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5993 const unsigned Stride = SplitSrcVT.getStoreSize();
5994 SmallVector<SDValue, 4> Loads;
5995 SmallVector<SDValue, 4> Chains;
5997 SDValue BasePtr = LN0->getBasePtr();
5998 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5999 const unsigned Offset = Idx * Stride;
6000 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
6002 SDValue SplitLoad = DAG.getExtLoad(
6003 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
6004 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
6005 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
6006 Align, LN0->getAAInfo());
6008 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
6009 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
6011 Loads.push_back(SplitLoad.getValue(0));
6012 Chains.push_back(SplitLoad.getValue(1));
6015 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
6016 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
6018 CombineTo(N, NewValue);
6020 // Replace uses of the original load (before extension)
6021 // with a truncate of the concatenated sextloaded vectors.
6023 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
6024 CombineTo(N0.getNode(), Trunc, NewChain);
6025 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
6026 (ISD::NodeType)N->getOpcode());
6027 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6030 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
6031 SDValue N0 = N->getOperand(0);
6032 EVT VT = N->getValueType(0);
6034 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6036 return SDValue(Res, 0);
6038 // fold (sext (sext x)) -> (sext x)
6039 // fold (sext (aext x)) -> (sext x)
6040 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6041 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
6044 if (N0.getOpcode() == ISD::TRUNCATE) {
6045 // fold (sext (truncate (load x))) -> (sext (smaller load x))
6046 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
6047 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6048 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6049 if (NarrowLoad.getNode() != N0.getNode()) {
6050 CombineTo(N0.getNode(), NarrowLoad);
6051 // CombineTo deleted the truncate, if needed, but not what's under it.
6054 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6057 // See if the value being truncated is already sign extended. If so, just
6058 // eliminate the trunc/sext pair.
6059 SDValue Op = N0.getOperand(0);
6060 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
6061 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
6062 unsigned DestBits = VT.getScalarType().getSizeInBits();
6063 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
6065 if (OpBits == DestBits) {
6066 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
6067 // bits, it is already ready.
6068 if (NumSignBits > DestBits-MidBits)
6070 } else if (OpBits < DestBits) {
6071 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
6072 // bits, just sext from i32.
6073 if (NumSignBits > OpBits-MidBits)
6074 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
6076 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
6077 // bits, just truncate to i32.
6078 if (NumSignBits > OpBits-MidBits)
6079 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6082 // fold (sext (truncate x)) -> (sextinreg x).
6083 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
6084 N0.getValueType())) {
6085 if (OpBits < DestBits)
6086 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
6087 else if (OpBits > DestBits)
6088 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
6089 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
6090 DAG.getValueType(N0.getValueType()));
6094 // fold (sext (load x)) -> (sext (truncate (sextload x)))
6095 // Only generate vector extloads when 1) they're legal, and 2) they are
6096 // deemed desirable by the target.
6097 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6098 ((!LegalOperations && !VT.isVector() &&
6099 !cast<LoadSDNode>(N0)->isVolatile()) ||
6100 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
6101 bool DoXform = true;
6102 SmallVector<SDNode*, 4> SetCCs;
6103 if (!N0.hasOneUse())
6104 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
6106 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6108 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6109 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6111 LN0->getBasePtr(), N0.getValueType(),
6112 LN0->getMemOperand());
6113 CombineTo(N, ExtLoad);
6114 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6115 N0.getValueType(), ExtLoad);
6116 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6117 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6119 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6123 // fold (sext (load x)) to multiple smaller sextloads.
6124 // Only on illegal but splittable vectors.
6125 if (SDValue ExtLoad = CombineExtLoad(N))
6128 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6129 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6130 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6131 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6132 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6133 EVT MemVT = LN0->getMemoryVT();
6134 if ((!LegalOperations && !LN0->isVolatile()) ||
6135 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6136 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6138 LN0->getBasePtr(), MemVT,
6139 LN0->getMemOperand());
6140 CombineTo(N, ExtLoad);
6141 CombineTo(N0.getNode(),
6142 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6143 N0.getValueType(), ExtLoad),
6144 ExtLoad.getValue(1));
6145 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6149 // fold (sext (and/or/xor (load x), cst)) ->
6150 // (and/or/xor (sextload x), (sext cst))
6151 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6152 N0.getOpcode() == ISD::XOR) &&
6153 isa<LoadSDNode>(N0.getOperand(0)) &&
6154 N0.getOperand(1).getOpcode() == ISD::Constant &&
6155 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
6156 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6157 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6158 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
6159 bool DoXform = true;
6160 SmallVector<SDNode*, 4> SetCCs;
6161 if (!N0.hasOneUse())
6162 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6165 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6166 LN0->getChain(), LN0->getBasePtr(),
6168 LN0->getMemOperand());
6169 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6170 Mask = Mask.sext(VT.getSizeInBits());
6172 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6173 ExtLoad, DAG.getConstant(Mask, DL, VT));
6174 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6175 SDLoc(N0.getOperand(0)),
6176 N0.getOperand(0).getValueType(), ExtLoad);
6178 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6179 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6181 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6186 if (N0.getOpcode() == ISD::SETCC) {
6187 EVT N0VT = N0.getOperand(0).getValueType();
6188 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6189 // Only do this before legalize for now.
6190 if (VT.isVector() && !LegalOperations &&
6191 TLI.getBooleanContents(N0VT) ==
6192 TargetLowering::ZeroOrNegativeOneBooleanContent) {
6193 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6194 // of the same size as the compared operands. Only optimize sext(setcc())
6195 // if this is the case.
6196 EVT SVT = getSetCCResultType(N0VT);
6198 // We know that the # elements of the results is the same as the
6199 // # elements of the compare (and the # elements of the compare result
6200 // for that matter). Check to see that they are the same size. If so,
6201 // we know that the element size of the sext'd result matches the
6202 // element size of the compare operands.
6203 if (VT.getSizeInBits() == SVT.getSizeInBits())
6204 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6206 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6208 // If the desired elements are smaller or larger than the source
6209 // elements we can use a matching integer vector type and then
6210 // truncate/sign extend
6211 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6212 if (SVT == MatchingVectorType) {
6213 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6214 N0.getOperand(0), N0.getOperand(1),
6215 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6216 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6220 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6221 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6224 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6226 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6227 NegOne, DAG.getConstant(0, DL, VT),
6228 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6229 if (SCC.getNode()) return SCC;
6231 if (!VT.isVector()) {
6232 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6233 if (!LegalOperations ||
6234 TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6236 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6237 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6238 N0.getOperand(0), N0.getOperand(1), CC);
6239 return DAG.getSelect(DL, VT, SetCC,
6240 NegOne, DAG.getConstant(0, DL, VT));
6245 // fold (sext x) -> (zext x) if the sign bit is known zero.
6246 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6247 DAG.SignBitIsZero(N0))
6248 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6253 // isTruncateOf - If N is a truncate of some other value, return true, record
6254 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6255 // This function computes KnownZero to avoid a duplicated call to
6256 // computeKnownBits in the caller.
6257 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6260 if (N->getOpcode() == ISD::TRUNCATE) {
6261 Op = N->getOperand(0);
6262 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6266 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6267 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6270 SDValue Op0 = N->getOperand(0);
6271 SDValue Op1 = N->getOperand(1);
6272 assert(Op0.getValueType() == Op1.getValueType());
6274 if (isNullConstant(Op0))
6276 else if (isNullConstant(Op1))
6281 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6283 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6289 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6290 SDValue N0 = N->getOperand(0);
6291 EVT VT = N->getValueType(0);
6293 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6295 return SDValue(Res, 0);
6297 // fold (zext (zext x)) -> (zext x)
6298 // fold (zext (aext x)) -> (zext x)
6299 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6300 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6303 // fold (zext (truncate x)) -> (zext x) or
6304 // (zext (truncate x)) -> (truncate x)
6305 // This is valid when the truncated bits of x are already zero.
6306 // FIXME: We should extend this to work for vectors too.
6309 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6310 APInt TruncatedBits =
6311 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6312 APInt(Op.getValueSizeInBits(), 0) :
6313 APInt::getBitsSet(Op.getValueSizeInBits(),
6314 N0.getValueSizeInBits(),
6315 std::min(Op.getValueSizeInBits(),
6316 VT.getSizeInBits()));
6317 if (TruncatedBits == (KnownZero & TruncatedBits)) {
6318 if (VT.bitsGT(Op.getValueType()))
6319 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6320 if (VT.bitsLT(Op.getValueType()))
6321 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6327 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6328 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6329 if (N0.getOpcode() == ISD::TRUNCATE) {
6330 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6331 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6332 if (NarrowLoad.getNode() != N0.getNode()) {
6333 CombineTo(N0.getNode(), NarrowLoad);
6334 // CombineTo deleted the truncate, if needed, but not what's under it.
6337 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6341 // fold (zext (truncate x)) -> (and x, mask)
6342 if (N0.getOpcode() == ISD::TRUNCATE) {
6343 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6344 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6345 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6346 SDNode *oye = N0.getNode()->getOperand(0).getNode();
6347 if (NarrowLoad.getNode() != N0.getNode()) {
6348 CombineTo(N0.getNode(), NarrowLoad);
6349 // CombineTo deleted the truncate, if needed, but not what's under it.
6352 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6355 EVT SrcVT = N0.getOperand(0).getValueType();
6356 EVT MinVT = N0.getValueType();
6358 // Try to mask before the extension to avoid having to generate a larger mask,
6359 // possibly over several sub-vectors.
6360 if (SrcVT.bitsLT(VT)) {
6361 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6362 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6363 SDValue Op = N0.getOperand(0);
6364 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6365 AddToWorklist(Op.getNode());
6366 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6370 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6371 SDValue Op = N0.getOperand(0);
6372 if (SrcVT.bitsLT(VT)) {
6373 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6374 AddToWorklist(Op.getNode());
6375 } else if (SrcVT.bitsGT(VT)) {
6376 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6377 AddToWorklist(Op.getNode());
6379 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6383 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6384 // if either of the casts is not free.
6385 if (N0.getOpcode() == ISD::AND &&
6386 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6387 N0.getOperand(1).getOpcode() == ISD::Constant &&
6388 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6389 N0.getValueType()) ||
6390 !TLI.isZExtFree(N0.getValueType(), VT))) {
6391 SDValue X = N0.getOperand(0).getOperand(0);
6392 if (X.getValueType().bitsLT(VT)) {
6393 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6394 } else if (X.getValueType().bitsGT(VT)) {
6395 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6397 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6398 Mask = Mask.zext(VT.getSizeInBits());
6400 return DAG.getNode(ISD::AND, DL, VT,
6401 X, DAG.getConstant(Mask, DL, VT));
6404 // fold (zext (load x)) -> (zext (truncate (zextload x)))
6405 // Only generate vector extloads when 1) they're legal, and 2) they are
6406 // deemed desirable by the target.
6407 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6408 ((!LegalOperations && !VT.isVector() &&
6409 !cast<LoadSDNode>(N0)->isVolatile()) ||
6410 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6411 bool DoXform = true;
6412 SmallVector<SDNode*, 4> SetCCs;
6413 if (!N0.hasOneUse())
6414 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6416 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6418 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6419 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6421 LN0->getBasePtr(), N0.getValueType(),
6422 LN0->getMemOperand());
6423 CombineTo(N, ExtLoad);
6424 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6425 N0.getValueType(), ExtLoad);
6426 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6428 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6430 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6434 // fold (zext (load x)) to multiple smaller zextloads.
6435 // Only on illegal but splittable vectors.
6436 if (SDValue ExtLoad = CombineExtLoad(N))
6439 // fold (zext (and/or/xor (load x), cst)) ->
6440 // (and/or/xor (zextload x), (zext cst))
6441 // Unless (and (load x) cst) will match as a zextload already and has
6442 // additional users.
6443 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6444 N0.getOpcode() == ISD::XOR) &&
6445 isa<LoadSDNode>(N0.getOperand(0)) &&
6446 N0.getOperand(1).getOpcode() == ISD::Constant &&
6447 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6448 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6449 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6450 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6451 bool DoXform = true;
6452 SmallVector<SDNode*, 4> SetCCs;
6453 if (!N0.hasOneUse()) {
6454 if (N0.getOpcode() == ISD::AND) {
6455 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
6456 auto NarrowLoad = false;
6457 EVT LoadResultTy = AndC->getValueType(0);
6458 EVT ExtVT, LoadedVT;
6459 if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
6464 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
6465 ISD::ZERO_EXTEND, SetCCs, TLI);
6468 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6469 LN0->getChain(), LN0->getBasePtr(),
6471 LN0->getMemOperand());
6472 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6473 Mask = Mask.zext(VT.getSizeInBits());
6475 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6476 ExtLoad, DAG.getConstant(Mask, DL, VT));
6477 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6478 SDLoc(N0.getOperand(0)),
6479 N0.getOperand(0).getValueType(), ExtLoad);
6481 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6482 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6484 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6489 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6490 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6491 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6492 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6493 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6494 EVT MemVT = LN0->getMemoryVT();
6495 if ((!LegalOperations && !LN0->isVolatile()) ||
6496 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6497 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6499 LN0->getBasePtr(), MemVT,
6500 LN0->getMemOperand());
6501 CombineTo(N, ExtLoad);
6502 CombineTo(N0.getNode(),
6503 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6505 ExtLoad.getValue(1));
6506 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6510 if (N0.getOpcode() == ISD::SETCC) {
6511 if (!LegalOperations && VT.isVector() &&
6512 N0.getValueType().getVectorElementType() == MVT::i1) {
6513 EVT N0VT = N0.getOperand(0).getValueType();
6514 if (getSetCCResultType(N0VT) == N0.getValueType())
6517 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6518 // Only do this before legalize for now.
6519 EVT EltVT = VT.getVectorElementType();
6521 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6522 DAG.getConstant(1, DL, EltVT));
6523 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6524 // We know that the # elements of the results is the same as the
6525 // # elements of the compare (and the # elements of the compare result
6526 // for that matter). Check to see that they are the same size. If so,
6527 // we know that the element size of the sext'd result matches the
6528 // element size of the compare operands.
6529 return DAG.getNode(ISD::AND, DL, VT,
6530 DAG.getSetCC(DL, VT, N0.getOperand(0),
6532 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6533 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6536 // If the desired elements are smaller or larger than the source
6537 // elements we can use a matching integer vector type and then
6538 // truncate/sign extend
6539 EVT MatchingElementType =
6540 EVT::getIntegerVT(*DAG.getContext(),
6541 N0VT.getScalarType().getSizeInBits());
6542 EVT MatchingVectorType =
6543 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6544 N0VT.getVectorNumElements());
6546 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6548 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6549 return DAG.getNode(ISD::AND, DL, VT,
6550 DAG.getSExtOrTrunc(VsetCC, DL, VT),
6551 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6554 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6557 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6558 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6559 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6560 if (SCC.getNode()) return SCC;
6563 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6564 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6565 isa<ConstantSDNode>(N0.getOperand(1)) &&
6566 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6568 SDValue ShAmt = N0.getOperand(1);
6569 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6570 if (N0.getOpcode() == ISD::SHL) {
6571 SDValue InnerZExt = N0.getOperand(0);
6572 // If the original shl may be shifting out bits, do not perform this
6574 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6575 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6576 if (ShAmtVal > KnownZeroBits)
6582 // Ensure that the shift amount is wide enough for the shifted value.
6583 if (VT.getSizeInBits() >= 256)
6584 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6586 return DAG.getNode(N0.getOpcode(), DL, VT,
6587 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6594 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6595 SDValue N0 = N->getOperand(0);
6596 EVT VT = N->getValueType(0);
6598 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6600 return SDValue(Res, 0);
6602 // fold (aext (aext x)) -> (aext x)
6603 // fold (aext (zext x)) -> (zext x)
6604 // fold (aext (sext x)) -> (sext x)
6605 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6606 N0.getOpcode() == ISD::ZERO_EXTEND ||
6607 N0.getOpcode() == ISD::SIGN_EXTEND)
6608 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6610 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6611 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6612 if (N0.getOpcode() == ISD::TRUNCATE) {
6613 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6614 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6615 if (NarrowLoad.getNode() != N0.getNode()) {
6616 CombineTo(N0.getNode(), NarrowLoad);
6617 // CombineTo deleted the truncate, if needed, but not what's under it.
6620 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6624 // fold (aext (truncate x))
6625 if (N0.getOpcode() == ISD::TRUNCATE) {
6626 SDValue TruncOp = N0.getOperand(0);
6627 if (TruncOp.getValueType() == VT)
6628 return TruncOp; // x iff x size == zext size.
6629 if (TruncOp.getValueType().bitsGT(VT))
6630 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6631 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6634 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6635 // if the trunc is not free.
6636 if (N0.getOpcode() == ISD::AND &&
6637 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6638 N0.getOperand(1).getOpcode() == ISD::Constant &&
6639 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6640 N0.getValueType())) {
6641 SDValue X = N0.getOperand(0).getOperand(0);
6642 if (X.getValueType().bitsLT(VT)) {
6643 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6644 } else if (X.getValueType().bitsGT(VT)) {
6645 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6647 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6648 Mask = Mask.zext(VT.getSizeInBits());
6650 return DAG.getNode(ISD::AND, DL, VT,
6651 X, DAG.getConstant(Mask, DL, VT));
6654 // fold (aext (load x)) -> (aext (truncate (extload x)))
6655 // None of the supported targets knows how to perform load and any_ext
6656 // on vectors in one instruction. We only perform this transformation on
6658 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6659 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6660 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6661 bool DoXform = true;
6662 SmallVector<SDNode*, 4> SetCCs;
6663 if (!N0.hasOneUse())
6664 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6666 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6667 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6669 LN0->getBasePtr(), N0.getValueType(),
6670 LN0->getMemOperand());
6671 CombineTo(N, ExtLoad);
6672 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6673 N0.getValueType(), ExtLoad);
6674 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6675 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6677 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6681 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6682 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6683 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6684 if (N0.getOpcode() == ISD::LOAD &&
6685 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6687 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6688 ISD::LoadExtType ExtType = LN0->getExtensionType();
6689 EVT MemVT = LN0->getMemoryVT();
6690 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6691 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6692 VT, LN0->getChain(), LN0->getBasePtr(),
6693 MemVT, LN0->getMemOperand());
6694 CombineTo(N, ExtLoad);
6695 CombineTo(N0.getNode(),
6696 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6697 N0.getValueType(), ExtLoad),
6698 ExtLoad.getValue(1));
6699 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6703 if (N0.getOpcode() == ISD::SETCC) {
6705 // aext(setcc) -> vsetcc
6706 // aext(setcc) -> truncate(vsetcc)
6707 // aext(setcc) -> aext(vsetcc)
6708 // Only do this before legalize for now.
6709 if (VT.isVector() && !LegalOperations) {
6710 EVT N0VT = N0.getOperand(0).getValueType();
6711 // We know that the # elements of the results is the same as the
6712 // # elements of the compare (and the # elements of the compare result
6713 // for that matter). Check to see that they are the same size. If so,
6714 // we know that the element size of the sext'd result matches the
6715 // element size of the compare operands.
6716 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6717 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6719 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6720 // If the desired elements are smaller or larger than the source
6721 // elements we can use a matching integer vector type and then
6722 // truncate/any extend
6724 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6726 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6728 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6729 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6733 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6736 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6737 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6738 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6746 /// See if the specified operand can be simplified with the knowledge that only
6747 /// the bits specified by Mask are used. If so, return the simpler operand,
6748 /// otherwise return a null SDValue.
6749 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6750 switch (V.getOpcode()) {
6752 case ISD::Constant: {
6753 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6754 assert(CV && "Const value should be ConstSDNode.");
6755 const APInt &CVal = CV->getAPIntValue();
6756 APInt NewVal = CVal & Mask;
6758 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6763 // If the LHS or RHS don't contribute bits to the or, drop them.
6764 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6765 return V.getOperand(1);
6766 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6767 return V.getOperand(0);
6770 // Only look at single-use SRLs.
6771 if (!V.getNode()->hasOneUse())
6773 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6774 // See if we can recursively simplify the LHS.
6775 unsigned Amt = RHSC->getZExtValue();
6777 // Watch out for shift count overflow though.
6778 if (Amt >= Mask.getBitWidth()) break;
6779 APInt NewMask = Mask << Amt;
6780 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6781 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6782 SimplifyLHS, V.getOperand(1));
6788 /// If the result of a wider load is shifted to right of N bits and then
6789 /// truncated to a narrower type and where N is a multiple of number of bits of
6790 /// the narrower type, transform it to a narrower load from address + N / num of
6791 /// bits of new type. If the result is to be extended, also fold the extension
6792 /// to form a extending load.
6793 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6794 unsigned Opc = N->getOpcode();
6796 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6797 SDValue N0 = N->getOperand(0);
6798 EVT VT = N->getValueType(0);
6801 // This transformation isn't valid for vector loads.
6805 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6807 if (Opc == ISD::SIGN_EXTEND_INREG) {
6808 ExtType = ISD::SEXTLOAD;
6809 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6810 } else if (Opc == ISD::SRL) {
6811 // Another special-case: SRL is basically zero-extending a narrower value.
6812 ExtType = ISD::ZEXTLOAD;
6814 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6815 if (!N01) return SDValue();
6816 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6817 VT.getSizeInBits() - N01->getZExtValue());
6819 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6822 unsigned EVTBits = ExtVT.getSizeInBits();
6824 // Do not generate loads of non-round integer types since these can
6825 // be expensive (and would be wrong if the type is not byte sized).
6826 if (!ExtVT.isRound())
6830 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6831 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6832 ShAmt = N01->getZExtValue();
6833 // Is the shift amount a multiple of size of VT?
6834 if ((ShAmt & (EVTBits-1)) == 0) {
6835 N0 = N0.getOperand(0);
6836 // Is the load width a multiple of size of VT?
6837 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6841 // At this point, we must have a load or else we can't do the transform.
6842 if (!isa<LoadSDNode>(N0)) return SDValue();
6844 // Because a SRL must be assumed to *need* to zero-extend the high bits
6845 // (as opposed to anyext the high bits), we can't combine the zextload
6846 // lowering of SRL and an sextload.
6847 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6850 // If the shift amount is larger than the input type then we're not
6851 // accessing any of the loaded bytes. If the load was a zextload/extload
6852 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6853 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6858 // If the load is shifted left (and the result isn't shifted back right),
6859 // we can fold the truncate through the shift.
6860 unsigned ShLeftAmt = 0;
6861 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6862 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6863 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6864 ShLeftAmt = N01->getZExtValue();
6865 N0 = N0.getOperand(0);
6869 // If we haven't found a load, we can't narrow it. Don't transform one with
6870 // multiple uses, this would require adding a new load.
6871 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6874 // Don't change the width of a volatile load.
6875 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6876 if (LN0->isVolatile())
6879 // Verify that we are actually reducing a load width here.
6880 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6883 // For the transform to be legal, the load must produce only two values
6884 // (the value loaded and the chain). Don't transform a pre-increment
6885 // load, for example, which produces an extra value. Otherwise the
6886 // transformation is not equivalent, and the downstream logic to replace
6887 // uses gets things wrong.
6888 if (LN0->getNumValues() > 2)
6891 // If the load that we're shrinking is an extload and we're not just
6892 // discarding the extension we can't simply shrink the load. Bail.
6893 // TODO: It would be possible to merge the extensions in some cases.
6894 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6895 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6898 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6901 EVT PtrType = N0.getOperand(1).getValueType();
6903 if (PtrType == MVT::Untyped || PtrType.isExtended())
6904 // It's not possible to generate a constant of extended or untyped type.
6907 // For big endian targets, we need to adjust the offset to the pointer to
6908 // load the correct bytes.
6909 if (DAG.getDataLayout().isBigEndian()) {
6910 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6911 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6912 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6915 uint64_t PtrOff = ShAmt / 8;
6916 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6918 // The original load itself didn't wrap, so an offset within it doesn't.
6920 Flags.setNoUnsignedWrap(true);
6921 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6922 PtrType, LN0->getBasePtr(),
6923 DAG.getConstant(PtrOff, DL, PtrType),
6925 AddToWorklist(NewPtr.getNode());
6928 if (ExtType == ISD::NON_EXTLOAD)
6929 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6930 LN0->getPointerInfo().getWithOffset(PtrOff),
6931 LN0->isVolatile(), LN0->isNonTemporal(),
6932 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6934 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6935 LN0->getPointerInfo().getWithOffset(PtrOff),
6936 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6937 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6939 // Replace the old load's chain with the new load's chain.
6940 WorklistRemover DeadNodes(*this);
6941 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6943 // Shift the result left, if we've swallowed a left shift.
6944 SDValue Result = Load;
6945 if (ShLeftAmt != 0) {
6946 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6947 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6949 // If the shift amount is as large as the result size (but, presumably,
6950 // no larger than the source) then the useful bits of the result are
6951 // zero; we can't simply return the shortened shift, because the result
6952 // of that operation is undefined.
6954 if (ShLeftAmt >= VT.getSizeInBits())
6955 Result = DAG.getConstant(0, DL, VT);
6957 Result = DAG.getNode(ISD::SHL, DL, VT,
6958 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6961 // Return the new loaded value.
6965 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6966 SDValue N0 = N->getOperand(0);
6967 SDValue N1 = N->getOperand(1);
6968 EVT VT = N->getValueType(0);
6969 EVT EVT = cast<VTSDNode>(N1)->getVT();
6970 unsigned VTBits = VT.getScalarType().getSizeInBits();
6971 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6974 return DAG.getUNDEF(VT);
6976 // fold (sext_in_reg c1) -> c1
6977 if (isConstantIntBuildVectorOrConstantInt(N0))
6978 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6980 // If the input is already sign extended, just drop the extension.
6981 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6984 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6985 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6986 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6987 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6988 N0.getOperand(0), N1);
6990 // fold (sext_in_reg (sext x)) -> (sext x)
6991 // fold (sext_in_reg (aext x)) -> (sext x)
6992 // if x is small enough.
6993 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6994 SDValue N00 = N0.getOperand(0);
6995 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6996 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6997 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
7000 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
7001 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
7002 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
7004 // fold operands of sext_in_reg based on knowledge that the top bits are not
7006 if (SimplifyDemandedBits(SDValue(N, 0)))
7007 return SDValue(N, 0);
7009 // fold (sext_in_reg (load x)) -> (smaller sextload x)
7010 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
7011 if (SDValue NarrowLoad = ReduceLoadWidth(N))
7014 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
7015 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
7016 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
7017 if (N0.getOpcode() == ISD::SRL) {
7018 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
7019 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
7020 // We can turn this into an SRA iff the input to the SRL is already sign
7022 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
7023 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
7024 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
7025 N0.getOperand(0), N0.getOperand(1));
7029 // fold (sext_inreg (extload x)) -> (sextload x)
7030 if (ISD::isEXTLoad(N0.getNode()) &&
7031 ISD::isUNINDEXEDLoad(N0.getNode()) &&
7032 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7033 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7034 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7035 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7036 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7038 LN0->getBasePtr(), EVT,
7039 LN0->getMemOperand());
7040 CombineTo(N, ExtLoad);
7041 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7042 AddToWorklist(ExtLoad.getNode());
7043 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7045 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
7046 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7048 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7049 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7050 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7051 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7052 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7054 LN0->getBasePtr(), EVT,
7055 LN0->getMemOperand());
7056 CombineTo(N, ExtLoad);
7057 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7058 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7061 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
7062 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
7063 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
7064 N0.getOperand(1), false);
7065 if (BSwap.getNode())
7066 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7073 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
7074 SDValue N0 = N->getOperand(0);
7075 EVT VT = N->getValueType(0);
7077 if (N0.getOpcode() == ISD::UNDEF)
7078 return DAG.getUNDEF(VT);
7080 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7082 return SDValue(Res, 0);
7087 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
7088 SDValue N0 = N->getOperand(0);
7089 EVT VT = N->getValueType(0);
7090 bool isLE = DAG.getDataLayout().isLittleEndian();
7093 if (N0.getValueType() == N->getValueType(0))
7095 // fold (truncate c1) -> c1
7096 if (isConstantIntBuildVectorOrConstantInt(N0))
7097 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
7098 // fold (truncate (truncate x)) -> (truncate x)
7099 if (N0.getOpcode() == ISD::TRUNCATE)
7100 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7101 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
7102 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
7103 N0.getOpcode() == ISD::SIGN_EXTEND ||
7104 N0.getOpcode() == ISD::ANY_EXTEND) {
7105 if (N0.getOperand(0).getValueType().bitsLT(VT))
7106 // if the source is smaller than the dest, we still need an extend
7107 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
7109 if (N0.getOperand(0).getValueType().bitsGT(VT))
7110 // if the source is larger than the dest, than we just need the truncate
7111 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7112 // if the source and dest are the same type, we can drop both the extend
7113 // and the truncate.
7114 return N0.getOperand(0);
7117 // Fold extract-and-trunc into a narrow extract. For example:
7118 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
7119 // i32 y = TRUNCATE(i64 x)
7121 // v16i8 b = BITCAST (v2i64 val)
7122 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
7124 // Note: We only run this optimization after type legalization (which often
7125 // creates this pattern) and before operation legalization after which
7126 // we need to be more careful about the vector instructions that we generate.
7127 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7128 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
7130 EVT VecTy = N0.getOperand(0).getValueType();
7131 EVT ExTy = N0.getValueType();
7132 EVT TrTy = N->getValueType(0);
7134 unsigned NumElem = VecTy.getVectorNumElements();
7135 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
7137 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
7138 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
7140 SDValue EltNo = N0->getOperand(1);
7141 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
7142 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7143 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7144 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
7146 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
7147 NVT, N0.getOperand(0));
7150 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
7152 DAG.getConstant(Index, DL, IndexTy));
7156 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
7157 if (N0.getOpcode() == ISD::SELECT) {
7158 EVT SrcVT = N0.getValueType();
7159 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
7160 TLI.isTruncateFree(SrcVT, VT)) {
7162 SDValue Cond = N0.getOperand(0);
7163 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7164 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7165 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7169 // Fold a series of buildvector, bitcast, and truncate if possible.
7171 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7172 // (2xi32 (buildvector x, y)).
7173 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7174 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7175 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7176 N0.getOperand(0).hasOneUse()) {
7178 SDValue BuildVect = N0.getOperand(0);
7179 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7180 EVT TruncVecEltTy = VT.getVectorElementType();
7182 // Check that the element types match.
7183 if (BuildVectEltTy == TruncVecEltTy) {
7184 // Now we only need to compute the offset of the truncated elements.
7185 unsigned BuildVecNumElts = BuildVect.getNumOperands();
7186 unsigned TruncVecNumElts = VT.getVectorNumElements();
7187 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7189 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7190 "Invalid number of elements");
7192 SmallVector<SDValue, 8> Opnds;
7193 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7194 Opnds.push_back(BuildVect.getOperand(i));
7196 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
7200 // See if we can simplify the input to this truncate through knowledge that
7201 // only the low bits are being used.
7202 // For example "trunc (or (shl x, 8), y)" // -> trunc y
7203 // Currently we only perform this optimization on scalars because vectors
7204 // may have different active low bits.
7205 if (!VT.isVector()) {
7207 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7208 VT.getSizeInBits()));
7209 if (Shorter.getNode())
7210 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7212 // fold (truncate (load x)) -> (smaller load x)
7213 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7214 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7215 if (SDValue Reduced = ReduceLoadWidth(N))
7218 // Handle the case where the load remains an extending load even
7219 // after truncation.
7220 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7221 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7222 if (!LN0->isVolatile() &&
7223 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7224 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7225 VT, LN0->getChain(), LN0->getBasePtr(),
7227 LN0->getMemOperand());
7228 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7233 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7234 // where ... are all 'undef'.
7235 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7236 SmallVector<EVT, 8> VTs;
7239 unsigned NumDefs = 0;
7241 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7242 SDValue X = N0.getOperand(i);
7243 if (X.getOpcode() != ISD::UNDEF) {
7248 // Stop if more than one members are non-undef.
7251 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7252 VT.getVectorElementType(),
7253 X.getValueType().getVectorNumElements()));
7257 return DAG.getUNDEF(VT);
7260 assert(V.getNode() && "The single defined operand is empty!");
7261 SmallVector<SDValue, 8> Opnds;
7262 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7264 Opnds.push_back(DAG.getUNDEF(VTs[i]));
7267 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7268 AddToWorklist(NV.getNode());
7269 Opnds.push_back(NV);
7271 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7275 // Simplify the operands using demanded-bits information.
7276 if (!VT.isVector() &&
7277 SimplifyDemandedBits(SDValue(N, 0)))
7278 return SDValue(N, 0);
7283 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7284 SDValue Elt = N->getOperand(i);
7285 if (Elt.getOpcode() != ISD::MERGE_VALUES)
7286 return Elt.getNode();
7287 return Elt.getOperand(Elt.getResNo()).getNode();
7290 /// build_pair (load, load) -> load
7291 /// if load locations are consecutive.
7292 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7293 assert(N->getOpcode() == ISD::BUILD_PAIR);
7295 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7296 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7297 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7298 LD1->getAddressSpace() != LD2->getAddressSpace())
7300 EVT LD1VT = LD1->getValueType(0);
7302 if (ISD::isNON_EXTLoad(LD2) &&
7304 // If both are volatile this would reduce the number of volatile loads.
7305 // If one is volatile it might be ok, but play conservative and bail out.
7306 !LD1->isVolatile() &&
7307 !LD2->isVolatile() &&
7308 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7309 unsigned Align = LD1->getAlignment();
7310 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7311 VT.getTypeForEVT(*DAG.getContext()));
7313 if (NewAlign <= Align &&
7314 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7315 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7316 LD1->getBasePtr(), LD1->getPointerInfo(),
7317 false, false, false, Align);
7323 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
7324 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
7325 // and Lo parts; on big-endian machines it doesn't.
7326 return DAG.getDataLayout().isBigEndian() ? 1 : 0;
7329 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7330 SDValue N0 = N->getOperand(0);
7331 EVT VT = N->getValueType(0);
7333 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7334 // Only do this before legalize, since afterward the target may be depending
7335 // on the bitconvert.
7336 // First check to see if this is all constant.
7338 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7340 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7342 EVT DestEltVT = N->getValueType(0).getVectorElementType();
7343 assert(!DestEltVT.isVector() &&
7344 "Element type of vector ValueType must not be vector!");
7346 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7349 // If the input is a constant, let getNode fold it.
7350 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7351 // If we can't allow illegal operations, we need to check that this is just
7352 // a fp -> int or int -> conversion and that the resulting operation will
7354 if (!LegalOperations ||
7355 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7356 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7357 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7358 TLI.isOperationLegal(ISD::Constant, VT)))
7359 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7362 // (conv (conv x, t1), t2) -> (conv x, t2)
7363 if (N0.getOpcode() == ISD::BITCAST)
7364 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7367 // fold (conv (load x)) -> (load (conv*)x)
7368 // If the resultant load doesn't need a higher alignment than the original!
7369 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7370 // Do not change the width of a volatile load.
7371 !cast<LoadSDNode>(N0)->isVolatile() &&
7372 // Do not remove the cast if the types differ in endian layout.
7373 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7374 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7375 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7376 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7377 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7378 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7379 VT.getTypeForEVT(*DAG.getContext()));
7380 unsigned OrigAlign = LN0->getAlignment();
7382 if (Align <= OrigAlign) {
7383 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7384 LN0->getBasePtr(), LN0->getPointerInfo(),
7385 LN0->isVolatile(), LN0->isNonTemporal(),
7386 LN0->isInvariant(), OrigAlign,
7388 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7393 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7394 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7397 // fold (bitcast (fneg x)) ->
7398 // flipbit = signbit
7399 // (xor (bitcast x) (build_pair flipbit, flipbit))
7401 // fold (bitcast (fabs x)) ->
7402 // flipbit = (and (extract_element (bitcast x), 0), signbit)
7403 // (xor (bitcast x) (build_pair flipbit, flipbit))
7404 // This often reduces constant pool loads.
7405 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7406 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7407 N0.getNode()->hasOneUse() && VT.isInteger() &&
7408 !VT.isVector() && !N0.getValueType().isVector()) {
7409 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7411 AddToWorklist(NewConv.getNode());
7414 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7415 assert(VT.getSizeInBits() == 128);
7416 SDValue SignBit = DAG.getConstant(
7417 APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
7419 if (N0.getOpcode() == ISD::FNEG) {
7421 AddToWorklist(FlipBit.getNode());
7423 assert(N0.getOpcode() == ISD::FABS);
7425 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
7426 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7428 AddToWorklist(Hi.getNode());
7429 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
7430 AddToWorklist(FlipBit.getNode());
7433 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7434 AddToWorklist(FlipBits.getNode());
7435 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
7437 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7438 if (N0.getOpcode() == ISD::FNEG)
7439 return DAG.getNode(ISD::XOR, DL, VT,
7440 NewConv, DAG.getConstant(SignBit, DL, VT));
7441 assert(N0.getOpcode() == ISD::FABS);
7442 return DAG.getNode(ISD::AND, DL, VT,
7443 NewConv, DAG.getConstant(~SignBit, DL, VT));
7446 // fold (bitconvert (fcopysign cst, x)) ->
7447 // (or (and (bitconvert x), sign), (and cst, (not sign)))
7448 // Note that we don't handle (copysign x, cst) because this can always be
7449 // folded to an fneg or fabs.
7452 // fold (bitcast (fcopysign cst, x)) ->
7453 // flipbit = (and (extract_element
7454 // (xor (bitcast cst), (bitcast x)), 0),
7456 // (xor (bitcast cst) (build_pair flipbit, flipbit))
7457 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7458 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7459 VT.isInteger() && !VT.isVector()) {
7460 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7461 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7462 if (isTypeLegal(IntXVT)) {
7463 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7464 IntXVT, N0.getOperand(1));
7465 AddToWorklist(X.getNode());
7467 // If X has a different width than the result/lhs, sext it or truncate it.
7468 unsigned VTWidth = VT.getSizeInBits();
7469 if (OrigXWidth < VTWidth) {
7470 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7471 AddToWorklist(X.getNode());
7472 } else if (OrigXWidth > VTWidth) {
7473 // To get the sign bit in the right place, we have to shift it right
7474 // before truncating.
7476 X = DAG.getNode(ISD::SRL, DL,
7477 X.getValueType(), X,
7478 DAG.getConstant(OrigXWidth-VTWidth, DL,
7480 AddToWorklist(X.getNode());
7481 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7482 AddToWorklist(X.getNode());
7485 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7486 APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2);
7487 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0.getOperand(0)), VT,
7489 AddToWorklist(Cst.getNode());
7490 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0.getOperand(1)), VT,
7492 AddToWorklist(X.getNode());
7493 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
7494 AddToWorklist(XorResult.getNode());
7495 SDValue XorResult64 = DAG.getNode(
7496 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
7497 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7499 AddToWorklist(XorResult64.getNode());
7501 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
7502 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
7503 AddToWorklist(FlipBit.getNode());
7505 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7506 AddToWorklist(FlipBits.getNode());
7507 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
7509 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7510 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7511 X, DAG.getConstant(SignBit, SDLoc(X), VT));
7512 AddToWorklist(X.getNode());
7514 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7515 VT, N0.getOperand(0));
7516 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7517 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7518 AddToWorklist(Cst.getNode());
7520 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7524 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7525 if (N0.getOpcode() == ISD::BUILD_PAIR)
7526 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7529 // Remove double bitcasts from shuffles - this is often a legacy of
7530 // XformToShuffleWithZero being used to combine bitmaskings (of
7531 // float vectors bitcast to integer vectors) into shuffles.
7532 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7533 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7534 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7535 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7536 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7537 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7539 // If operands are a bitcast, peek through if it casts the original VT.
7540 // If operands are a constant, just bitcast back to original VT.
7541 auto PeekThroughBitcast = [&](SDValue Op) {
7542 if (Op.getOpcode() == ISD::BITCAST &&
7543 Op.getOperand(0).getValueType() == VT)
7544 return SDValue(Op.getOperand(0));
7545 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7546 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7547 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7551 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7552 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7557 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7558 SmallVector<int, 8> NewMask;
7559 for (int M : SVN->getMask())
7560 for (int i = 0; i != MaskScale; ++i)
7561 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7563 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7565 std::swap(SV0, SV1);
7566 ShuffleVectorSDNode::commuteMask(NewMask);
7567 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7571 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7577 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7578 EVT VT = N->getValueType(0);
7579 return CombineConsecutiveLoads(N, VT);
7582 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7583 /// operands. DstEltVT indicates the destination element value type.
7584 SDValue DAGCombiner::
7585 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7586 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7588 // If this is already the right type, we're done.
7589 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7591 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7592 unsigned DstBitSize = DstEltVT.getSizeInBits();
7594 // If this is a conversion of N elements of one type to N elements of another
7595 // type, convert each element. This handles FP<->INT cases.
7596 if (SrcBitSize == DstBitSize) {
7597 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7598 BV->getValueType(0).getVectorNumElements());
7600 // Due to the FP element handling below calling this routine recursively,
7601 // we can end up with a scalar-to-vector node here.
7602 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7603 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7604 DAG.getNode(ISD::BITCAST, SDLoc(BV),
7605 DstEltVT, BV->getOperand(0)));
7607 SmallVector<SDValue, 8> Ops;
7608 for (SDValue Op : BV->op_values()) {
7609 // If the vector element type is not legal, the BUILD_VECTOR operands
7610 // are promoted and implicitly truncated. Make that explicit here.
7611 if (Op.getValueType() != SrcEltVT)
7612 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7613 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7615 AddToWorklist(Ops.back().getNode());
7617 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7620 // Otherwise, we're growing or shrinking the elements. To avoid having to
7621 // handle annoying details of growing/shrinking FP values, we convert them to
7623 if (SrcEltVT.isFloatingPoint()) {
7624 // Convert the input float vector to a int vector where the elements are the
7626 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7627 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7631 // Now we know the input is an integer vector. If the output is a FP type,
7632 // convert to integer first, then to FP of the right size.
7633 if (DstEltVT.isFloatingPoint()) {
7634 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7635 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7637 // Next, convert to FP elements of the same size.
7638 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7643 // Okay, we know the src/dst types are both integers of differing types.
7644 // Handling growing first.
7645 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7646 if (SrcBitSize < DstBitSize) {
7647 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7649 SmallVector<SDValue, 8> Ops;
7650 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7651 i += NumInputsPerOutput) {
7652 bool isLE = DAG.getDataLayout().isLittleEndian();
7653 APInt NewBits = APInt(DstBitSize, 0);
7654 bool EltIsUndef = true;
7655 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7656 // Shift the previously computed bits over.
7657 NewBits <<= SrcBitSize;
7658 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7659 if (Op.getOpcode() == ISD::UNDEF) continue;
7662 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7663 zextOrTrunc(SrcBitSize).zext(DstBitSize);
7667 Ops.push_back(DAG.getUNDEF(DstEltVT));
7669 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7672 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7673 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7676 // Finally, this must be the case where we are shrinking elements: each input
7677 // turns into multiple outputs.
7678 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7679 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7680 NumOutputsPerInput*BV->getNumOperands());
7681 SmallVector<SDValue, 8> Ops;
7683 for (const SDValue &Op : BV->op_values()) {
7684 if (Op.getOpcode() == ISD::UNDEF) {
7685 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7689 APInt OpVal = cast<ConstantSDNode>(Op)->
7690 getAPIntValue().zextOrTrunc(SrcBitSize);
7692 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7693 APInt ThisVal = OpVal.trunc(DstBitSize);
7694 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7695 OpVal = OpVal.lshr(DstBitSize);
7698 // For big endian targets, swap the order of the pieces of each element.
7699 if (DAG.getDataLayout().isBigEndian())
7700 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7703 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7706 /// Try to perform FMA combining on a given FADD node.
7707 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7708 SDValue N0 = N->getOperand(0);
7709 SDValue N1 = N->getOperand(1);
7710 EVT VT = N->getValueType(0);
7713 const TargetOptions &Options = DAG.getTarget().Options;
7715 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7717 // Floating-point multiply-add with intermediate rounding.
7718 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7720 // Floating-point multiply-add without intermediate rounding.
7722 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7723 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7725 // No valid opcode, do not combine.
7726 if (!HasFMAD && !HasFMA)
7729 // Always prefer FMAD to FMA for precision.
7730 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7731 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7732 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7734 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7735 // prefer to fold the multiply with fewer uses.
7736 if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7737 N1.getOpcode() == ISD::FMUL) {
7738 if (N0.getNode()->use_size() > N1.getNode()->use_size())
7742 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7743 if (N0.getOpcode() == ISD::FMUL &&
7744 (Aggressive || N0->hasOneUse())) {
7745 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7746 N0.getOperand(0), N0.getOperand(1), N1);
7749 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7750 // Note: Commutes FADD operands.
7751 if (N1.getOpcode() == ISD::FMUL &&
7752 (Aggressive || N1->hasOneUse())) {
7753 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7754 N1.getOperand(0), N1.getOperand(1), N0);
7757 // Look through FP_EXTEND nodes to do more combining.
7758 if (AllowFusion && LookThroughFPExt) {
7759 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7760 if (N0.getOpcode() == ISD::FP_EXTEND) {
7761 SDValue N00 = N0.getOperand(0);
7762 if (N00.getOpcode() == ISD::FMUL)
7763 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7764 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7766 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7767 N00.getOperand(1)), N1);
7770 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7771 // Note: Commutes FADD operands.
7772 if (N1.getOpcode() == ISD::FP_EXTEND) {
7773 SDValue N10 = N1.getOperand(0);
7774 if (N10.getOpcode() == ISD::FMUL)
7775 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7776 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7778 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7779 N10.getOperand(1)), N0);
7783 // More folding opportunities when target permits.
7784 if ((AllowFusion || HasFMAD) && Aggressive) {
7785 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7786 if (N0.getOpcode() == PreferredFusedOpcode &&
7787 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7788 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7789 N0.getOperand(0), N0.getOperand(1),
7790 DAG.getNode(PreferredFusedOpcode, SL, VT,
7791 N0.getOperand(2).getOperand(0),
7792 N0.getOperand(2).getOperand(1),
7796 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7797 if (N1->getOpcode() == PreferredFusedOpcode &&
7798 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7799 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7800 N1.getOperand(0), N1.getOperand(1),
7801 DAG.getNode(PreferredFusedOpcode, SL, VT,
7802 N1.getOperand(2).getOperand(0),
7803 N1.getOperand(2).getOperand(1),
7807 if (AllowFusion && LookThroughFPExt) {
7808 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7809 // -> (fma x, y, (fma (fpext u), (fpext v), z))
7810 auto FoldFAddFMAFPExtFMul = [&] (
7811 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7812 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7813 DAG.getNode(PreferredFusedOpcode, SL, VT,
7814 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7815 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7818 if (N0.getOpcode() == PreferredFusedOpcode) {
7819 SDValue N02 = N0.getOperand(2);
7820 if (N02.getOpcode() == ISD::FP_EXTEND) {
7821 SDValue N020 = N02.getOperand(0);
7822 if (N020.getOpcode() == ISD::FMUL)
7823 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7824 N020.getOperand(0), N020.getOperand(1),
7829 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7830 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7831 // FIXME: This turns two single-precision and one double-precision
7832 // operation into two double-precision operations, which might not be
7833 // interesting for all targets, especially GPUs.
7834 auto FoldFAddFPExtFMAFMul = [&] (
7835 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7836 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7837 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7838 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7839 DAG.getNode(PreferredFusedOpcode, SL, VT,
7840 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7841 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7844 if (N0.getOpcode() == ISD::FP_EXTEND) {
7845 SDValue N00 = N0.getOperand(0);
7846 if (N00.getOpcode() == PreferredFusedOpcode) {
7847 SDValue N002 = N00.getOperand(2);
7848 if (N002.getOpcode() == ISD::FMUL)
7849 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7850 N002.getOperand(0), N002.getOperand(1),
7855 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7856 // -> (fma y, z, (fma (fpext u), (fpext v), x))
7857 if (N1.getOpcode() == PreferredFusedOpcode) {
7858 SDValue N12 = N1.getOperand(2);
7859 if (N12.getOpcode() == ISD::FP_EXTEND) {
7860 SDValue N120 = N12.getOperand(0);
7861 if (N120.getOpcode() == ISD::FMUL)
7862 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7863 N120.getOperand(0), N120.getOperand(1),
7868 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7869 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7870 // FIXME: This turns two single-precision and one double-precision
7871 // operation into two double-precision operations, which might not be
7872 // interesting for all targets, especially GPUs.
7873 if (N1.getOpcode() == ISD::FP_EXTEND) {
7874 SDValue N10 = N1.getOperand(0);
7875 if (N10.getOpcode() == PreferredFusedOpcode) {
7876 SDValue N102 = N10.getOperand(2);
7877 if (N102.getOpcode() == ISD::FMUL)
7878 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7879 N102.getOperand(0), N102.getOperand(1),
7889 /// Try to perform FMA combining on a given FSUB node.
7890 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7891 SDValue N0 = N->getOperand(0);
7892 SDValue N1 = N->getOperand(1);
7893 EVT VT = N->getValueType(0);
7896 const TargetOptions &Options = DAG.getTarget().Options;
7898 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7900 // Floating-point multiply-add with intermediate rounding.
7901 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7903 // Floating-point multiply-add without intermediate rounding.
7905 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7906 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7908 // No valid opcode, do not combine.
7909 if (!HasFMAD && !HasFMA)
7912 // Always prefer FMAD to FMA for precision.
7913 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7914 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7915 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7917 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7918 if (N0.getOpcode() == ISD::FMUL &&
7919 (Aggressive || N0->hasOneUse())) {
7920 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7921 N0.getOperand(0), N0.getOperand(1),
7922 DAG.getNode(ISD::FNEG, SL, VT, N1));
7925 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7926 // Note: Commutes FSUB operands.
7927 if (N1.getOpcode() == ISD::FMUL &&
7928 (Aggressive || N1->hasOneUse()))
7929 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7930 DAG.getNode(ISD::FNEG, SL, VT,
7932 N1.getOperand(1), N0);
7934 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7935 if (N0.getOpcode() == ISD::FNEG &&
7936 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7937 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7938 SDValue N00 = N0.getOperand(0).getOperand(0);
7939 SDValue N01 = N0.getOperand(0).getOperand(1);
7940 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7941 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7942 DAG.getNode(ISD::FNEG, SL, VT, N1));
7945 // Look through FP_EXTEND nodes to do more combining.
7946 if (AllowFusion && LookThroughFPExt) {
7947 // fold (fsub (fpext (fmul x, y)), z)
7948 // -> (fma (fpext x), (fpext y), (fneg z))
7949 if (N0.getOpcode() == ISD::FP_EXTEND) {
7950 SDValue N00 = N0.getOperand(0);
7951 if (N00.getOpcode() == ISD::FMUL)
7952 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7953 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7955 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7957 DAG.getNode(ISD::FNEG, SL, VT, N1));
7960 // fold (fsub x, (fpext (fmul y, z)))
7961 // -> (fma (fneg (fpext y)), (fpext z), x)
7962 // Note: Commutes FSUB operands.
7963 if (N1.getOpcode() == ISD::FP_EXTEND) {
7964 SDValue N10 = N1.getOperand(0);
7965 if (N10.getOpcode() == ISD::FMUL)
7966 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7967 DAG.getNode(ISD::FNEG, SL, VT,
7968 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7969 N10.getOperand(0))),
7970 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7975 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7976 // -> (fneg (fma (fpext x), (fpext y), z))
7977 // Note: This could be removed with appropriate canonicalization of the
7978 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7979 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7980 // from implementing the canonicalization in visitFSUB.
7981 if (N0.getOpcode() == ISD::FP_EXTEND) {
7982 SDValue N00 = N0.getOperand(0);
7983 if (N00.getOpcode() == ISD::FNEG) {
7984 SDValue N000 = N00.getOperand(0);
7985 if (N000.getOpcode() == ISD::FMUL) {
7986 return DAG.getNode(ISD::FNEG, SL, VT,
7987 DAG.getNode(PreferredFusedOpcode, SL, VT,
7988 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7989 N000.getOperand(0)),
7990 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7991 N000.getOperand(1)),
7997 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7998 // -> (fneg (fma (fpext x)), (fpext y), z)
7999 // Note: This could be removed with appropriate canonicalization of the
8000 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8001 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8002 // from implementing the canonicalization in visitFSUB.
8003 if (N0.getOpcode() == ISD::FNEG) {
8004 SDValue N00 = N0.getOperand(0);
8005 if (N00.getOpcode() == ISD::FP_EXTEND) {
8006 SDValue N000 = N00.getOperand(0);
8007 if (N000.getOpcode() == ISD::FMUL) {
8008 return DAG.getNode(ISD::FNEG, SL, VT,
8009 DAG.getNode(PreferredFusedOpcode, SL, VT,
8010 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8011 N000.getOperand(0)),
8012 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8013 N000.getOperand(1)),
8021 // More folding opportunities when target permits.
8022 if ((AllowFusion || HasFMAD) && Aggressive) {
8023 // fold (fsub (fma x, y, (fmul u, v)), z)
8024 // -> (fma x, y (fma u, v, (fneg z)))
8025 if (N0.getOpcode() == PreferredFusedOpcode &&
8026 N0.getOperand(2).getOpcode() == ISD::FMUL) {
8027 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8028 N0.getOperand(0), N0.getOperand(1),
8029 DAG.getNode(PreferredFusedOpcode, SL, VT,
8030 N0.getOperand(2).getOperand(0),
8031 N0.getOperand(2).getOperand(1),
8032 DAG.getNode(ISD::FNEG, SL, VT,
8036 // fold (fsub x, (fma y, z, (fmul u, v)))
8037 // -> (fma (fneg y), z, (fma (fneg u), v, x))
8038 if (N1.getOpcode() == PreferredFusedOpcode &&
8039 N1.getOperand(2).getOpcode() == ISD::FMUL) {
8040 SDValue N20 = N1.getOperand(2).getOperand(0);
8041 SDValue N21 = N1.getOperand(2).getOperand(1);
8042 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8043 DAG.getNode(ISD::FNEG, SL, VT,
8046 DAG.getNode(PreferredFusedOpcode, SL, VT,
8047 DAG.getNode(ISD::FNEG, SL, VT, N20),
8052 if (AllowFusion && LookThroughFPExt) {
8053 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
8054 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
8055 if (N0.getOpcode() == PreferredFusedOpcode) {
8056 SDValue N02 = N0.getOperand(2);
8057 if (N02.getOpcode() == ISD::FP_EXTEND) {
8058 SDValue N020 = N02.getOperand(0);
8059 if (N020.getOpcode() == ISD::FMUL)
8060 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8061 N0.getOperand(0), N0.getOperand(1),
8062 DAG.getNode(PreferredFusedOpcode, SL, VT,
8063 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8064 N020.getOperand(0)),
8065 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8066 N020.getOperand(1)),
8067 DAG.getNode(ISD::FNEG, SL, VT,
8072 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
8073 // -> (fma (fpext x), (fpext y),
8074 // (fma (fpext u), (fpext v), (fneg z)))
8075 // FIXME: This turns two single-precision and one double-precision
8076 // operation into two double-precision operations, which might not be
8077 // interesting for all targets, especially GPUs.
8078 if (N0.getOpcode() == ISD::FP_EXTEND) {
8079 SDValue N00 = N0.getOperand(0);
8080 if (N00.getOpcode() == PreferredFusedOpcode) {
8081 SDValue N002 = N00.getOperand(2);
8082 if (N002.getOpcode() == ISD::FMUL)
8083 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8084 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8086 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8088 DAG.getNode(PreferredFusedOpcode, SL, VT,
8089 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8090 N002.getOperand(0)),
8091 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8092 N002.getOperand(1)),
8093 DAG.getNode(ISD::FNEG, SL, VT,
8098 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
8099 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
8100 if (N1.getOpcode() == PreferredFusedOpcode &&
8101 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
8102 SDValue N120 = N1.getOperand(2).getOperand(0);
8103 if (N120.getOpcode() == ISD::FMUL) {
8104 SDValue N1200 = N120.getOperand(0);
8105 SDValue N1201 = N120.getOperand(1);
8106 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8107 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
8109 DAG.getNode(PreferredFusedOpcode, SL, VT,
8110 DAG.getNode(ISD::FNEG, SL, VT,
8111 DAG.getNode(ISD::FP_EXTEND, SL,
8113 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8119 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
8120 // -> (fma (fneg (fpext y)), (fpext z),
8121 // (fma (fneg (fpext u)), (fpext v), x))
8122 // FIXME: This turns two single-precision and one double-precision
8123 // operation into two double-precision operations, which might not be
8124 // interesting for all targets, especially GPUs.
8125 if (N1.getOpcode() == ISD::FP_EXTEND &&
8126 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
8127 SDValue N100 = N1.getOperand(0).getOperand(0);
8128 SDValue N101 = N1.getOperand(0).getOperand(1);
8129 SDValue N102 = N1.getOperand(0).getOperand(2);
8130 if (N102.getOpcode() == ISD::FMUL) {
8131 SDValue N1020 = N102.getOperand(0);
8132 SDValue N1021 = N102.getOperand(1);
8133 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8134 DAG.getNode(ISD::FNEG, SL, VT,
8135 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8137 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
8138 DAG.getNode(PreferredFusedOpcode, SL, VT,
8139 DAG.getNode(ISD::FNEG, SL, VT,
8140 DAG.getNode(ISD::FP_EXTEND, SL,
8142 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8153 /// Try to perform FMA combining on a given FMUL node.
8154 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
8155 SDValue N0 = N->getOperand(0);
8156 SDValue N1 = N->getOperand(1);
8157 EVT VT = N->getValueType(0);
8160 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
8162 const TargetOptions &Options = DAG.getTarget().Options;
8164 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8166 // Floating-point multiply-add with intermediate rounding.
8167 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8169 // Floating-point multiply-add without intermediate rounding.
8171 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8172 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8174 // No valid opcode, do not combine.
8175 if (!HasFMAD && !HasFMA)
8178 // Always prefer FMAD to FMA for precision.
8179 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8180 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8182 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
8183 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
8184 auto FuseFADD = [&](SDValue X, SDValue Y) {
8185 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
8186 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8187 if (XC1 && XC1->isExactlyValue(+1.0))
8188 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8189 if (XC1 && XC1->isExactlyValue(-1.0))
8190 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8191 DAG.getNode(ISD::FNEG, SL, VT, Y));
8196 if (SDValue FMA = FuseFADD(N0, N1))
8198 if (SDValue FMA = FuseFADD(N1, N0))
8201 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
8202 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
8203 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
8204 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
8205 auto FuseFSUB = [&](SDValue X, SDValue Y) {
8206 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
8207 auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
8208 if (XC0 && XC0->isExactlyValue(+1.0))
8209 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8210 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8212 if (XC0 && XC0->isExactlyValue(-1.0))
8213 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8214 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8215 DAG.getNode(ISD::FNEG, SL, VT, Y));
8217 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8218 if (XC1 && XC1->isExactlyValue(+1.0))
8219 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8220 DAG.getNode(ISD::FNEG, SL, VT, Y));
8221 if (XC1 && XC1->isExactlyValue(-1.0))
8222 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8227 if (SDValue FMA = FuseFSUB(N0, N1))
8229 if (SDValue FMA = FuseFSUB(N1, N0))
8235 SDValue DAGCombiner::visitFADD(SDNode *N) {
8236 SDValue N0 = N->getOperand(0);
8237 SDValue N1 = N->getOperand(1);
8238 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
8239 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8240 EVT VT = N->getValueType(0);
8242 const TargetOptions &Options = DAG.getTarget().Options;
8243 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8247 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8250 // fold (fadd c1, c2) -> c1 + c2
8252 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8254 // canonicalize constant to RHS
8255 if (N0CFP && !N1CFP)
8256 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8258 // fold (fadd A, (fneg B)) -> (fsub A, B)
8259 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8260 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8261 return DAG.getNode(ISD::FSUB, DL, VT, N0,
8262 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8264 // fold (fadd (fneg A), B) -> (fsub B, A)
8265 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8266 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8267 return DAG.getNode(ISD::FSUB, DL, VT, N1,
8268 GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8270 // If 'unsafe math' is enabled, fold lots of things.
8271 if (Options.UnsafeFPMath) {
8272 // No FP constant should be created after legalization as Instruction
8273 // Selection pass has a hard time dealing with FP constants.
8274 bool AllowNewConst = (Level < AfterLegalizeDAG);
8276 // fold (fadd A, 0) -> A
8277 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8281 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8282 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8283 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8284 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8285 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8289 // If allowed, fold (fadd (fneg x), x) -> 0.0
8290 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8291 return DAG.getConstantFP(0.0, DL, VT);
8293 // If allowed, fold (fadd x, (fneg x)) -> 0.0
8294 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8295 return DAG.getConstantFP(0.0, DL, VT);
8297 // We can fold chains of FADD's of the same value into multiplications.
8298 // This transform is not safe in general because we are reducing the number
8299 // of rounding steps.
8300 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8301 if (N0.getOpcode() == ISD::FMUL) {
8302 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8303 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8305 // (fadd (fmul x, c), x) -> (fmul x, c+1)
8306 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8307 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8308 DAG.getConstantFP(1.0, DL, VT), Flags);
8309 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8312 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8313 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8314 N1.getOperand(0) == N1.getOperand(1) &&
8315 N0.getOperand(0) == N1.getOperand(0)) {
8316 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8317 DAG.getConstantFP(2.0, DL, VT), Flags);
8318 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8322 if (N1.getOpcode() == ISD::FMUL) {
8323 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8324 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8326 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8327 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8328 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8329 DAG.getConstantFP(1.0, DL, VT), Flags);
8330 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8333 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8334 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8335 N0.getOperand(0) == N0.getOperand(1) &&
8336 N1.getOperand(0) == N0.getOperand(0)) {
8337 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8338 DAG.getConstantFP(2.0, DL, VT), Flags);
8339 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8343 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8344 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8345 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8346 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8347 (N0.getOperand(0) == N1)) {
8348 return DAG.getNode(ISD::FMUL, DL, VT,
8349 N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8353 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8354 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8355 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8356 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8357 N1.getOperand(0) == N0) {
8358 return DAG.getNode(ISD::FMUL, DL, VT,
8359 N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8363 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8364 if (AllowNewConst &&
8365 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8366 N0.getOperand(0) == N0.getOperand(1) &&
8367 N1.getOperand(0) == N1.getOperand(1) &&
8368 N0.getOperand(0) == N1.getOperand(0)) {
8369 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8370 DAG.getConstantFP(4.0, DL, VT), Flags);
8373 } // enable-unsafe-fp-math
8375 // FADD -> FMA combines:
8376 if (SDValue Fused = visitFADDForFMACombine(N)) {
8377 AddToWorklist(Fused.getNode());
8384 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8385 SDValue N0 = N->getOperand(0);
8386 SDValue N1 = N->getOperand(1);
8387 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8388 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8389 EVT VT = N->getValueType(0);
8391 const TargetOptions &Options = DAG.getTarget().Options;
8392 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8396 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8399 // fold (fsub c1, c2) -> c1-c2
8401 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags);
8403 // fold (fsub A, (fneg B)) -> (fadd A, B)
8404 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8405 return DAG.getNode(ISD::FADD, dl, VT, N0,
8406 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8408 // If 'unsafe math' is enabled, fold lots of things.
8409 if (Options.UnsafeFPMath) {
8411 if (N1CFP && N1CFP->isZero())
8414 // (fsub 0, B) -> -B
8415 if (N0CFP && N0CFP->isZero()) {
8416 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8417 return GetNegatedExpression(N1, DAG, LegalOperations);
8418 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8419 return DAG.getNode(ISD::FNEG, dl, VT, N1);
8422 // (fsub x, x) -> 0.0
8424 return DAG.getConstantFP(0.0f, dl, VT);
8426 // (fsub x, (fadd x, y)) -> (fneg y)
8427 // (fsub x, (fadd y, x)) -> (fneg y)
8428 if (N1.getOpcode() == ISD::FADD) {
8429 SDValue N10 = N1->getOperand(0);
8430 SDValue N11 = N1->getOperand(1);
8432 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8433 return GetNegatedExpression(N11, DAG, LegalOperations);
8435 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8436 return GetNegatedExpression(N10, DAG, LegalOperations);
8440 // FSUB -> FMA combines:
8441 if (SDValue Fused = visitFSUBForFMACombine(N)) {
8442 AddToWorklist(Fused.getNode());
8449 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8450 SDValue N0 = N->getOperand(0);
8451 SDValue N1 = N->getOperand(1);
8452 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8453 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8454 EVT VT = N->getValueType(0);
8456 const TargetOptions &Options = DAG.getTarget().Options;
8457 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8460 if (VT.isVector()) {
8461 // This just handles C1 * C2 for vectors. Other vector folds are below.
8462 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8466 // fold (fmul c1, c2) -> c1*c2
8468 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8470 // canonicalize constant to RHS
8471 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8472 !isConstantFPBuildVectorOrConstantFP(N1))
8473 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8475 // fold (fmul A, 1.0) -> A
8476 if (N1CFP && N1CFP->isExactlyValue(1.0))
8479 if (Options.UnsafeFPMath) {
8480 // fold (fmul A, 0) -> 0
8481 if (N1CFP && N1CFP->isZero())
8484 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8485 if (N0.getOpcode() == ISD::FMUL) {
8486 // Fold scalars or any vector constants (not just splats).
8487 // This fold is done in general by InstCombine, but extra fmul insts
8488 // may have been generated during lowering.
8489 SDValue N00 = N0.getOperand(0);
8490 SDValue N01 = N0.getOperand(1);
8491 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8492 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8493 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8495 // Check 1: Make sure that the first operand of the inner multiply is NOT
8496 // a constant. Otherwise, we may induce infinite looping.
8497 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8498 // Check 2: Make sure that the second operand of the inner multiply and
8499 // the second operand of the outer multiply are constants.
8500 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8501 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8502 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8503 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8508 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8509 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8510 // during an early run of DAGCombiner can prevent folding with fmuls
8511 // inserted during lowering.
8512 if (N0.getOpcode() == ISD::FADD &&
8513 (N0.getOperand(0) == N0.getOperand(1)) &&
8515 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8516 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8517 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8521 // fold (fmul X, 2.0) -> (fadd X, X)
8522 if (N1CFP && N1CFP->isExactlyValue(+2.0))
8523 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8525 // fold (fmul X, -1.0) -> (fneg X)
8526 if (N1CFP && N1CFP->isExactlyValue(-1.0))
8527 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8528 return DAG.getNode(ISD::FNEG, DL, VT, N0);
8530 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8531 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8532 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8533 // Both can be negated for free, check to see if at least one is cheaper
8535 if (LHSNeg == 2 || RHSNeg == 2)
8536 return DAG.getNode(ISD::FMUL, DL, VT,
8537 GetNegatedExpression(N0, DAG, LegalOperations),
8538 GetNegatedExpression(N1, DAG, LegalOperations),
8543 // FMUL -> FMA combines:
8544 if (SDValue Fused = visitFMULForFMACombine(N)) {
8545 AddToWorklist(Fused.getNode());
8552 SDValue DAGCombiner::visitFMA(SDNode *N) {
8553 SDValue N0 = N->getOperand(0);
8554 SDValue N1 = N->getOperand(1);
8555 SDValue N2 = N->getOperand(2);
8556 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8557 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8558 EVT VT = N->getValueType(0);
8560 const TargetOptions &Options = DAG.getTarget().Options;
8562 // Constant fold FMA.
8563 if (isa<ConstantFPSDNode>(N0) &&
8564 isa<ConstantFPSDNode>(N1) &&
8565 isa<ConstantFPSDNode>(N2)) {
8566 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8569 if (Options.UnsafeFPMath) {
8570 if (N0CFP && N0CFP->isZero())
8572 if (N1CFP && N1CFP->isZero())
8575 // TODO: The FMA node should have flags that propagate to these nodes.
8576 if (N0CFP && N0CFP->isExactlyValue(1.0))
8577 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8578 if (N1CFP && N1CFP->isExactlyValue(1.0))
8579 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8581 // Canonicalize (fma c, x, y) -> (fma x, c, y)
8582 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8583 !isConstantFPBuildVectorOrConstantFP(N1))
8584 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8586 // TODO: FMA nodes should have flags that propagate to the created nodes.
8587 // For now, create a Flags object for use with all unsafe math transforms.
8589 Flags.setUnsafeAlgebra(true);
8591 if (Options.UnsafeFPMath) {
8592 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8593 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8594 isConstantFPBuildVectorOrConstantFP(N1) &&
8595 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8596 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8597 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1),
8601 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8602 if (N0.getOpcode() == ISD::FMUL &&
8603 isConstantFPBuildVectorOrConstantFP(N1) &&
8604 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8605 return DAG.getNode(ISD::FMA, dl, VT,
8607 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1),
8613 // (fma x, 1, y) -> (fadd x, y)
8614 // (fma x, -1, y) -> (fadd (fneg x), y)
8616 if (N1CFP->isExactlyValue(1.0))
8617 // TODO: The FMA node should have flags that propagate to this node.
8618 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8620 if (N1CFP->isExactlyValue(-1.0) &&
8621 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8622 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8623 AddToWorklist(RHSNeg.getNode());
8624 // TODO: The FMA node should have flags that propagate to this node.
8625 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8629 if (Options.UnsafeFPMath) {
8630 // (fma x, c, x) -> (fmul x, (c+1))
8631 if (N1CFP && N0 == N2) {
8632 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8633 DAG.getNode(ISD::FADD, dl, VT,
8634 N1, DAG.getConstantFP(1.0, dl, VT),
8638 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8639 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8640 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8641 DAG.getNode(ISD::FADD, dl, VT,
8642 N1, DAG.getConstantFP(-1.0, dl, VT),
8650 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8652 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8653 // Notice that this is not always beneficial. One reason is different target
8654 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8655 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8656 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8657 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8658 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
8659 const SDNodeFlags *Flags = N->getFlags();
8660 if (!UnsafeMath && !Flags->hasAllowReciprocal())
8663 // Skip if current node is a reciprocal.
8664 SDValue N0 = N->getOperand(0);
8665 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8666 if (N0CFP && N0CFP->isExactlyValue(1.0))
8669 // Exit early if the target does not want this transform or if there can't
8670 // possibly be enough uses of the divisor to make the transform worthwhile.
8671 SDValue N1 = N->getOperand(1);
8672 unsigned MinUses = TLI.combineRepeatedFPDivisors();
8673 if (!MinUses || N1->use_size() < MinUses)
8676 // Find all FDIV users of the same divisor.
8677 // Use a set because duplicates may be present in the user list.
8678 SetVector<SDNode *> Users;
8679 for (auto *U : N1->uses()) {
8680 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
8681 // This division is eligible for optimization only if global unsafe math
8682 // is enabled or if this division allows reciprocal formation.
8683 if (UnsafeMath || U->getFlags()->hasAllowReciprocal())
8688 // Now that we have the actual number of divisor uses, make sure it meets
8689 // the minimum threshold specified by the target.
8690 if (Users.size() < MinUses)
8693 EVT VT = N->getValueType(0);
8695 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8696 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8698 // Dividend / Divisor -> Dividend * Reciprocal
8699 for (auto *U : Users) {
8700 SDValue Dividend = U->getOperand(0);
8701 if (Dividend != FPOne) {
8702 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8704 CombineTo(U, NewNode);
8705 } else if (U != Reciprocal.getNode()) {
8706 // In the absence of fast-math-flags, this user node is always the
8707 // same node as Reciprocal, but with FMF they may be different nodes.
8708 CombineTo(U, Reciprocal);
8711 return SDValue(N, 0); // N was replaced.
8714 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8715 SDValue N0 = N->getOperand(0);
8716 SDValue N1 = N->getOperand(1);
8717 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8718 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8719 EVT VT = N->getValueType(0);
8721 const TargetOptions &Options = DAG.getTarget().Options;
8722 SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8726 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8729 // fold (fdiv c1, c2) -> c1/c2
8731 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8733 if (Options.UnsafeFPMath) {
8734 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8736 // Compute the reciprocal 1.0 / c2.
8737 APFloat N1APF = N1CFP->getValueAPF();
8738 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8739 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8740 // Only do the transform if the reciprocal is a legal fp immediate that
8741 // isn't too nasty (eg NaN, denormal, ...).
8742 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8743 (!LegalOperations ||
8744 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8745 // backend)... we should handle this gracefully after Legalize.
8746 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8747 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8748 TLI.isFPImmLegal(Recip, VT)))
8749 return DAG.getNode(ISD::FMUL, DL, VT, N0,
8750 DAG.getConstantFP(Recip, DL, VT), Flags);
8753 // If this FDIV is part of a reciprocal square root, it may be folded
8754 // into a target-specific square root estimate instruction.
8755 if (N1.getOpcode() == ISD::FSQRT) {
8756 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) {
8757 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8759 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8760 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8761 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8763 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8764 AddToWorklist(RV.getNode());
8765 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8767 } else if (N1.getOpcode() == ISD::FP_ROUND &&
8768 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8769 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8771 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8772 AddToWorklist(RV.getNode());
8773 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8775 } else if (N1.getOpcode() == ISD::FMUL) {
8776 // Look through an FMUL. Even though this won't remove the FDIV directly,
8777 // it's still worthwhile to get rid of the FSQRT if possible.
8780 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8781 SqrtOp = N1.getOperand(0);
8782 OtherOp = N1.getOperand(1);
8783 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8784 SqrtOp = N1.getOperand(1);
8785 OtherOp = N1.getOperand(0);
8787 if (SqrtOp.getNode()) {
8788 // We found a FSQRT, so try to make this fold:
8789 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8790 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
8791 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
8792 AddToWorklist(RV.getNode());
8793 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8798 // Fold into a reciprocal estimate and multiply instead of a real divide.
8799 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
8800 AddToWorklist(RV.getNode());
8801 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8805 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8806 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8807 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8808 // Both can be negated for free, check to see if at least one is cheaper
8810 if (LHSNeg == 2 || RHSNeg == 2)
8811 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8812 GetNegatedExpression(N0, DAG, LegalOperations),
8813 GetNegatedExpression(N1, DAG, LegalOperations),
8818 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8819 return CombineRepeatedDivisors;
8824 SDValue DAGCombiner::visitFREM(SDNode *N) {
8825 SDValue N0 = N->getOperand(0);
8826 SDValue N1 = N->getOperand(1);
8827 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8828 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8829 EVT VT = N->getValueType(0);
8831 // fold (frem c1, c2) -> fmod(c1,c2)
8833 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
8834 &cast<BinaryWithFlagsSDNode>(N)->Flags);
8839 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8840 if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8843 // TODO: FSQRT nodes should have flags that propagate to the created nodes.
8844 // For now, create a Flags object for use with all unsafe math transforms.
8846 Flags.setUnsafeAlgebra(true);
8848 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8849 SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags);
8853 EVT VT = RV.getValueType();
8855 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags);
8856 AddToWorklist(RV.getNode());
8858 // Unfortunately, RV is now NaN if the input was exactly 0.
8859 // Select out this case and force the answer to 0.
8860 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8861 EVT CCVT = getSetCCResultType(VT);
8862 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8863 AddToWorklist(ZeroCmp.getNode());
8864 AddToWorklist(RV.getNode());
8866 return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8870 /// copysign(x, fp_extend(y)) -> copysign(x, y)
8871 /// copysign(x, fp_round(y)) -> copysign(x, y)
8872 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
8873 SDValue N1 = N->getOperand(1);
8874 if ((N1.getOpcode() == ISD::FP_EXTEND ||
8875 N1.getOpcode() == ISD::FP_ROUND)) {
8876 // Do not optimize out type conversion of f128 type yet.
8877 // For some targets like x86_64, configuration is changed to keep one f128
8878 // value in one SSE register, but instruction selection cannot handle
8879 // FCOPYSIGN on SSE registers yet.
8880 EVT N1VT = N1->getValueType(0);
8881 EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
8882 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
8887 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8888 SDValue N0 = N->getOperand(0);
8889 SDValue N1 = N->getOperand(1);
8890 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8891 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8892 EVT VT = N->getValueType(0);
8894 if (N0CFP && N1CFP) // Constant fold
8895 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8898 const APFloat& V = N1CFP->getValueAPF();
8899 // copysign(x, c1) -> fabs(x) iff ispos(c1)
8900 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8901 if (!V.isNegative()) {
8902 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8903 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8905 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8906 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8907 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8911 // copysign(fabs(x), y) -> copysign(x, y)
8912 // copysign(fneg(x), y) -> copysign(x, y)
8913 // copysign(copysign(x,z), y) -> copysign(x, y)
8914 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8915 N0.getOpcode() == ISD::FCOPYSIGN)
8916 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8917 N0.getOperand(0), N1);
8919 // copysign(x, abs(y)) -> abs(x)
8920 if (N1.getOpcode() == ISD::FABS)
8921 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8923 // copysign(x, copysign(y,z)) -> copysign(x, z)
8924 if (N1.getOpcode() == ISD::FCOPYSIGN)
8925 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8926 N0, N1.getOperand(1));
8928 // copysign(x, fp_extend(y)) -> copysign(x, y)
8929 // copysign(x, fp_round(y)) -> copysign(x, y)
8930 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
8931 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8932 N0, N1.getOperand(0));
8937 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8938 SDValue N0 = N->getOperand(0);
8939 EVT VT = N->getValueType(0);
8940 EVT OpVT = N0.getValueType();
8942 // fold (sint_to_fp c1) -> c1fp
8943 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8944 // ...but only if the target supports immediate floating-point values
8945 (!LegalOperations ||
8946 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8947 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8949 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8950 // but UINT_TO_FP is legal on this target, try to convert.
8951 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8952 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8953 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8954 if (DAG.SignBitIsZero(N0))
8955 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8958 // The next optimizations are desirable only if SELECT_CC can be lowered.
8959 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8960 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8961 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8963 (!LegalOperations ||
8964 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8967 { N0.getOperand(0), N0.getOperand(1),
8968 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8970 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8973 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8974 // (select_cc x, y, 1.0, 0.0,, cc)
8975 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8976 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8977 (!LegalOperations ||
8978 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8981 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8982 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8983 N0.getOperand(0).getOperand(2) };
8984 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8991 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8992 SDValue N0 = N->getOperand(0);
8993 EVT VT = N->getValueType(0);
8994 EVT OpVT = N0.getValueType();
8996 // fold (uint_to_fp c1) -> c1fp
8997 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8998 // ...but only if the target supports immediate floating-point values
8999 (!LegalOperations ||
9000 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9001 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
9003 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
9004 // but SINT_TO_FP is legal on this target, try to convert.
9005 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
9006 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
9007 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
9008 if (DAG.SignBitIsZero(N0))
9009 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9012 // The next optimizations are desirable only if SELECT_CC can be lowered.
9013 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9014 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9016 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
9017 (!LegalOperations ||
9018 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9021 { N0.getOperand(0), N0.getOperand(1),
9022 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9024 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9031 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
9032 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
9033 SDValue N0 = N->getOperand(0);
9034 EVT VT = N->getValueType(0);
9036 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
9039 SDValue Src = N0.getOperand(0);
9040 EVT SrcVT = Src.getValueType();
9041 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
9042 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
9044 // We can safely assume the conversion won't overflow the output range,
9045 // because (for example) (uint8_t)18293.f is undefined behavior.
9047 // Since we can assume the conversion won't overflow, our decision as to
9048 // whether the input will fit in the float should depend on the minimum
9049 // of the input range and output range.
9051 // This means this is also safe for a signed input and unsigned output, since
9052 // a negative input would lead to undefined behavior.
9053 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
9054 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
9055 unsigned ActualSize = std::min(InputSize, OutputSize);
9056 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
9058 // We can only fold away the float conversion if the input range can be
9059 // represented exactly in the float range.
9060 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
9061 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
9062 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
9064 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
9066 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
9067 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
9070 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
9075 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
9076 SDValue N0 = N->getOperand(0);
9077 EVT VT = N->getValueType(0);
9079 // fold (fp_to_sint c1fp) -> c1
9080 if (isConstantFPBuildVectorOrConstantFP(N0))
9081 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
9083 return FoldIntToFPToInt(N, DAG);
9086 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
9087 SDValue N0 = N->getOperand(0);
9088 EVT VT = N->getValueType(0);
9090 // fold (fp_to_uint c1fp) -> c1
9091 if (isConstantFPBuildVectorOrConstantFP(N0))
9092 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
9094 return FoldIntToFPToInt(N, DAG);
9097 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
9098 SDValue N0 = N->getOperand(0);
9099 SDValue N1 = N->getOperand(1);
9100 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9101 EVT VT = N->getValueType(0);
9103 // fold (fp_round c1fp) -> c1fp
9105 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
9107 // fold (fp_round (fp_extend x)) -> x
9108 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
9109 return N0.getOperand(0);
9111 // fold (fp_round (fp_round x)) -> (fp_round x)
9112 if (N0.getOpcode() == ISD::FP_ROUND) {
9113 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
9114 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
9115 // If the first fp_round isn't a value preserving truncation, it might
9116 // introduce a tie in the second fp_round, that wouldn't occur in the
9117 // single-step fp_round we want to fold to.
9118 // In other words, double rounding isn't the same as rounding.
9119 // Also, this is a value preserving truncation iff both fp_round's are.
9120 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
9122 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
9123 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
9127 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
9128 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
9129 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
9130 N0.getOperand(0), N1);
9131 AddToWorklist(Tmp.getNode());
9132 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
9133 Tmp, N0.getOperand(1));
9139 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
9140 SDValue N0 = N->getOperand(0);
9141 EVT VT = N->getValueType(0);
9142 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
9143 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9145 // fold (fp_round_inreg c1fp) -> c1fp
9146 if (N0CFP && isTypeLegal(EVT)) {
9148 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
9149 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
9155 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
9156 SDValue N0 = N->getOperand(0);
9157 EVT VT = N->getValueType(0);
9159 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
9160 if (N->hasOneUse() &&
9161 N->use_begin()->getOpcode() == ISD::FP_ROUND)
9164 // fold (fp_extend c1fp) -> c1fp
9165 if (isConstantFPBuildVectorOrConstantFP(N0))
9166 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
9168 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
9169 if (N0.getOpcode() == ISD::FP16_TO_FP &&
9170 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
9171 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
9173 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
9175 if (N0.getOpcode() == ISD::FP_ROUND
9176 && N0.getNode()->getConstantOperandVal(1) == 1) {
9177 SDValue In = N0.getOperand(0);
9178 if (In.getValueType() == VT) return In;
9179 if (VT.bitsLT(In.getValueType()))
9180 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
9181 In, N0.getOperand(1));
9182 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
9185 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
9186 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9187 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
9188 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9189 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
9191 LN0->getBasePtr(), N0.getValueType(),
9192 LN0->getMemOperand());
9193 CombineTo(N, ExtLoad);
9194 CombineTo(N0.getNode(),
9195 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
9196 N0.getValueType(), ExtLoad,
9197 DAG.getIntPtrConstant(1, SDLoc(N0))),
9198 ExtLoad.getValue(1));
9199 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9205 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
9206 SDValue N0 = N->getOperand(0);
9207 EVT VT = N->getValueType(0);
9209 // fold (fceil c1) -> fceil(c1)
9210 if (isConstantFPBuildVectorOrConstantFP(N0))
9211 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
9216 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
9217 SDValue N0 = N->getOperand(0);
9218 EVT VT = N->getValueType(0);
9220 // fold (ftrunc c1) -> ftrunc(c1)
9221 if (isConstantFPBuildVectorOrConstantFP(N0))
9222 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
9227 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
9228 SDValue N0 = N->getOperand(0);
9229 EVT VT = N->getValueType(0);
9231 // fold (ffloor c1) -> ffloor(c1)
9232 if (isConstantFPBuildVectorOrConstantFP(N0))
9233 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
9238 // FIXME: FNEG and FABS have a lot in common; refactor.
9239 SDValue DAGCombiner::visitFNEG(SDNode *N) {
9240 SDValue N0 = N->getOperand(0);
9241 EVT VT = N->getValueType(0);
9243 // Constant fold FNEG.
9244 if (isConstantFPBuildVectorOrConstantFP(N0))
9245 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
9247 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
9248 &DAG.getTarget().Options))
9249 return GetNegatedExpression(N0, DAG, LegalOperations);
9251 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
9252 // constant pool values.
9253 if (!TLI.isFNegFree(VT) &&
9254 N0.getOpcode() == ISD::BITCAST &&
9255 N0.getNode()->hasOneUse()) {
9256 SDValue Int = N0.getOperand(0);
9257 EVT IntVT = Int.getValueType();
9258 if (IntVT.isInteger() && !IntVT.isVector()) {
9260 if (N0.getValueType().isVector()) {
9261 // For a vector, get a mask such as 0x80... per scalar element
9263 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9264 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9266 // For a scalar, just generate 0x80...
9267 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
9270 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9271 DAG.getConstant(SignMask, DL0, IntVT));
9272 AddToWorklist(Int.getNode());
9273 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
9277 // (fneg (fmul c, x)) -> (fmul -c, x)
9278 if (N0.getOpcode() == ISD::FMUL &&
9279 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9280 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9282 APFloat CVal = CFP1->getValueAPF();
9284 if (Level >= AfterLegalizeDAG &&
9285 (TLI.isFPImmLegal(CVal, VT) ||
9286 TLI.isOperationLegal(ISD::ConstantFP, VT)))
9287 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9288 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9290 &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9297 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
9298 SDValue N0 = N->getOperand(0);
9299 SDValue N1 = N->getOperand(1);
9300 EVT VT = N->getValueType(0);
9301 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9302 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9304 if (N0CFP && N1CFP) {
9305 const APFloat &C0 = N0CFP->getValueAPF();
9306 const APFloat &C1 = N1CFP->getValueAPF();
9307 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9310 // Canonicalize to constant on RHS.
9311 if (isConstantFPBuildVectorOrConstantFP(N0) &&
9312 !isConstantFPBuildVectorOrConstantFP(N1))
9313 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9318 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9319 SDValue N0 = N->getOperand(0);
9320 SDValue N1 = N->getOperand(1);
9321 EVT VT = N->getValueType(0);
9322 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9323 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9325 if (N0CFP && N1CFP) {
9326 const APFloat &C0 = N0CFP->getValueAPF();
9327 const APFloat &C1 = N1CFP->getValueAPF();
9328 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9331 // Canonicalize to constant on RHS.
9332 if (isConstantFPBuildVectorOrConstantFP(N0) &&
9333 !isConstantFPBuildVectorOrConstantFP(N1))
9334 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9339 SDValue DAGCombiner::visitFABS(SDNode *N) {
9340 SDValue N0 = N->getOperand(0);
9341 EVT VT = N->getValueType(0);
9343 // fold (fabs c1) -> fabs(c1)
9344 if (isConstantFPBuildVectorOrConstantFP(N0))
9345 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9347 // fold (fabs (fabs x)) -> (fabs x)
9348 if (N0.getOpcode() == ISD::FABS)
9349 return N->getOperand(0);
9351 // fold (fabs (fneg x)) -> (fabs x)
9352 // fold (fabs (fcopysign x, y)) -> (fabs x)
9353 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9354 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9356 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9357 // constant pool values.
9358 if (!TLI.isFAbsFree(VT) &&
9359 N0.getOpcode() == ISD::BITCAST &&
9360 N0.getNode()->hasOneUse()) {
9361 SDValue Int = N0.getOperand(0);
9362 EVT IntVT = Int.getValueType();
9363 if (IntVT.isInteger() && !IntVT.isVector()) {
9365 if (N0.getValueType().isVector()) {
9366 // For a vector, get a mask such as 0x7f... per scalar element
9368 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9369 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9371 // For a scalar, just generate 0x7f...
9372 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9375 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9376 DAG.getConstant(SignMask, DL, IntVT));
9377 AddToWorklist(Int.getNode());
9378 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
9385 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9386 SDValue Chain = N->getOperand(0);
9387 SDValue N1 = N->getOperand(1);
9388 SDValue N2 = N->getOperand(2);
9390 // If N is a constant we could fold this into a fallthrough or unconditional
9391 // branch. However that doesn't happen very often in normal code, because
9392 // Instcombine/SimplifyCFG should have handled the available opportunities.
9393 // If we did this folding here, it would be necessary to update the
9394 // MachineBasicBlock CFG, which is awkward.
9396 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9398 if (N1.getOpcode() == ISD::SETCC &&
9399 TLI.isOperationLegalOrCustom(ISD::BR_CC,
9400 N1.getOperand(0).getValueType())) {
9401 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9402 Chain, N1.getOperand(2),
9403 N1.getOperand(0), N1.getOperand(1), N2);
9406 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9407 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9408 (N1.getOperand(0).hasOneUse() &&
9409 N1.getOperand(0).getOpcode() == ISD::SRL))) {
9410 SDNode *Trunc = nullptr;
9411 if (N1.getOpcode() == ISD::TRUNCATE) {
9412 // Look pass the truncate.
9413 Trunc = N1.getNode();
9414 N1 = N1.getOperand(0);
9417 // Match this pattern so that we can generate simpler code:
9420 // %b = and i32 %a, 2
9421 // %c = srl i32 %b, 1
9422 // brcond i32 %c ...
9427 // %b = and i32 %a, 2
9428 // %c = setcc eq %b, 0
9431 // This applies only when the AND constant value has one bit set and the
9432 // SRL constant is equal to the log2 of the AND constant. The back-end is
9433 // smart enough to convert the result into a TEST/JMP sequence.
9434 SDValue Op0 = N1.getOperand(0);
9435 SDValue Op1 = N1.getOperand(1);
9437 if (Op0.getOpcode() == ISD::AND &&
9438 Op1.getOpcode() == ISD::Constant) {
9439 SDValue AndOp1 = Op0.getOperand(1);
9441 if (AndOp1.getOpcode() == ISD::Constant) {
9442 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9444 if (AndConst.isPowerOf2() &&
9445 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9449 getSetCCResultType(Op0.getValueType()),
9450 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9453 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9454 MVT::Other, Chain, SetCC, N2);
9455 // Don't add the new BRCond into the worklist or else SimplifySelectCC
9456 // will convert it back to (X & C1) >> C2.
9457 CombineTo(N, NewBRCond, false);
9458 // Truncate is dead.
9460 deleteAndRecombine(Trunc);
9461 // Replace the uses of SRL with SETCC
9462 WorklistRemover DeadNodes(*this);
9463 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9464 deleteAndRecombine(N1.getNode());
9465 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9471 // Restore N1 if the above transformation doesn't match.
9472 N1 = N->getOperand(1);
9475 // Transform br(xor(x, y)) -> br(x != y)
9476 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9477 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9478 SDNode *TheXor = N1.getNode();
9479 SDValue Op0 = TheXor->getOperand(0);
9480 SDValue Op1 = TheXor->getOperand(1);
9481 if (Op0.getOpcode() == Op1.getOpcode()) {
9482 // Avoid missing important xor optimizations.
9483 if (SDValue Tmp = visitXOR(TheXor)) {
9484 if (Tmp.getNode() != TheXor) {
9485 DEBUG(dbgs() << "\nReplacing.8 ";
9487 dbgs() << "\nWith: ";
9488 Tmp.getNode()->dump(&DAG);
9490 WorklistRemover DeadNodes(*this);
9491 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9492 deleteAndRecombine(TheXor);
9493 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9494 MVT::Other, Chain, Tmp, N2);
9497 // visitXOR has changed XOR's operands or replaced the XOR completely,
9499 return SDValue(N, 0);
9503 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9505 if (isOneConstant(Op0) && Op0.hasOneUse() &&
9506 Op0.getOpcode() == ISD::XOR) {
9507 TheXor = Op0.getNode();
9511 EVT SetCCVT = N1.getValueType();
9513 SetCCVT = getSetCCResultType(SetCCVT);
9514 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9517 Equal ? ISD::SETEQ : ISD::SETNE);
9518 // Replace the uses of XOR with SETCC
9519 WorklistRemover DeadNodes(*this);
9520 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9521 deleteAndRecombine(N1.getNode());
9522 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9523 MVT::Other, Chain, SetCC, N2);
9530 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9532 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9533 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9534 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9536 // If N is a constant we could fold this into a fallthrough or unconditional
9537 // branch. However that doesn't happen very often in normal code, because
9538 // Instcombine/SimplifyCFG should have handled the available opportunities.
9539 // If we did this folding here, it would be necessary to update the
9540 // MachineBasicBlock CFG, which is awkward.
9542 // Use SimplifySetCC to simplify SETCC's.
9543 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9544 CondLHS, CondRHS, CC->get(), SDLoc(N),
9546 if (Simp.getNode()) AddToWorklist(Simp.getNode());
9548 // fold to a simpler setcc
9549 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9550 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9551 N->getOperand(0), Simp.getOperand(2),
9552 Simp.getOperand(0), Simp.getOperand(1),
9558 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9559 /// and that N may be folded in the load / store addressing mode.
9560 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9562 const TargetLowering &TLI) {
9566 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
9567 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9569 VT = LD->getMemoryVT();
9570 AS = LD->getAddressSpace();
9571 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
9572 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9574 VT = ST->getMemoryVT();
9575 AS = ST->getAddressSpace();
9579 TargetLowering::AddrMode AM;
9580 if (N->getOpcode() == ISD::ADD) {
9581 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9584 AM.BaseOffs = Offset->getSExtValue();
9588 } else if (N->getOpcode() == ISD::SUB) {
9589 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9592 AM.BaseOffs = -Offset->getSExtValue();
9599 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9600 VT.getTypeForEVT(*DAG.getContext()), AS);
9603 /// Try turning a load/store into a pre-indexed load/store when the base
9604 /// pointer is an add or subtract and it has other uses besides the load/store.
9605 /// After the transformation, the new indexed load/store has effectively folded
9606 /// the add/subtract in and all of its other uses are redirected to the
9608 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9609 if (Level < AfterLegalizeDAG)
9615 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9616 if (LD->isIndexed())
9618 VT = LD->getMemoryVT();
9619 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9620 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9622 Ptr = LD->getBasePtr();
9623 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9624 if (ST->isIndexed())
9626 VT = ST->getMemoryVT();
9627 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9628 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9630 Ptr = ST->getBasePtr();
9636 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9637 // out. There is no reason to make this a preinc/predec.
9638 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9639 Ptr.getNode()->hasOneUse())
9642 // Ask the target to do addressing mode selection.
9645 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9646 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9649 // Backends without true r+i pre-indexed forms may need to pass a
9650 // constant base with a variable offset so that constant coercion
9651 // will work with the patterns in canonical form.
9652 bool Swapped = false;
9653 if (isa<ConstantSDNode>(BasePtr)) {
9654 std::swap(BasePtr, Offset);
9658 // Don't create a indexed load / store with zero offset.
9659 if (isNullConstant(Offset))
9662 // Try turning it into a pre-indexed load / store except when:
9663 // 1) The new base ptr is a frame index.
9664 // 2) If N is a store and the new base ptr is either the same as or is a
9665 // predecessor of the value being stored.
9666 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9667 // that would create a cycle.
9668 // 4) All uses are load / store ops that use it as old base ptr.
9670 // Check #1. Preinc'ing a frame index would require copying the stack pointer
9671 // (plus the implicit offset) to a register to preinc anyway.
9672 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9677 SDValue Val = cast<StoreSDNode>(N)->getValue();
9678 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9682 // If the offset is a constant, there may be other adds of constants that
9683 // can be folded with this one. We should do this to avoid having to keep
9684 // a copy of the original base pointer.
9685 SmallVector<SDNode *, 16> OtherUses;
9686 if (isa<ConstantSDNode>(Offset))
9687 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9688 UE = BasePtr.getNode()->use_end();
9690 SDUse &Use = UI.getUse();
9691 // Skip the use that is Ptr and uses of other results from BasePtr's
9692 // node (important for nodes that return multiple results).
9693 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9696 if (Use.getUser()->isPredecessorOf(N))
9699 if (Use.getUser()->getOpcode() != ISD::ADD &&
9700 Use.getUser()->getOpcode() != ISD::SUB) {
9705 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9706 if (!isa<ConstantSDNode>(Op1)) {
9711 // FIXME: In some cases, we can be smarter about this.
9712 if (Op1.getValueType() != Offset.getValueType()) {
9717 OtherUses.push_back(Use.getUser());
9721 std::swap(BasePtr, Offset);
9723 // Now check for #3 and #4.
9724 bool RealUse = false;
9726 // Caches for hasPredecessorHelper
9727 SmallPtrSet<const SDNode *, 32> Visited;
9728 SmallVector<const SDNode *, 16> Worklist;
9730 for (SDNode *Use : Ptr.getNode()->uses()) {
9733 if (N->hasPredecessorHelper(Use, Visited, Worklist))
9736 // If Ptr may be folded in addressing mode of other use, then it's
9737 // not profitable to do this transformation.
9738 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9747 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9748 BasePtr, Offset, AM);
9750 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9751 BasePtr, Offset, AM);
9754 DEBUG(dbgs() << "\nReplacing.4 ";
9756 dbgs() << "\nWith: ";
9757 Result.getNode()->dump(&DAG);
9759 WorklistRemover DeadNodes(*this);
9761 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9762 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9764 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9767 // Finally, since the node is now dead, remove it from the graph.
9768 deleteAndRecombine(N);
9771 std::swap(BasePtr, Offset);
9773 // Replace other uses of BasePtr that can be updated to use Ptr
9774 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9775 unsigned OffsetIdx = 1;
9776 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9778 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9779 BasePtr.getNode() && "Expected BasePtr operand");
9781 // We need to replace ptr0 in the following expression:
9782 // x0 * offset0 + y0 * ptr0 = t0
9784 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9786 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9787 // indexed load/store and the expresion that needs to be re-written.
9789 // Therefore, we have:
9790 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9792 ConstantSDNode *CN =
9793 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9795 APInt Offset0 = CN->getAPIntValue();
9796 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9798 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9799 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9800 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9801 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9803 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9805 APInt CNV = Offset0;
9806 if (X0 < 0) CNV = -CNV;
9807 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9808 else CNV = CNV - Offset1;
9810 SDLoc DL(OtherUses[i]);
9812 // We can now generate the new expression.
9813 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9814 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9816 SDValue NewUse = DAG.getNode(Opcode,
9818 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9819 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9820 deleteAndRecombine(OtherUses[i]);
9823 // Replace the uses of Ptr with uses of the updated base value.
9824 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9825 deleteAndRecombine(Ptr.getNode());
9830 /// Try to combine a load/store with a add/sub of the base pointer node into a
9831 /// post-indexed load/store. The transformation folded the add/subtract into the
9832 /// new indexed load/store effectively and all of its uses are redirected to the
9834 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9835 if (Level < AfterLegalizeDAG)
9841 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9842 if (LD->isIndexed())
9844 VT = LD->getMemoryVT();
9845 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9846 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9848 Ptr = LD->getBasePtr();
9849 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9850 if (ST->isIndexed())
9852 VT = ST->getMemoryVT();
9853 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9854 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9856 Ptr = ST->getBasePtr();
9862 if (Ptr.getNode()->hasOneUse())
9865 for (SDNode *Op : Ptr.getNode()->uses()) {
9867 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9872 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9873 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9874 // Don't create a indexed load / store with zero offset.
9875 if (isNullConstant(Offset))
9878 // Try turning it into a post-indexed load / store except when
9879 // 1) All uses are load / store ops that use it as base ptr (and
9880 // it may be folded as addressing mmode).
9881 // 2) Op must be independent of N, i.e. Op is neither a predecessor
9882 // nor a successor of N. Otherwise, if Op is folded that would
9885 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9889 bool TryNext = false;
9890 for (SDNode *Use : BasePtr.getNode()->uses()) {
9891 if (Use == Ptr.getNode())
9894 // If all the uses are load / store addresses, then don't do the
9896 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9897 bool RealUse = false;
9898 for (SDNode *UseUse : Use->uses()) {
9899 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9914 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9915 SDValue Result = isLoad
9916 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9917 BasePtr, Offset, AM)
9918 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9919 BasePtr, Offset, AM);
9922 DEBUG(dbgs() << "\nReplacing.5 ";
9924 dbgs() << "\nWith: ";
9925 Result.getNode()->dump(&DAG);
9927 WorklistRemover DeadNodes(*this);
9929 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9930 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9932 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9935 // Finally, since the node is now dead, remove it from the graph.
9936 deleteAndRecombine(N);
9938 // Replace the uses of Use with uses of the updated base value.
9939 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9940 Result.getValue(isLoad ? 1 : 0));
9941 deleteAndRecombine(Op);
9950 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9951 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9952 ISD::MemIndexedMode AM = LD->getAddressingMode();
9953 assert(AM != ISD::UNINDEXED);
9954 SDValue BP = LD->getOperand(1);
9955 SDValue Inc = LD->getOperand(2);
9957 // Some backends use TargetConstants for load offsets, but don't expect
9958 // TargetConstants in general ADD nodes. We can convert these constants into
9959 // regular Constants (if the constant is not opaque).
9960 assert((Inc.getOpcode() != ISD::TargetConstant ||
9961 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9962 "Cannot split out indexing using opaque target constants");
9963 if (Inc.getOpcode() == ISD::TargetConstant) {
9964 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9965 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9966 ConstInc->getValueType(0));
9970 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9971 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9974 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9975 LoadSDNode *LD = cast<LoadSDNode>(N);
9976 SDValue Chain = LD->getChain();
9977 SDValue Ptr = LD->getBasePtr();
9979 // If load is not volatile and there are no uses of the loaded value (and
9980 // the updated indexed value in case of indexed loads), change uses of the
9981 // chain value into uses of the chain input (i.e. delete the dead load).
9982 if (!LD->isVolatile()) {
9983 if (N->getValueType(1) == MVT::Other) {
9985 if (!N->hasAnyUseOfValue(0)) {
9986 // It's not safe to use the two value CombineTo variant here. e.g.
9987 // v1, chain2 = load chain1, loc
9988 // v2, chain3 = load chain2, loc
9990 // Now we replace use of chain2 with chain1. This makes the second load
9991 // isomorphic to the one we are deleting, and thus makes this load live.
9992 DEBUG(dbgs() << "\nReplacing.6 ";
9994 dbgs() << "\nWith chain: ";
9995 Chain.getNode()->dump(&DAG);
9997 WorklistRemover DeadNodes(*this);
9998 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10000 if (N->use_empty())
10001 deleteAndRecombine(N);
10003 return SDValue(N, 0); // Return N so it doesn't get rechecked!
10007 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
10009 // If this load has an opaque TargetConstant offset, then we cannot split
10010 // the indexing into an add/sub directly (that TargetConstant may not be
10011 // valid for a different type of node, and we cannot convert an opaque
10012 // target constant into a regular constant).
10013 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
10014 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
10016 if (!N->hasAnyUseOfValue(0) &&
10017 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
10018 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
10020 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
10021 Index = SplitIndexingFromLoad(LD);
10022 // Try to fold the base pointer arithmetic into subsequent loads and
10024 AddUsersToWorklist(N);
10026 Index = DAG.getUNDEF(N->getValueType(1));
10027 DEBUG(dbgs() << "\nReplacing.7 ";
10029 dbgs() << "\nWith: ";
10030 Undef.getNode()->dump(&DAG);
10031 dbgs() << " and 2 other values\n");
10032 WorklistRemover DeadNodes(*this);
10033 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
10034 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
10035 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
10036 deleteAndRecombine(N);
10037 return SDValue(N, 0); // Return N so it doesn't get rechecked!
10042 // If this load is directly stored, replace the load value with the stored
10044 // TODO: Handle store large -> read small portion.
10045 // TODO: Handle TRUNCSTORE/LOADEXT
10046 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
10047 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
10048 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
10049 if (PrevST->getBasePtr() == Ptr &&
10050 PrevST->getValue().getValueType() == N->getValueType(0))
10051 return CombineTo(N, Chain.getOperand(1), Chain);
10055 // Try to infer better alignment information than the load already has.
10056 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
10057 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10058 if (Align > LD->getMemOperand()->getBaseAlignment()) {
10060 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
10061 LD->getValueType(0),
10062 Chain, Ptr, LD->getPointerInfo(),
10064 LD->isVolatile(), LD->isNonTemporal(),
10065 LD->isInvariant(), Align, LD->getAAInfo());
10066 if (NewLoad.getNode() != N)
10067 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
10072 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10073 : DAG.getSubtarget().useAA();
10075 if (CombinerAAOnlyFunc.getNumOccurrences() &&
10076 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10079 if (UseAA && LD->isUnindexed()) {
10080 // Walk up chain skipping non-aliasing memory nodes.
10081 SDValue BetterChain = FindBetterChain(N, Chain);
10083 // If there is a better chain.
10084 if (Chain != BetterChain) {
10087 // Replace the chain to void dependency.
10088 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
10089 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
10090 BetterChain, Ptr, LD->getMemOperand());
10092 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
10093 LD->getValueType(0),
10094 BetterChain, Ptr, LD->getMemoryVT(),
10095 LD->getMemOperand());
10098 // Create token factor to keep old chain connected.
10099 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10100 MVT::Other, Chain, ReplLoad.getValue(1));
10102 // Make sure the new and old chains are cleaned up.
10103 AddToWorklist(Token.getNode());
10105 // Replace uses with load result and token factor. Don't add users
10107 return CombineTo(N, ReplLoad.getValue(0), Token, false);
10111 // Try transforming N to an indexed load.
10112 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10113 return SDValue(N, 0);
10115 // Try to slice up N to more direct loads if the slices are mapped to
10116 // different register banks or pairing can take place.
10117 if (SliceUpLoad(N))
10118 return SDValue(N, 0);
10124 /// \brief Helper structure used to slice a load in smaller loads.
10125 /// Basically a slice is obtained from the following sequence:
10126 /// Origin = load Ty1, Base
10127 /// Shift = srl Ty1 Origin, CstTy Amount
10128 /// Inst = trunc Shift to Ty2
10130 /// Then, it will be rewriten into:
10131 /// Slice = load SliceTy, Base + SliceOffset
10132 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
10134 /// SliceTy is deduced from the number of bits that are actually used to
10136 struct LoadedSlice {
10137 /// \brief Helper structure used to compute the cost of a slice.
10139 /// Are we optimizing for code size.
10143 unsigned Truncates;
10144 unsigned CrossRegisterBanksCopies;
10148 Cost(bool ForCodeSize = false)
10149 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
10150 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
10152 /// \brief Get the cost of one isolated slice.
10153 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
10154 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
10155 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
10156 EVT TruncType = LS.Inst->getValueType(0);
10157 EVT LoadedType = LS.getLoadedType();
10158 if (TruncType != LoadedType &&
10159 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
10163 /// \brief Account for slicing gain in the current cost.
10164 /// Slicing provide a few gains like removing a shift or a
10165 /// truncate. This method allows to grow the cost of the original
10166 /// load with the gain from this slice.
10167 void addSliceGain(const LoadedSlice &LS) {
10168 // Each slice saves a truncate.
10169 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
10170 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
10171 LS.Inst->getValueType(0)))
10173 // If there is a shift amount, this slice gets rid of it.
10176 // If this slice can merge a cross register bank copy, account for it.
10177 if (LS.canMergeExpensiveCrossRegisterBankCopy())
10178 ++CrossRegisterBanksCopies;
10181 Cost &operator+=(const Cost &RHS) {
10182 Loads += RHS.Loads;
10183 Truncates += RHS.Truncates;
10184 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
10185 ZExts += RHS.ZExts;
10186 Shift += RHS.Shift;
10190 bool operator==(const Cost &RHS) const {
10191 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
10192 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
10193 ZExts == RHS.ZExts && Shift == RHS.Shift;
10196 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
10198 bool operator<(const Cost &RHS) const {
10199 // Assume cross register banks copies are as expensive as loads.
10200 // FIXME: Do we want some more target hooks?
10201 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
10202 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
10203 // Unless we are optimizing for code size, consider the
10204 // expensive operation first.
10205 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
10206 return ExpensiveOpsLHS < ExpensiveOpsRHS;
10207 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
10208 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
10211 bool operator>(const Cost &RHS) const { return RHS < *this; }
10213 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
10215 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
10217 // The last instruction that represent the slice. This should be a
10218 // truncate instruction.
10220 // The original load instruction.
10221 LoadSDNode *Origin;
10222 // The right shift amount in bits from the original load.
10224 // The DAG from which Origin came from.
10225 // This is used to get some contextual information about legal types, etc.
10228 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
10229 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
10230 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
10232 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
10233 /// \return Result is \p BitWidth and has used bits set to 1 and
10234 /// not used bits set to 0.
10235 APInt getUsedBits() const {
10236 // Reproduce the trunc(lshr) sequence:
10237 // - Start from the truncated value.
10238 // - Zero extend to the desired bit width.
10240 assert(Origin && "No original load to compare against.");
10241 unsigned BitWidth = Origin->getValueSizeInBits(0);
10242 assert(Inst && "This slice is not bound to an instruction");
10243 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
10244 "Extracted slice is bigger than the whole type!");
10245 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
10246 UsedBits.setAllBits();
10247 UsedBits = UsedBits.zext(BitWidth);
10248 UsedBits <<= Shift;
10252 /// \brief Get the size of the slice to be loaded in bytes.
10253 unsigned getLoadedSize() const {
10254 unsigned SliceSize = getUsedBits().countPopulation();
10255 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
10256 return SliceSize / 8;
10259 /// \brief Get the type that will be loaded for this slice.
10260 /// Note: This may not be the final type for the slice.
10261 EVT getLoadedType() const {
10262 assert(DAG && "Missing context");
10263 LLVMContext &Ctxt = *DAG->getContext();
10264 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
10267 /// \brief Get the alignment of the load used for this slice.
10268 unsigned getAlignment() const {
10269 unsigned Alignment = Origin->getAlignment();
10270 unsigned Offset = getOffsetFromBase();
10272 Alignment = MinAlign(Alignment, Alignment + Offset);
10276 /// \brief Check if this slice can be rewritten with legal operations.
10277 bool isLegal() const {
10278 // An invalid slice is not legal.
10279 if (!Origin || !Inst || !DAG)
10282 // Offsets are for indexed load only, we do not handle that.
10283 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
10286 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10288 // Check that the type is legal.
10289 EVT SliceType = getLoadedType();
10290 if (!TLI.isTypeLegal(SliceType))
10293 // Check that the load is legal for this type.
10294 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10297 // Check that the offset can be computed.
10298 // 1. Check its type.
10299 EVT PtrType = Origin->getBasePtr().getValueType();
10300 if (PtrType == MVT::Untyped || PtrType.isExtended())
10303 // 2. Check that it fits in the immediate.
10304 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10307 // 3. Check that the computation is legal.
10308 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10311 // Check that the zext is legal if it needs one.
10312 EVT TruncateType = Inst->getValueType(0);
10313 if (TruncateType != SliceType &&
10314 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10320 /// \brief Get the offset in bytes of this slice in the original chunk of
10322 /// \pre DAG != nullptr.
10323 uint64_t getOffsetFromBase() const {
10324 assert(DAG && "Missing context.");
10325 bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10326 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10327 uint64_t Offset = Shift / 8;
10328 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10329 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10330 "The size of the original loaded type is not a multiple of a"
10332 // If Offset is bigger than TySizeInBytes, it means we are loading all
10333 // zeros. This should have been optimized before in the process.
10334 assert(TySizeInBytes > Offset &&
10335 "Invalid shift amount for given loaded size");
10337 Offset = TySizeInBytes - Offset - getLoadedSize();
10341 /// \brief Generate the sequence of instructions to load the slice
10342 /// represented by this object and redirect the uses of this slice to
10343 /// this new sequence of instructions.
10344 /// \pre this->Inst && this->Origin are valid Instructions and this
10345 /// object passed the legal check: LoadedSlice::isLegal returned true.
10346 /// \return The last instruction of the sequence used to load the slice.
10347 SDValue loadSlice() const {
10348 assert(Inst && Origin && "Unable to replace a non-existing slice.");
10349 const SDValue &OldBaseAddr = Origin->getBasePtr();
10350 SDValue BaseAddr = OldBaseAddr;
10351 // Get the offset in that chunk of bytes w.r.t. the endianess.
10352 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10353 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10355 // BaseAddr = BaseAddr + Offset.
10356 EVT ArithType = BaseAddr.getValueType();
10358 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10359 DAG->getConstant(Offset, DL, ArithType));
10362 // Create the type of the loaded slice according to its size.
10363 EVT SliceType = getLoadedType();
10365 // Create the load for the slice.
10366 SDValue LastInst = DAG->getLoad(
10367 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10368 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
10369 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
10370 // If the final type is not the same as the loaded type, this means that
10371 // we have to pad with zero. Create a zero extend for that.
10372 EVT FinalType = Inst->getValueType(0);
10373 if (SliceType != FinalType)
10375 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10379 /// \brief Check if this slice can be merged with an expensive cross register
10380 /// bank copy. E.g.,
10382 /// f = bitcast i32 i to float
10383 bool canMergeExpensiveCrossRegisterBankCopy() const {
10384 if (!Inst || !Inst->hasOneUse())
10386 SDNode *Use = *Inst->use_begin();
10387 if (Use->getOpcode() != ISD::BITCAST)
10389 assert(DAG && "Missing context");
10390 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10391 EVT ResVT = Use->getValueType(0);
10392 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10393 const TargetRegisterClass *ArgRC =
10394 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10395 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10398 // At this point, we know that we perform a cross-register-bank copy.
10399 // Check if it is expensive.
10400 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10401 // Assume bitcasts are cheap, unless both register classes do not
10402 // explicitly share a common sub class.
10403 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10406 // Check if it will be merged with the load.
10407 // 1. Check the alignment constraint.
10408 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10409 ResVT.getTypeForEVT(*DAG->getContext()));
10411 if (RequiredAlignment > getAlignment())
10414 // 2. Check that the load is a legal operation for that type.
10415 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10418 // 3. Check that we do not have a zext in the way.
10419 if (Inst->getValueType(0) != getLoadedType())
10427 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10428 /// \p UsedBits looks like 0..0 1..1 0..0.
10429 static bool areUsedBitsDense(const APInt &UsedBits) {
10430 // If all the bits are one, this is dense!
10431 if (UsedBits.isAllOnesValue())
10434 // Get rid of the unused bits on the right.
10435 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10436 // Get rid of the unused bits on the left.
10437 if (NarrowedUsedBits.countLeadingZeros())
10438 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10439 // Check that the chunk of bits is completely used.
10440 return NarrowedUsedBits.isAllOnesValue();
10443 /// \brief Check whether or not \p First and \p Second are next to each other
10444 /// in memory. This means that there is no hole between the bits loaded
10445 /// by \p First and the bits loaded by \p Second.
10446 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10447 const LoadedSlice &Second) {
10448 assert(First.Origin == Second.Origin && First.Origin &&
10449 "Unable to match different memory origins.");
10450 APInt UsedBits = First.getUsedBits();
10451 assert((UsedBits & Second.getUsedBits()) == 0 &&
10452 "Slices are not supposed to overlap.");
10453 UsedBits |= Second.getUsedBits();
10454 return areUsedBitsDense(UsedBits);
10457 /// \brief Adjust the \p GlobalLSCost according to the target
10458 /// paring capabilities and the layout of the slices.
10459 /// \pre \p GlobalLSCost should account for at least as many loads as
10460 /// there is in the slices in \p LoadedSlices.
10461 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10462 LoadedSlice::Cost &GlobalLSCost) {
10463 unsigned NumberOfSlices = LoadedSlices.size();
10464 // If there is less than 2 elements, no pairing is possible.
10465 if (NumberOfSlices < 2)
10468 // Sort the slices so that elements that are likely to be next to each
10469 // other in memory are next to each other in the list.
10470 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10471 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10472 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10473 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10475 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10476 // First (resp. Second) is the first (resp. Second) potentially candidate
10477 // to be placed in a paired load.
10478 const LoadedSlice *First = nullptr;
10479 const LoadedSlice *Second = nullptr;
10480 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10481 // Set the beginning of the pair.
10484 Second = &LoadedSlices[CurrSlice];
10486 // If First is NULL, it means we start a new pair.
10487 // Get to the next slice.
10491 EVT LoadedType = First->getLoadedType();
10493 // If the types of the slices are different, we cannot pair them.
10494 if (LoadedType != Second->getLoadedType())
10497 // Check if the target supplies paired loads for this type.
10498 unsigned RequiredAlignment = 0;
10499 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10500 // move to the next pair, this type is hopeless.
10504 // Check if we meet the alignment requirement.
10505 if (RequiredAlignment > First->getAlignment())
10508 // Check that both loads are next to each other in memory.
10509 if (!areSlicesNextToEachOther(*First, *Second))
10512 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10513 --GlobalLSCost.Loads;
10514 // Move to the next pair.
10519 /// \brief Check the profitability of all involved LoadedSlice.
10520 /// Currently, it is considered profitable if there is exactly two
10521 /// involved slices (1) which are (2) next to each other in memory, and
10522 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10524 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10525 /// the elements themselves.
10527 /// FIXME: When the cost model will be mature enough, we can relax
10528 /// constraints (1) and (2).
10529 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10530 const APInt &UsedBits, bool ForCodeSize) {
10531 unsigned NumberOfSlices = LoadedSlices.size();
10532 if (StressLoadSlicing)
10533 return NumberOfSlices > 1;
10536 if (NumberOfSlices != 2)
10540 if (!areUsedBitsDense(UsedBits))
10544 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10545 // The original code has one big load.
10546 OrigCost.Loads = 1;
10547 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10548 const LoadedSlice &LS = LoadedSlices[CurrSlice];
10549 // Accumulate the cost of all the slices.
10550 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10551 GlobalSlicingCost += SliceCost;
10553 // Account as cost in the original configuration the gain obtained
10554 // with the current slices.
10555 OrigCost.addSliceGain(LS);
10558 // If the target supports paired load, adjust the cost accordingly.
10559 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10560 return OrigCost > GlobalSlicingCost;
10563 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10564 /// operations, split it in the various pieces being extracted.
10566 /// This sort of thing is introduced by SROA.
10567 /// This slicing takes care not to insert overlapping loads.
10568 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10569 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10570 if (Level < AfterLegalizeDAG)
10573 LoadSDNode *LD = cast<LoadSDNode>(N);
10574 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10575 !LD->getValueType(0).isInteger())
10578 // Keep track of already used bits to detect overlapping values.
10579 // In that case, we will just abort the transformation.
10580 APInt UsedBits(LD->getValueSizeInBits(0), 0);
10582 SmallVector<LoadedSlice, 4> LoadedSlices;
10584 // Check if this load is used as several smaller chunks of bits.
10585 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10586 // of computation for each trunc.
10587 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10588 UI != UIEnd; ++UI) {
10589 // Skip the uses of the chain.
10590 if (UI.getUse().getResNo() != 0)
10593 SDNode *User = *UI;
10594 unsigned Shift = 0;
10596 // Check if this is a trunc(lshr).
10597 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10598 isa<ConstantSDNode>(User->getOperand(1))) {
10599 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10600 User = *User->use_begin();
10603 // At this point, User is a Truncate, iff we encountered, trunc or
10605 if (User->getOpcode() != ISD::TRUNCATE)
10608 // The width of the type must be a power of 2 and greater than 8-bits.
10609 // Otherwise the load cannot be represented in LLVM IR.
10610 // Moreover, if we shifted with a non-8-bits multiple, the slice
10611 // will be across several bytes. We do not support that.
10612 unsigned Width = User->getValueSizeInBits(0);
10613 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10616 // Build the slice for this chain of computations.
10617 LoadedSlice LS(User, LD, Shift, &DAG);
10618 APInt CurrentUsedBits = LS.getUsedBits();
10620 // Check if this slice overlaps with another.
10621 if ((CurrentUsedBits & UsedBits) != 0)
10623 // Update the bits used globally.
10624 UsedBits |= CurrentUsedBits;
10626 // Check if the new slice would be legal.
10630 // Record the slice.
10631 LoadedSlices.push_back(LS);
10634 // Abort slicing if it does not seem to be profitable.
10635 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10640 // Rewrite each chain to use an independent load.
10641 // By construction, each chain can be represented by a unique load.
10643 // Prepare the argument for the new token factor for all the slices.
10644 SmallVector<SDValue, 8> ArgChains;
10645 for (SmallVectorImpl<LoadedSlice>::const_iterator
10646 LSIt = LoadedSlices.begin(),
10647 LSItEnd = LoadedSlices.end();
10648 LSIt != LSItEnd; ++LSIt) {
10649 SDValue SliceInst = LSIt->loadSlice();
10650 CombineTo(LSIt->Inst, SliceInst, true);
10651 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10652 SliceInst = SliceInst.getOperand(0);
10653 assert(SliceInst->getOpcode() == ISD::LOAD &&
10654 "It takes more than a zext to get to the loaded slice!!");
10655 ArgChains.push_back(SliceInst.getValue(1));
10658 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10660 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10664 /// Check to see if V is (and load (ptr), imm), where the load is having
10665 /// specific bytes cleared out. If so, return the byte size being masked out
10666 /// and the shift amount.
10667 static std::pair<unsigned, unsigned>
10668 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10669 std::pair<unsigned, unsigned> Result(0, 0);
10671 // Check for the structure we're looking for.
10672 if (V->getOpcode() != ISD::AND ||
10673 !isa<ConstantSDNode>(V->getOperand(1)) ||
10674 !ISD::isNormalLoad(V->getOperand(0).getNode()))
10677 // Check the chain and pointer.
10678 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10679 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
10681 // The store should be chained directly to the load or be an operand of a
10683 if (LD == Chain.getNode())
10685 else if (Chain->getOpcode() != ISD::TokenFactor)
10686 return Result; // Fail.
10689 for (const SDValue &ChainOp : Chain->op_values())
10690 if (ChainOp.getNode() == LD) {
10694 if (!isOk) return Result;
10697 // This only handles simple types.
10698 if (V.getValueType() != MVT::i16 &&
10699 V.getValueType() != MVT::i32 &&
10700 V.getValueType() != MVT::i64)
10703 // Check the constant mask. Invert it so that the bits being masked out are
10704 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
10705 // follow the sign bit for uniformity.
10706 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10707 unsigned NotMaskLZ = countLeadingZeros(NotMask);
10708 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
10709 unsigned NotMaskTZ = countTrailingZeros(NotMask);
10710 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
10711 if (NotMaskLZ == 64) return Result; // All zero mask.
10713 // See if we have a continuous run of bits. If so, we have 0*1+0*
10714 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10717 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10718 if (V.getValueType() != MVT::i64 && NotMaskLZ)
10719 NotMaskLZ -= 64-V.getValueSizeInBits();
10721 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10722 switch (MaskedBytes) {
10726 default: return Result; // All one mask, or 5-byte mask.
10729 // Verify that the first bit starts at a multiple of mask so that the access
10730 // is aligned the same as the access width.
10731 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10733 Result.first = MaskedBytes;
10734 Result.second = NotMaskTZ/8;
10739 /// Check to see if IVal is something that provides a value as specified by
10740 /// MaskInfo. If so, replace the specified store with a narrower store of
10741 /// truncated IVal.
10743 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10744 SDValue IVal, StoreSDNode *St,
10746 unsigned NumBytes = MaskInfo.first;
10747 unsigned ByteShift = MaskInfo.second;
10748 SelectionDAG &DAG = DC->getDAG();
10750 // Check to see if IVal is all zeros in the part being masked in by the 'or'
10751 // that uses this. If not, this is not a replacement.
10752 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10753 ByteShift*8, (ByteShift+NumBytes)*8);
10754 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10756 // Check that it is legal on the target to do this. It is legal if the new
10757 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10759 MVT VT = MVT::getIntegerVT(NumBytes*8);
10760 if (!DC->isTypeLegal(VT))
10763 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
10764 // shifted by ByteShift and truncated down to NumBytes.
10767 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10768 DAG.getConstant(ByteShift*8, DL,
10769 DC->getShiftAmountTy(IVal.getValueType())));
10772 // Figure out the offset for the store and the alignment of the access.
10774 unsigned NewAlign = St->getAlignment();
10776 if (DAG.getDataLayout().isLittleEndian())
10777 StOffset = ByteShift;
10779 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10781 SDValue Ptr = St->getBasePtr();
10784 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10785 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10786 NewAlign = MinAlign(NewAlign, StOffset);
10789 // Truncate down to the new size.
10790 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10793 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10794 St->getPointerInfo().getWithOffset(StOffset),
10795 false, false, NewAlign).getNode();
10799 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10800 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10801 /// narrowing the load and store if it would end up being a win for performance
10803 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10804 StoreSDNode *ST = cast<StoreSDNode>(N);
10805 if (ST->isVolatile())
10808 SDValue Chain = ST->getChain();
10809 SDValue Value = ST->getValue();
10810 SDValue Ptr = ST->getBasePtr();
10811 EVT VT = Value.getValueType();
10813 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10816 unsigned Opc = Value.getOpcode();
10818 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10819 // is a byte mask indicating a consecutive number of bytes, check to see if
10820 // Y is known to provide just those bytes. If so, we try to replace the
10821 // load + replace + store sequence with a single (narrower) store, which makes
10823 if (Opc == ISD::OR) {
10824 std::pair<unsigned, unsigned> MaskedLoad;
10825 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10826 if (MaskedLoad.first)
10827 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10828 Value.getOperand(1), ST,this))
10829 return SDValue(NewST, 0);
10831 // Or is commutative, so try swapping X and Y.
10832 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10833 if (MaskedLoad.first)
10834 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10835 Value.getOperand(0), ST,this))
10836 return SDValue(NewST, 0);
10839 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10840 Value.getOperand(1).getOpcode() != ISD::Constant)
10843 SDValue N0 = Value.getOperand(0);
10844 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10845 Chain == SDValue(N0.getNode(), 1)) {
10846 LoadSDNode *LD = cast<LoadSDNode>(N0);
10847 if (LD->getBasePtr() != Ptr ||
10848 LD->getPointerInfo().getAddrSpace() !=
10849 ST->getPointerInfo().getAddrSpace())
10852 // Find the type to narrow it the load / op / store to.
10853 SDValue N1 = Value.getOperand(1);
10854 unsigned BitWidth = N1.getValueSizeInBits();
10855 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10856 if (Opc == ISD::AND)
10857 Imm ^= APInt::getAllOnesValue(BitWidth);
10858 if (Imm == 0 || Imm.isAllOnesValue())
10860 unsigned ShAmt = Imm.countTrailingZeros();
10861 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10862 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10863 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10864 // The narrowing should be profitable, the load/store operation should be
10865 // legal (or custom) and the store size should be equal to the NewVT width.
10866 while (NewBW < BitWidth &&
10867 (NewVT.getStoreSizeInBits() != NewBW ||
10868 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10869 !TLI.isNarrowingProfitable(VT, NewVT))) {
10870 NewBW = NextPowerOf2(NewBW);
10871 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10873 if (NewBW >= BitWidth)
10876 // If the lsb changed does not start at the type bitwidth boundary,
10877 // start at the previous one.
10879 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10880 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10881 std::min(BitWidth, ShAmt + NewBW));
10882 if ((Imm & Mask) == Imm) {
10883 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10884 if (Opc == ISD::AND)
10885 NewImm ^= APInt::getAllOnesValue(NewBW);
10886 uint64_t PtrOff = ShAmt / 8;
10887 // For big endian targets, we need to adjust the offset to the pointer to
10888 // load the correct bytes.
10889 if (DAG.getDataLayout().isBigEndian())
10890 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10892 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10893 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10894 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10897 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10898 Ptr.getValueType(), Ptr,
10899 DAG.getConstant(PtrOff, SDLoc(LD),
10900 Ptr.getValueType()));
10901 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10902 LD->getChain(), NewPtr,
10903 LD->getPointerInfo().getWithOffset(PtrOff),
10904 LD->isVolatile(), LD->isNonTemporal(),
10905 LD->isInvariant(), NewAlign,
10907 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10908 DAG.getConstant(NewImm, SDLoc(Value),
10910 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10912 ST->getPointerInfo().getWithOffset(PtrOff),
10913 false, false, NewAlign);
10915 AddToWorklist(NewPtr.getNode());
10916 AddToWorklist(NewLD.getNode());
10917 AddToWorklist(NewVal.getNode());
10918 WorklistRemover DeadNodes(*this);
10919 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10928 /// For a given floating point load / store pair, if the load value isn't used
10929 /// by any other operations, then consider transforming the pair to integer
10930 /// load / store operations if the target deems the transformation profitable.
10931 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10932 StoreSDNode *ST = cast<StoreSDNode>(N);
10933 SDValue Chain = ST->getChain();
10934 SDValue Value = ST->getValue();
10935 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10936 Value.hasOneUse() &&
10937 Chain == SDValue(Value.getNode(), 1)) {
10938 LoadSDNode *LD = cast<LoadSDNode>(Value);
10939 EVT VT = LD->getMemoryVT();
10940 if (!VT.isFloatingPoint() ||
10941 VT != ST->getMemoryVT() ||
10942 LD->isNonTemporal() ||
10943 ST->isNonTemporal() ||
10944 LD->getPointerInfo().getAddrSpace() != 0 ||
10945 ST->getPointerInfo().getAddrSpace() != 0)
10948 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10949 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10950 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10951 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10952 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10955 unsigned LDAlign = LD->getAlignment();
10956 unsigned STAlign = ST->getAlignment();
10957 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10958 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10959 if (LDAlign < ABIAlign || STAlign < ABIAlign)
10962 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10963 LD->getChain(), LD->getBasePtr(),
10964 LD->getPointerInfo(),
10965 false, false, false, LDAlign);
10967 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10968 NewLD, ST->getBasePtr(),
10969 ST->getPointerInfo(),
10970 false, false, STAlign);
10972 AddToWorklist(NewLD.getNode());
10973 AddToWorklist(NewST.getNode());
10974 WorklistRemover DeadNodes(*this);
10975 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10984 /// Helper struct to parse and store a memory address as base + index + offset.
10985 /// We ignore sign extensions when it is safe to do so.
10986 /// The following two expressions are not equivalent. To differentiate we need
10987 /// to store whether there was a sign extension involved in the index
10989 /// (load (i64 add (i64 copyfromreg %c)
10990 /// (i64 signextend (add (i8 load %index)
10994 /// (load (i64 add (i64 copyfromreg %c)
10995 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
10997 struct BaseIndexOffset {
11001 bool IsIndexSignExt;
11003 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
11005 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
11006 bool IsIndexSignExt) :
11007 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
11009 bool equalBaseIndex(const BaseIndexOffset &Other) {
11010 return Other.Base == Base && Other.Index == Index &&
11011 Other.IsIndexSignExt == IsIndexSignExt;
11014 /// Parses tree in Ptr for base, index, offset addresses.
11015 static BaseIndexOffset match(SDValue Ptr) {
11016 bool IsIndexSignExt = false;
11018 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
11019 // instruction, then it could be just the BASE or everything else we don't
11020 // know how to handle. Just use Ptr as BASE and give up.
11021 if (Ptr->getOpcode() != ISD::ADD)
11022 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11024 // We know that we have at least an ADD instruction. Try to pattern match
11025 // the simple case of BASE + OFFSET.
11026 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
11027 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
11028 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
11032 // Inside a loop the current BASE pointer is calculated using an ADD and a
11033 // MUL instruction. In this case Ptr is the actual BASE pointer.
11034 // (i64 add (i64 %array_ptr)
11035 // (i64 mul (i64 %induction_var)
11036 // (i64 %element_size)))
11037 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
11038 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11040 // Look at Base + Index + Offset cases.
11041 SDValue Base = Ptr->getOperand(0);
11042 SDValue IndexOffset = Ptr->getOperand(1);
11044 // Skip signextends.
11045 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
11046 IndexOffset = IndexOffset->getOperand(0);
11047 IsIndexSignExt = true;
11050 // Either the case of Base + Index (no offset) or something else.
11051 if (IndexOffset->getOpcode() != ISD::ADD)
11052 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
11054 // Now we have the case of Base + Index + offset.
11055 SDValue Index = IndexOffset->getOperand(0);
11056 SDValue Offset = IndexOffset->getOperand(1);
11058 if (!isa<ConstantSDNode>(Offset))
11059 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11061 // Ignore signextends.
11062 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
11063 Index = Index->getOperand(0);
11064 IsIndexSignExt = true;
11065 } else IsIndexSignExt = false;
11067 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
11068 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
11073 // This is a helper function for visitMUL to check the profitability
11074 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
11075 // MulNode is the original multiply, AddNode is (add x, c1),
11076 // and ConstNode is c2.
11078 // If the (add x, c1) has multiple uses, we could increase
11079 // the number of adds if we make this transformation.
11080 // It would only be worth doing this if we can remove a
11081 // multiply in the process. Check for that here.
11085 // We're checking for cases where we have common "c3 * A" expressions.
11086 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
11088 SDValue &ConstNode) {
11091 // If the add only has one use, this would be OK to do.
11092 if (AddNode.getNode()->hasOneUse())
11095 // Walk all the users of the constant with which we're multiplying.
11096 for (SDNode *Use : ConstNode->uses()) {
11098 if (Use == MulNode) // This use is the one we're on right now. Skip it.
11101 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
11103 SDNode *MulVar = AddNode.getOperand(0).getNode();
11105 // OtherOp is what we're multiplying against the constant.
11106 if (Use->getOperand(0) == ConstNode)
11107 OtherOp = Use->getOperand(1).getNode();
11109 OtherOp = Use->getOperand(0).getNode();
11111 // Check to see if multiply is with the same operand of our "add".
11113 // ConstNode = CONST
11114 // Use = ConstNode * A <-- visiting Use. OtherOp is A.
11116 // AddNode = (A + c1) <-- MulVar is A.
11117 // = AddNode * ConstNode <-- current visiting instruction.
11119 // If we make this transformation, we will have a common
11120 // multiply (ConstNode * A) that we can save.
11121 if (OtherOp == MulVar)
11124 // Now check to see if a future expansion will give us a common
11127 // ConstNode = CONST
11128 // AddNode = (A + c1)
11129 // ... = AddNode * ConstNode <-- current visiting instruction.
11131 // OtherOp = (A + c2)
11132 // Use = OtherOp * ConstNode <-- visiting Use.
11134 // If we make this transformation, we will have a common
11135 // multiply (CONST * A) after we also do the same transformation
11136 // to the "t2" instruction.
11137 if (OtherOp->getOpcode() == ISD::ADD &&
11138 isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
11139 OtherOp->getOperand(0).getNode() == MulVar)
11144 // Didn't find a case where this would be profitable.
11148 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
11150 ArrayRef<MemOpLink> Stores,
11151 SmallVectorImpl<SDValue> &Chains,
11153 SmallVector<SDValue, 8> BuildVector;
11155 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
11156 StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
11157 Chains.push_back(St->getChain());
11158 BuildVector.push_back(St->getValue());
11161 return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
11164 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
11165 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
11166 unsigned NumStores, bool IsConstantSrc, bool UseVector) {
11167 // Make sure we have something to merge.
11171 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11172 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11173 unsigned LatestNodeUsed = 0;
11175 for (unsigned i=0; i < NumStores; ++i) {
11176 // Find a chain for the new wide-store operand. Notice that some
11177 // of the store nodes that we found may not be selected for inclusion
11178 // in the wide store. The chain we use needs to be the chain of the
11179 // latest store node which is *used* and replaced by the wide store.
11180 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11181 LatestNodeUsed = i;
11184 SmallVector<SDValue, 8> Chains;
11186 // The latest Node in the DAG.
11187 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11188 SDLoc DL(StoreNodes[0].MemNode);
11192 bool IsVec = MemVT.isVector();
11193 unsigned Elts = NumStores;
11195 // When merging vector stores, get the total number of elements.
11196 Elts *= MemVT.getVectorNumElements();
11198 // Get the type for the merged vector store.
11199 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11200 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
11202 if (IsConstantSrc) {
11203 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
11205 SmallVector<SDValue, 8> Ops;
11206 for (unsigned i = 0; i < NumStores; ++i) {
11207 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11208 SDValue Val = St->getValue();
11209 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
11210 if (Val.getValueType() != MemVT)
11212 Ops.push_back(Val);
11213 Chains.push_back(St->getChain());
11216 // Build the extracted vector elements back into a vector.
11217 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
11220 // We should always use a vector store when merging extracted vector
11221 // elements, so this path implies a store of constants.
11222 assert(IsConstantSrc && "Merged vector elements should use vector store");
11224 unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
11225 APInt StoreInt(SizeInBits, 0);
11227 // Construct a single integer constant which is made of the smaller
11228 // constant inputs.
11229 bool IsLE = DAG.getDataLayout().isLittleEndian();
11230 for (unsigned i = 0; i < NumStores; ++i) {
11231 unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
11232 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
11233 Chains.push_back(St->getChain());
11235 SDValue Val = St->getValue();
11236 StoreInt <<= ElementSizeBytes * 8;
11237 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
11238 StoreInt |= C->getAPIntValue().zext(SizeInBits);
11239 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
11240 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
11242 llvm_unreachable("Invalid constant element type");
11246 // Create the new Load and Store operations.
11247 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11248 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
11251 assert(!Chains.empty());
11253 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11254 SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
11255 FirstInChain->getBasePtr(),
11256 FirstInChain->getPointerInfo(),
11258 FirstInChain->getAlignment());
11260 // Replace the last store with the new store
11261 CombineTo(LatestOp, NewStore);
11262 // Erase all other stores.
11263 for (unsigned i = 0; i < NumStores; ++i) {
11264 if (StoreNodes[i].MemNode == LatestOp)
11266 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11267 // ReplaceAllUsesWith will replace all uses that existed when it was
11268 // called, but graph optimizations may cause new ones to appear. For
11269 // example, the case in pr14333 looks like
11271 // St's chain -> St -> another store -> X
11273 // And the only difference from St to the other store is the chain.
11274 // When we change it's chain to be St's chain they become identical,
11275 // get CSEed and the net result is that X is now a use of St.
11276 // Since we know that St is redundant, just iterate.
11277 while (!St->use_empty())
11278 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
11279 deleteAndRecombine(St);
11285 void DAGCombiner::getStoreMergeAndAliasCandidates(
11286 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
11287 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
11288 // This holds the base pointer, index, and the offset in bytes from the base
11290 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
11292 // We must have a base and an offset.
11293 if (!BasePtr.Base.getNode())
11296 // Do not handle stores to undef base pointers.
11297 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
11300 // Walk up the chain and look for nodes with offsets from the same
11301 // base pointer. Stop when reaching an instruction with a different kind
11302 // or instruction which has a different base pointer.
11303 EVT MemVT = St->getMemoryVT();
11305 StoreSDNode *Index = St;
11308 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11309 : DAG.getSubtarget().useAA();
11312 // Look at other users of the same chain. Stores on the same chain do not
11313 // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
11314 // to be on the same chain, so don't bother looking at adjacent chains.
11316 SDValue Chain = St->getChain();
11317 for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
11318 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
11319 if (I.getOperandNo() != 0)
11322 if (OtherST->isVolatile() || OtherST->isIndexed())
11325 if (OtherST->getMemoryVT() != MemVT)
11328 BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr());
11330 if (Ptr.equalBaseIndex(BasePtr))
11331 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
11339 // If the chain has more than one use, then we can't reorder the mem ops.
11340 if (Index != St && !SDValue(Index, 0)->hasOneUse())
11343 // Find the base pointer and offset for this memory node.
11344 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
11346 // Check that the base pointer is the same as the original one.
11347 if (!Ptr.equalBaseIndex(BasePtr))
11350 // The memory operands must not be volatile.
11351 if (Index->isVolatile() || Index->isIndexed())
11355 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
11356 if (St->isTruncatingStore())
11359 // The stored memory type must be the same.
11360 if (Index->getMemoryVT() != MemVT)
11363 // We do not allow under-aligned stores in order to prevent
11364 // overriding stores. NOTE: this is a bad hack. Alignment SHOULD
11365 // be irrelevant here; what MATTERS is that we not move memory
11366 // operations that potentially overlap past each-other.
11367 if (Index->getAlignment() < MemVT.getStoreSize())
11370 // We found a potential memory operand to merge.
11371 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11373 // Find the next memory operand in the chain. If the next operand in the
11374 // chain is a store then move up and continue the scan with the next
11375 // memory operand. If the next operand is a load save it and use alias
11376 // information to check if it interferes with anything.
11377 SDNode *NextInChain = Index->getChain().getNode();
11379 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11380 // We found a store node. Use it for the next iteration.
11383 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11384 if (Ldn->isVolatile()) {
11389 // Save the load node for later. Continue the scan.
11390 AliasLoadNodes.push_back(Ldn);
11391 NextInChain = Ldn->getChain().getNode();
11401 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
11402 if (OptLevel == CodeGenOpt::None)
11405 EVT MemVT = St->getMemoryVT();
11406 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11407 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11408 Attribute::NoImplicitFloat);
11410 // This function cannot currently deal with non-byte-sized memory sizes.
11411 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11414 if (!MemVT.isSimple())
11417 // Perform an early exit check. Do not bother looking at stored values that
11418 // are not constants, loads, or extracted vector elements.
11419 SDValue StoredVal = St->getValue();
11420 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11421 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11422 isa<ConstantFPSDNode>(StoredVal);
11423 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11424 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11426 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11429 // Don't merge vectors into wider vectors if the source data comes from loads.
11430 // TODO: This restriction can be lifted by using logic similar to the
11431 // ExtractVecSrc case.
11432 if (MemVT.isVector() && IsLoadSrc)
11435 // Only look at ends of store sequences.
11436 SDValue Chain = SDValue(St, 0);
11437 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11440 // Save the LoadSDNodes that we find in the chain.
11441 // We need to make sure that these nodes do not interfere with
11442 // any of the store nodes.
11443 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11445 // Save the StoreSDNodes that we find in the chain.
11446 SmallVector<MemOpLink, 8> StoreNodes;
11448 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11450 // Check if there is anything to merge.
11451 if (StoreNodes.size() < 2)
11454 // Sort the memory operands according to their distance from the
11455 // base pointer. As a secondary criteria: make sure stores coming
11456 // later in the code come first in the list. This is important for
11457 // the non-UseAA case, because we're merging stores into the FINAL
11458 // store along a chain which potentially contains aliasing stores.
11459 // Thus, if there are multiple stores to the same address, the last
11460 // one can be considered for merging but not the others.
11461 std::sort(StoreNodes.begin(), StoreNodes.end(),
11462 [](MemOpLink LHS, MemOpLink RHS) {
11463 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11464 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11465 LHS.SequenceNum < RHS.SequenceNum);
11468 // Scan the memory operations on the chain and find the first non-consecutive
11469 // store memory address.
11470 unsigned LastConsecutiveStore = 0;
11471 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11472 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11474 // Check that the addresses are consecutive starting from the second
11475 // element in the list of stores.
11477 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11478 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11482 // Check if this store interferes with any of the loads that we found.
11483 // If we find a load that alias with this store. Stop the sequence.
11484 if (std::any_of(AliasLoadNodes.begin(), AliasLoadNodes.end(),
11485 [&](LSBaseSDNode* Ldn) {
11486 return isAlias(Ldn, StoreNodes[i].MemNode);
11490 // Mark this node as useful.
11491 LastConsecutiveStore = i;
11494 // The node with the lowest store address.
11495 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11496 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11497 unsigned FirstStoreAlign = FirstInChain->getAlignment();
11498 LLVMContext &Context = *DAG.getContext();
11499 const DataLayout &DL = DAG.getDataLayout();
11501 // Store the constants into memory as one consecutive store.
11502 if (IsConstantSrc) {
11503 unsigned LastLegalType = 0;
11504 unsigned LastLegalVectorType = 0;
11505 bool NonZero = false;
11506 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11507 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11508 SDValue StoredVal = St->getValue();
11510 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11511 NonZero |= !C->isNullValue();
11512 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11513 NonZero |= !C->getConstantFPValue()->isNullValue();
11519 // Find a legal type for the constant store.
11520 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11521 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11523 if (TLI.isTypeLegal(StoreTy) &&
11524 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11525 FirstStoreAlign, &IsFast) && IsFast) {
11526 LastLegalType = i+1;
11527 // Or check whether a truncstore is legal.
11528 } else if (TLI.getTypeAction(Context, StoreTy) ==
11529 TargetLowering::TypePromoteInteger) {
11530 EVT LegalizedStoredValueTy =
11531 TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11532 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11533 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11534 FirstStoreAS, FirstStoreAlign, &IsFast) &&
11536 LastLegalType = i + 1;
11540 // We only use vectors if the constant is known to be zero or the target
11541 // allows it and the function is not marked with the noimplicitfloat
11543 if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11546 // Find a legal type for the vector store.
11547 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11548 if (TLI.isTypeLegal(Ty) &&
11549 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11550 FirstStoreAlign, &IsFast) && IsFast)
11551 LastLegalVectorType = i + 1;
11555 // Check if we found a legal integer type to store.
11556 if (LastLegalType == 0 && LastLegalVectorType == 0)
11559 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11560 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11562 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11566 // When extracting multiple vector elements, try to store them
11567 // in one vector store rather than a sequence of scalar stores.
11568 if (IsExtractVecSrc) {
11569 unsigned NumStoresToMerge = 0;
11570 bool IsVec = MemVT.isVector();
11571 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11572 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11573 unsigned StoreValOpcode = St->getValue().getOpcode();
11574 // This restriction could be loosened.
11575 // Bail out if any stored values are not elements extracted from a vector.
11576 // It should be possible to handle mixed sources, but load sources need
11577 // more careful handling (see the block of code below that handles
11578 // consecutive loads).
11579 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11580 StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11583 // Find a legal type for the vector store.
11584 unsigned Elts = i + 1;
11586 // When merging vector stores, get the total number of elements.
11587 Elts *= MemVT.getVectorNumElements();
11589 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11591 if (TLI.isTypeLegal(Ty) &&
11592 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11593 FirstStoreAlign, &IsFast) && IsFast)
11594 NumStoresToMerge = i + 1;
11597 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11601 // Below we handle the case of multiple consecutive stores that
11602 // come from multiple consecutive loads. We merge them into a single
11603 // wide load and a single wide store.
11605 // Look for load nodes which are used by the stored values.
11606 SmallVector<MemOpLink, 8> LoadNodes;
11608 // Find acceptable loads. Loads need to have the same chain (token factor),
11609 // must not be zext, volatile, indexed, and they must be consecutive.
11610 BaseIndexOffset LdBasePtr;
11611 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11612 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11613 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11616 // Loads must only have one use.
11617 if (!Ld->hasNUsesOfValue(1, 0))
11620 // The memory operands must not be volatile.
11621 if (Ld->isVolatile() || Ld->isIndexed())
11624 // We do not accept ext loads.
11625 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11628 // The stored memory type must be the same.
11629 if (Ld->getMemoryVT() != MemVT)
11632 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11633 // If this is not the first ptr that we check.
11634 if (LdBasePtr.Base.getNode()) {
11635 // The base ptr must be the same.
11636 if (!LdPtr.equalBaseIndex(LdBasePtr))
11639 // Check that all other base pointers are the same as this one.
11643 // We found a potential memory operand to merge.
11644 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11647 if (LoadNodes.size() < 2)
11650 // If we have load/store pair instructions and we only have two values,
11652 unsigned RequiredAlignment;
11653 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11654 St->getAlignment() >= RequiredAlignment)
11657 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11658 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11659 unsigned FirstLoadAlign = FirstLoad->getAlignment();
11661 // Scan the memory operations on the chain and find the first non-consecutive
11662 // load memory address. These variables hold the index in the store node
11664 unsigned LastConsecutiveLoad = 0;
11665 // This variable refers to the size and not index in the array.
11666 unsigned LastLegalVectorType = 0;
11667 unsigned LastLegalIntegerType = 0;
11668 StartAddress = LoadNodes[0].OffsetFromBase;
11669 SDValue FirstChain = FirstLoad->getChain();
11670 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11671 // All loads must share the same chain.
11672 if (LoadNodes[i].MemNode->getChain() != FirstChain)
11675 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11676 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11678 LastConsecutiveLoad = i;
11679 // Find a legal type for the vector store.
11680 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11681 bool IsFastSt, IsFastLd;
11682 if (TLI.isTypeLegal(StoreTy) &&
11683 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11684 FirstStoreAlign, &IsFastSt) && IsFastSt &&
11685 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11686 FirstLoadAlign, &IsFastLd) && IsFastLd) {
11687 LastLegalVectorType = i + 1;
11690 // Find a legal type for the integer store.
11691 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11692 StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11693 if (TLI.isTypeLegal(StoreTy) &&
11694 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11695 FirstStoreAlign, &IsFastSt) && IsFastSt &&
11696 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11697 FirstLoadAlign, &IsFastLd) && IsFastLd)
11698 LastLegalIntegerType = i + 1;
11699 // Or check whether a truncstore and extload is legal.
11700 else if (TLI.getTypeAction(Context, StoreTy) ==
11701 TargetLowering::TypePromoteInteger) {
11702 EVT LegalizedStoredValueTy =
11703 TLI.getTypeToTransformTo(Context, StoreTy);
11704 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11705 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11706 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11707 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11708 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11709 FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11711 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11712 FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11714 LastLegalIntegerType = i+1;
11718 // Only use vector types if the vector type is larger than the integer type.
11719 // If they are the same, use integers.
11720 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11721 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11723 // We add +1 here because the LastXXX variables refer to location while
11724 // the NumElem refers to array/index size.
11725 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11726 NumElem = std::min(LastLegalType, NumElem);
11731 // Collect the chains from all merged stores.
11732 SmallVector<SDValue, 8> MergeStoreChains;
11733 MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
11735 // The latest Node in the DAG.
11736 unsigned LatestNodeUsed = 0;
11737 for (unsigned i=1; i<NumElem; ++i) {
11738 // Find a chain for the new wide-store operand. Notice that some
11739 // of the store nodes that we found may not be selected for inclusion
11740 // in the wide store. The chain we use needs to be the chain of the
11741 // latest store node which is *used* and replaced by the wide store.
11742 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11743 LatestNodeUsed = i;
11745 MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
11748 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11750 // Find if it is better to use vectors or integers to load and store
11754 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11756 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11757 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11760 SDLoc LoadDL(LoadNodes[0].MemNode);
11761 SDLoc StoreDL(StoreNodes[0].MemNode);
11763 // The merged loads are required to have the same incoming chain, so
11764 // using the first's chain is acceptable.
11765 SDValue NewLoad = DAG.getLoad(
11766 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11767 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11769 SDValue NewStoreChain =
11770 DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
11772 SDValue NewStore = DAG.getStore(
11773 NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
11774 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11776 // Transfer chain users from old loads to the new load.
11777 for (unsigned i = 0; i < NumElem; ++i) {
11778 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11779 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11780 SDValue(NewLoad.getNode(), 1));
11783 // Replace the last store with the new store.
11784 CombineTo(LatestOp, NewStore);
11785 // Erase all other stores.
11786 for (unsigned i = 0; i < NumElem ; ++i) {
11787 // Remove all Store nodes.
11788 if (StoreNodes[i].MemNode == LatestOp)
11790 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11791 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11792 deleteAndRecombine(St);
11798 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11802 // Replace the chain to avoid dependency.
11803 if (ST->isTruncatingStore()) {
11804 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11805 ST->getBasePtr(), ST->getMemoryVT(),
11806 ST->getMemOperand());
11808 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11809 ST->getMemOperand());
11812 // Create token to keep both nodes around.
11813 SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11814 MVT::Other, ST->getChain(), ReplStore);
11816 // Make sure the new and old chains are cleaned up.
11817 AddToWorklist(Token.getNode());
11819 // Don't add users to work list.
11820 return CombineTo(ST, Token, false);
11823 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
11824 SDValue Value = ST->getValue();
11825 if (Value.getOpcode() == ISD::TargetConstantFP)
11830 SDValue Chain = ST->getChain();
11831 SDValue Ptr = ST->getBasePtr();
11833 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
11835 // NOTE: If the original store is volatile, this transform must not increase
11836 // the number of stores. For example, on x86-32 an f64 can be stored in one
11837 // processor operation but an i64 (which is not legal) requires two. So the
11838 // transform should not be done in this case.
11841 switch (CFP->getSimpleValueType(0).SimpleTy) {
11843 llvm_unreachable("Unknown FP type");
11844 case MVT::f16: // We don't do this for these yet.
11850 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11851 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11853 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11854 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11856 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
11861 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11862 !ST->isVolatile()) ||
11863 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11865 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11866 getZExtValue(), SDLoc(CFP), MVT::i64);
11867 return DAG.getStore(Chain, DL, Tmp,
11868 Ptr, ST->getMemOperand());
11871 if (!ST->isVolatile() &&
11872 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11873 // Many FP stores are not made apparent until after legalize, e.g. for
11874 // argument passing. Since this is so common, custom legalize the
11875 // 64-bit integer store into two 32-bit stores.
11876 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11877 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11878 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11879 if (DAG.getDataLayout().isBigEndian())
11882 unsigned Alignment = ST->getAlignment();
11883 bool isVolatile = ST->isVolatile();
11884 bool isNonTemporal = ST->isNonTemporal();
11885 AAMDNodes AAInfo = ST->getAAInfo();
11887 SDValue St0 = DAG.getStore(Chain, DL, Lo,
11888 Ptr, ST->getPointerInfo(),
11889 isVolatile, isNonTemporal,
11890 ST->getAlignment(), AAInfo);
11891 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11892 DAG.getConstant(4, DL, Ptr.getValueType()));
11893 Alignment = MinAlign(Alignment, 4U);
11894 SDValue St1 = DAG.getStore(Chain, DL, Hi,
11895 Ptr, ST->getPointerInfo().getWithOffset(4),
11896 isVolatile, isNonTemporal,
11897 Alignment, AAInfo);
11898 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11906 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11907 StoreSDNode *ST = cast<StoreSDNode>(N);
11908 SDValue Chain = ST->getChain();
11909 SDValue Value = ST->getValue();
11910 SDValue Ptr = ST->getBasePtr();
11912 // If this is a store of a bit convert, store the input value if the
11913 // resultant store does not need a higher alignment than the original.
11914 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11915 ST->isUnindexed()) {
11916 unsigned OrigAlign = ST->getAlignment();
11917 EVT SVT = Value.getOperand(0).getValueType();
11918 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11919 SVT.getTypeForEVT(*DAG.getContext()));
11920 if (Align <= OrigAlign &&
11921 ((!LegalOperations && !ST->isVolatile()) ||
11922 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11923 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11924 Ptr, ST->getPointerInfo(), ST->isVolatile(),
11925 ST->isNonTemporal(), OrigAlign,
11929 // Turn 'store undef, Ptr' -> nothing.
11930 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11933 // Try to infer better alignment information than the store already has.
11934 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11935 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11936 if (Align > ST->getAlignment()) {
11938 DAG.getTruncStore(Chain, SDLoc(N), Value,
11939 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11940 ST->isVolatile(), ST->isNonTemporal(), Align,
11942 if (NewStore.getNode() != N)
11943 return CombineTo(ST, NewStore, true);
11948 // Try transforming a pair floating point load / store ops to integer
11949 // load / store ops.
11950 if (SDValue NewST = TransformFPLoadStorePair(N))
11953 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11954 : DAG.getSubtarget().useAA();
11956 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11957 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11960 if (UseAA && ST->isUnindexed()) {
11961 // FIXME: We should do this even without AA enabled. AA will just allow
11962 // FindBetterChain to work in more situations. The problem with this is that
11963 // any combine that expects memory operations to be on consecutive chains
11964 // first needs to be updated to look for users of the same chain.
11966 // Walk up chain skipping non-aliasing memory nodes, on this store and any
11967 // adjacent stores.
11968 if (findBetterNeighborChains(ST)) {
11969 // replaceStoreChain uses CombineTo, which handled all of the worklist
11970 // manipulation. Return the original node to not do anything else.
11971 return SDValue(ST, 0);
11975 // Try transforming N to an indexed store.
11976 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11977 return SDValue(N, 0);
11979 // FIXME: is there such a thing as a truncating indexed store?
11980 if (ST->isTruncatingStore() && ST->isUnindexed() &&
11981 Value.getValueType().isInteger()) {
11982 // See if we can simplify the input to this truncstore with knowledge that
11983 // only the low bits are being used. For example:
11984 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
11986 GetDemandedBits(Value,
11987 APInt::getLowBitsSet(
11988 Value.getValueType().getScalarType().getSizeInBits(),
11989 ST->getMemoryVT().getScalarType().getSizeInBits()));
11990 AddToWorklist(Value.getNode());
11991 if (Shorter.getNode())
11992 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11993 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11995 // Otherwise, see if we can simplify the operation with
11996 // SimplifyDemandedBits, which only works if the value has a single use.
11997 if (SimplifyDemandedBits(Value,
11998 APInt::getLowBitsSet(
11999 Value.getValueType().getScalarType().getSizeInBits(),
12000 ST->getMemoryVT().getScalarType().getSizeInBits())))
12001 return SDValue(N, 0);
12004 // If this is a load followed by a store to the same location, then the store
12006 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
12007 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
12008 ST->isUnindexed() && !ST->isVolatile() &&
12009 // There can't be any side effects between the load and store, such as
12010 // a call or store.
12011 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
12012 // The store is dead, remove it.
12017 // If this is a store followed by a store with the same value to the same
12018 // location, then the store is dead/noop.
12019 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
12020 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
12021 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
12022 ST1->isUnindexed() && !ST1->isVolatile()) {
12023 // The store is dead, remove it.
12028 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
12029 // truncating store. We can do this even if this is already a truncstore.
12030 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
12031 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
12032 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
12033 ST->getMemoryVT())) {
12034 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
12035 Ptr, ST->getMemoryVT(), ST->getMemOperand());
12038 // Only perform this optimization before the types are legal, because we
12039 // don't want to perform this optimization on every DAGCombine invocation.
12041 bool EverChanged = false;
12044 // There can be multiple store sequences on the same chain.
12045 // Keep trying to merge store sequences until we are unable to do so
12046 // or until we merge the last store on the chain.
12047 bool Changed = MergeConsecutiveStores(ST);
12048 EverChanged |= Changed;
12049 if (!Changed) break;
12050 } while (ST->getOpcode() != ISD::DELETED_NODE);
12053 return SDValue(N, 0);
12056 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
12058 // Make sure to do this only after attempting to merge stores in order to
12059 // avoid changing the types of some subset of stores due to visit order,
12060 // preventing their merging.
12061 if (isa<ConstantFPSDNode>(Value)) {
12062 if (SDValue NewSt = replaceStoreOfFPConstant(ST))
12066 return ReduceLoadOpStoreWidth(N);
12069 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
12070 SDValue InVec = N->getOperand(0);
12071 SDValue InVal = N->getOperand(1);
12072 SDValue EltNo = N->getOperand(2);
12075 // If the inserted element is an UNDEF, just use the input vector.
12076 if (InVal.getOpcode() == ISD::UNDEF)
12079 EVT VT = InVec.getValueType();
12081 // If we can't generate a legal BUILD_VECTOR, exit
12082 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
12085 // Check that we know which element is being inserted
12086 if (!isa<ConstantSDNode>(EltNo))
12088 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12090 // Canonicalize insert_vector_elt dag nodes.
12092 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
12093 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
12095 // Do this only if the child insert_vector node has one use; also
12096 // do this only if indices are both constants and Idx1 < Idx0.
12097 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
12098 && isa<ConstantSDNode>(InVec.getOperand(2))) {
12099 unsigned OtherElt =
12100 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
12101 if (Elt < OtherElt) {
12103 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
12104 InVec.getOperand(0), InVal, EltNo);
12105 AddToWorklist(NewOp.getNode());
12106 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
12107 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
12111 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
12112 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
12113 // vector elements.
12114 SmallVector<SDValue, 8> Ops;
12115 // Do not combine these two vectors if the output vector will not replace
12116 // the input vector.
12117 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
12118 Ops.append(InVec.getNode()->op_begin(),
12119 InVec.getNode()->op_end());
12120 } else if (InVec.getOpcode() == ISD::UNDEF) {
12121 unsigned NElts = VT.getVectorNumElements();
12122 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
12127 // Insert the element
12128 if (Elt < Ops.size()) {
12129 // All the operands of BUILD_VECTOR must have the same type;
12130 // we enforce that here.
12131 EVT OpVT = Ops[0].getValueType();
12132 if (InVal.getValueType() != OpVT)
12133 InVal = OpVT.bitsGT(InVal.getValueType()) ?
12134 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
12135 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
12139 // Return the new vector
12140 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
12143 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
12144 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
12145 EVT ResultVT = EVE->getValueType(0);
12146 EVT VecEltVT = InVecVT.getVectorElementType();
12147 unsigned Align = OriginalLoad->getAlignment();
12148 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
12149 VecEltVT.getTypeForEVT(*DAG.getContext()));
12151 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
12156 SDValue NewPtr = OriginalLoad->getBasePtr();
12158 EVT PtrType = NewPtr.getValueType();
12159 MachinePointerInfo MPI;
12161 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
12162 int Elt = ConstEltNo->getZExtValue();
12163 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
12164 Offset = DAG.getConstant(PtrOff, DL, PtrType);
12165 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
12167 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
12168 Offset = DAG.getNode(
12169 ISD::MUL, DL, PtrType, Offset,
12170 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
12171 MPI = OriginalLoad->getPointerInfo();
12173 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
12175 // The replacement we need to do here is a little tricky: we need to
12176 // replace an extractelement of a load with a load.
12177 // Use ReplaceAllUsesOfValuesWith to do the replacement.
12178 // Note that this replacement assumes that the extractvalue is the only
12179 // use of the load; that's okay because we don't want to perform this
12180 // transformation in other cases anyway.
12183 if (ResultVT.bitsGT(VecEltVT)) {
12184 // If the result type of vextract is wider than the load, then issue an
12185 // extending load instead.
12186 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
12190 Load = DAG.getExtLoad(
12191 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
12192 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
12193 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
12194 Chain = Load.getValue(1);
12196 Load = DAG.getLoad(
12197 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
12198 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
12199 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
12200 Chain = Load.getValue(1);
12201 if (ResultVT.bitsLT(VecEltVT))
12202 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
12204 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
12206 WorklistRemover DeadNodes(*this);
12207 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
12208 SDValue To[] = { Load, Chain };
12209 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
12210 // Since we're explicitly calling ReplaceAllUses, add the new node to the
12211 // worklist explicitly as well.
12212 AddToWorklist(Load.getNode());
12213 AddUsersToWorklist(Load.getNode()); // Add users too
12214 // Make sure to revisit this node to clean it up; it will usually be dead.
12215 AddToWorklist(EVE);
12217 return SDValue(EVE, 0);
12220 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
12221 // (vextract (scalar_to_vector val, 0) -> val
12222 SDValue InVec = N->getOperand(0);
12223 EVT VT = InVec.getValueType();
12224 EVT NVT = N->getValueType(0);
12226 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
12227 // Check if the result type doesn't match the inserted element type. A
12228 // SCALAR_TO_VECTOR may truncate the inserted element and the
12229 // EXTRACT_VECTOR_ELT may widen the extracted vector.
12230 SDValue InOp = InVec.getOperand(0);
12231 if (InOp.getValueType() != NVT) {
12232 assert(InOp.getValueType().isInteger() && NVT.isInteger());
12233 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
12238 SDValue EltNo = N->getOperand(1);
12239 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
12241 // extract_vector_elt (build_vector x, y), 1 -> y
12243 InVec.getOpcode() == ISD::BUILD_VECTOR &&
12244 TLI.isTypeLegal(VT) &&
12245 (InVec.hasOneUse() ||
12246 TLI.aggressivelyPreferBuildVectorSources(VT))) {
12247 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
12248 EVT InEltVT = Elt.getValueType();
12250 // Sometimes build_vector's scalar input types do not match result type.
12251 if (NVT == InEltVT)
12254 // TODO: It may be useful to truncate if free if the build_vector implicitly
12258 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
12259 // We only perform this optimization before the op legalization phase because
12260 // we may introduce new vector instructions which are not backed by TD
12261 // patterns. For example on AVX, extracting elements from a wide vector
12262 // without using extract_subvector. However, if we can find an underlying
12263 // scalar value, then we can always use that.
12264 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
12265 int NumElem = VT.getVectorNumElements();
12266 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
12267 // Find the new index to extract from.
12268 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
12270 // Extracting an undef index is undef.
12272 return DAG.getUNDEF(NVT);
12274 // Select the right vector half to extract from.
12276 if (OrigElt < NumElem) {
12277 SVInVec = InVec->getOperand(0);
12279 SVInVec = InVec->getOperand(1);
12280 OrigElt -= NumElem;
12283 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
12284 SDValue InOp = SVInVec.getOperand(OrigElt);
12285 if (InOp.getValueType() != NVT) {
12286 assert(InOp.getValueType().isInteger() && NVT.isInteger());
12287 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
12293 // FIXME: We should handle recursing on other vector shuffles and
12294 // scalar_to_vector here as well.
12296 if (!LegalOperations) {
12297 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12298 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
12299 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
12303 bool BCNumEltsChanged = false;
12304 EVT ExtVT = VT.getVectorElementType();
12307 // If the result of load has to be truncated, then it's not necessarily
12309 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
12312 if (InVec.getOpcode() == ISD::BITCAST) {
12313 // Don't duplicate a load with other uses.
12314 if (!InVec.hasOneUse())
12317 EVT BCVT = InVec.getOperand(0).getValueType();
12318 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
12320 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
12321 BCNumEltsChanged = true;
12322 InVec = InVec.getOperand(0);
12323 ExtVT = BCVT.getVectorElementType();
12326 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
12327 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
12328 ISD::isNormalLoad(InVec.getNode()) &&
12329 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
12330 SDValue Index = N->getOperand(1);
12331 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
12332 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
12336 // Perform only after legalization to ensure build_vector / vector_shuffle
12337 // optimizations have already been done.
12338 if (!LegalOperations) return SDValue();
12340 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
12341 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
12342 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
12345 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12347 LoadSDNode *LN0 = nullptr;
12348 const ShuffleVectorSDNode *SVN = nullptr;
12349 if (ISD::isNormalLoad(InVec.getNode())) {
12350 LN0 = cast<LoadSDNode>(InVec);
12351 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
12352 InVec.getOperand(0).getValueType() == ExtVT &&
12353 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
12354 // Don't duplicate a load with other uses.
12355 if (!InVec.hasOneUse())
12358 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
12359 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
12360 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
12362 // (load $addr+1*size)
12364 // Don't duplicate a load with other uses.
12365 if (!InVec.hasOneUse())
12368 // If the bit convert changed the number of elements, it is unsafe
12369 // to examine the mask.
12370 if (BCNumEltsChanged)
12373 // Select the input vector, guarding against out of range extract vector.
12374 unsigned NumElems = VT.getVectorNumElements();
12375 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
12376 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
12378 if (InVec.getOpcode() == ISD::BITCAST) {
12379 // Don't duplicate a load with other uses.
12380 if (!InVec.hasOneUse())
12383 InVec = InVec.getOperand(0);
12385 if (ISD::isNormalLoad(InVec.getNode())) {
12386 LN0 = cast<LoadSDNode>(InVec);
12387 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12388 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12392 // Make sure we found a non-volatile load and the extractelement is
12394 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12397 // If Idx was -1 above, Elt is going to be -1, so just return undef.
12399 return DAG.getUNDEF(LVT);
12401 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12407 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12408 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12409 // We perform this optimization post type-legalization because
12410 // the type-legalizer often scalarizes integer-promoted vectors.
12411 // Performing this optimization before may create bit-casts which
12412 // will be type-legalized to complex code sequences.
12413 // We perform this optimization only before the operation legalizer because we
12414 // may introduce illegal operations.
12415 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12418 unsigned NumInScalars = N->getNumOperands();
12420 EVT VT = N->getValueType(0);
12422 // Check to see if this is a BUILD_VECTOR of a bunch of values
12423 // which come from any_extend or zero_extend nodes. If so, we can create
12424 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12425 // optimizations. We do not handle sign-extend because we can't fill the sign
12427 EVT SourceType = MVT::Other;
12428 bool AllAnyExt = true;
12430 for (unsigned i = 0; i != NumInScalars; ++i) {
12431 SDValue In = N->getOperand(i);
12432 // Ignore undef inputs.
12433 if (In.getOpcode() == ISD::UNDEF) continue;
12435 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
12436 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12438 // Abort if the element is not an extension.
12439 if (!ZeroExt && !AnyExt) {
12440 SourceType = MVT::Other;
12444 // The input is a ZeroExt or AnyExt. Check the original type.
12445 EVT InTy = In.getOperand(0).getValueType();
12447 // Check that all of the widened source types are the same.
12448 if (SourceType == MVT::Other)
12451 else if (InTy != SourceType) {
12452 // Multiple income types. Abort.
12453 SourceType = MVT::Other;
12457 // Check if all of the extends are ANY_EXTENDs.
12458 AllAnyExt &= AnyExt;
12461 // In order to have valid types, all of the inputs must be extended from the
12462 // same source type and all of the inputs must be any or zero extend.
12463 // Scalar sizes must be a power of two.
12464 EVT OutScalarTy = VT.getScalarType();
12465 bool ValidTypes = SourceType != MVT::Other &&
12466 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12467 isPowerOf2_32(SourceType.getSizeInBits());
12469 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12470 // turn into a single shuffle instruction.
12474 bool isLE = DAG.getDataLayout().isLittleEndian();
12475 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12476 assert(ElemRatio > 1 && "Invalid element size ratio");
12477 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12478 DAG.getConstant(0, SDLoc(N), SourceType);
12480 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12481 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12483 // Populate the new build_vector
12484 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12485 SDValue Cast = N->getOperand(i);
12486 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12487 Cast.getOpcode() == ISD::ZERO_EXTEND ||
12488 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
12490 if (Cast.getOpcode() == ISD::UNDEF)
12491 In = DAG.getUNDEF(SourceType);
12493 In = Cast->getOperand(0);
12494 unsigned Index = isLE ? (i * ElemRatio) :
12495 (i * ElemRatio + (ElemRatio - 1));
12497 assert(Index < Ops.size() && "Invalid index");
12501 // The type of the new BUILD_VECTOR node.
12502 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12503 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12504 "Invalid vector size");
12505 // Check if the new vector type is legal.
12506 if (!isTypeLegal(VecVT)) return SDValue();
12508 // Make the new BUILD_VECTOR.
12509 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
12511 // The new BUILD_VECTOR node has the potential to be further optimized.
12512 AddToWorklist(BV.getNode());
12513 // Bitcast to the desired type.
12514 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12517 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12518 EVT VT = N->getValueType(0);
12520 unsigned NumInScalars = N->getNumOperands();
12523 EVT SrcVT = MVT::Other;
12524 unsigned Opcode = ISD::DELETED_NODE;
12525 unsigned NumDefs = 0;
12527 for (unsigned i = 0; i != NumInScalars; ++i) {
12528 SDValue In = N->getOperand(i);
12529 unsigned Opc = In.getOpcode();
12531 if (Opc == ISD::UNDEF)
12534 // If all scalar values are floats and converted from integers.
12535 if (Opcode == ISD::DELETED_NODE &&
12536 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12543 EVT InVT = In.getOperand(0).getValueType();
12545 // If all scalar values are typed differently, bail out. It's chosen to
12546 // simplify BUILD_VECTOR of integer types.
12547 if (SrcVT == MVT::Other)
12554 // If the vector has just one element defined, it's not worth to fold it into
12555 // a vectorized one.
12559 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12560 && "Should only handle conversion from integer to float.");
12561 assert(SrcVT != MVT::Other && "Cannot determine source type!");
12563 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12565 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12568 // Just because the floating-point vector type is legal does not necessarily
12569 // mean that the corresponding integer vector type is.
12570 if (!isTypeLegal(NVT))
12573 SmallVector<SDValue, 8> Opnds;
12574 for (unsigned i = 0; i != NumInScalars; ++i) {
12575 SDValue In = N->getOperand(i);
12577 if (In.getOpcode() == ISD::UNDEF)
12578 Opnds.push_back(DAG.getUNDEF(SrcVT));
12580 Opnds.push_back(In.getOperand(0));
12582 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
12583 AddToWorklist(BV.getNode());
12585 return DAG.getNode(Opcode, dl, VT, BV);
12588 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12589 unsigned NumInScalars = N->getNumOperands();
12591 EVT VT = N->getValueType(0);
12593 // A vector built entirely of undefs is undef.
12594 if (ISD::allOperandsUndef(N))
12595 return DAG.getUNDEF(VT);
12597 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12600 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12603 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12604 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12605 // at most two distinct vectors, turn this into a shuffle node.
12607 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12608 if (!isTypeLegal(VT))
12611 // May only combine to shuffle after legalize if shuffle is legal.
12612 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12615 SDValue VecIn1, VecIn2;
12616 bool UsesZeroVector = false;
12617 for (unsigned i = 0; i != NumInScalars; ++i) {
12618 SDValue Op = N->getOperand(i);
12619 // Ignore undef inputs.
12620 if (Op.getOpcode() == ISD::UNDEF) continue;
12622 // See if we can combine this build_vector into a blend with a zero vector.
12623 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12624 UsesZeroVector = true;
12628 // If this input is something other than a EXTRACT_VECTOR_ELT with a
12629 // constant index, bail out.
12630 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12631 !isa<ConstantSDNode>(Op.getOperand(1))) {
12632 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12636 // We allow up to two distinct input vectors.
12637 SDValue ExtractedFromVec = Op.getOperand(0);
12638 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12641 if (!VecIn1.getNode()) {
12642 VecIn1 = ExtractedFromVec;
12643 } else if (!VecIn2.getNode() && !UsesZeroVector) {
12644 VecIn2 = ExtractedFromVec;
12646 // Too many inputs.
12647 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12652 // If everything is good, we can make a shuffle operation.
12653 if (VecIn1.getNode()) {
12654 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12655 SmallVector<int, 8> Mask;
12656 for (unsigned i = 0; i != NumInScalars; ++i) {
12657 unsigned Opcode = N->getOperand(i).getOpcode();
12658 if (Opcode == ISD::UNDEF) {
12659 Mask.push_back(-1);
12663 // Operands can also be zero.
12664 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12665 assert(UsesZeroVector &&
12666 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12667 "Unexpected node found!");
12668 Mask.push_back(NumInScalars+i);
12672 // If extracting from the first vector, just use the index directly.
12673 SDValue Extract = N->getOperand(i);
12674 SDValue ExtVal = Extract.getOperand(1);
12675 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12676 if (Extract.getOperand(0) == VecIn1) {
12677 Mask.push_back(ExtIndex);
12681 // Otherwise, use InIdx + InputVecSize
12682 Mask.push_back(InNumElements + ExtIndex);
12685 // Avoid introducing illegal shuffles with zero.
12686 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12689 // We can't generate a shuffle node with mismatched input and output types.
12690 // Attempt to transform a single input vector to the correct type.
12691 if ((VT != VecIn1.getValueType())) {
12692 // If the input vector type has a different base type to the output
12693 // vector type, bail out.
12694 EVT VTElemType = VT.getVectorElementType();
12695 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12696 (VecIn2.getNode() &&
12697 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12700 // If the input vector is too small, widen it.
12701 // We only support widening of vectors which are half the size of the
12702 // output registers. For example XMM->YMM widening on X86 with AVX.
12703 EVT VecInT = VecIn1.getValueType();
12704 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12705 // If we only have one small input, widen it by adding undef values.
12706 if (!VecIn2.getNode())
12707 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12708 DAG.getUNDEF(VecIn1.getValueType()));
12709 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12710 // If we have two small inputs of the same type, try to concat them.
12711 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12712 VecIn2 = SDValue(nullptr, 0);
12715 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12716 // If the input vector is too large, try to split it.
12717 // We don't support having two input vectors that are too large.
12718 // If the zero vector was used, we can not split the vector,
12719 // since we'd need 3 inputs.
12720 if (UsesZeroVector || VecIn2.getNode())
12723 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12726 // Try to replace VecIn1 with two extract_subvectors
12727 // No need to update the masks, they should still be correct.
12728 VecIn2 = DAG.getNode(
12729 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12730 DAG.getConstant(VT.getVectorNumElements(), dl,
12731 TLI.getVectorIdxTy(DAG.getDataLayout())));
12732 VecIn1 = DAG.getNode(
12733 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12734 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12739 if (UsesZeroVector)
12740 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12741 DAG.getConstantFP(0.0, dl, VT);
12743 // If VecIn2 is unused then change it to undef.
12744 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12746 // Check that we were able to transform all incoming values to the same
12748 if (VecIn2.getValueType() != VecIn1.getValueType() ||
12749 VecIn1.getValueType() != VT)
12752 // Return the new VECTOR_SHUFFLE node.
12756 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12762 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12763 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12764 EVT OpVT = N->getOperand(0).getValueType();
12766 // If the operands are legal vectors, leave them alone.
12767 if (TLI.isTypeLegal(OpVT))
12771 EVT VT = N->getValueType(0);
12772 SmallVector<SDValue, 8> Ops;
12774 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12775 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12777 // Keep track of what we encounter.
12778 bool AnyInteger = false;
12779 bool AnyFP = false;
12780 for (const SDValue &Op : N->ops()) {
12781 if (ISD::BITCAST == Op.getOpcode() &&
12782 !Op.getOperand(0).getValueType().isVector())
12783 Ops.push_back(Op.getOperand(0));
12784 else if (ISD::UNDEF == Op.getOpcode())
12785 Ops.push_back(ScalarUndef);
12789 // Note whether we encounter an integer or floating point scalar.
12790 // If it's neither, bail out, it could be something weird like x86mmx.
12791 EVT LastOpVT = Ops.back().getValueType();
12792 if (LastOpVT.isFloatingPoint())
12794 else if (LastOpVT.isInteger())
12800 // If any of the operands is a floating point scalar bitcast to a vector,
12801 // use floating point types throughout, and bitcast everything.
12802 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12804 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12805 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12807 for (SDValue &Op : Ops) {
12808 if (Op.getValueType() == SVT)
12810 if (Op.getOpcode() == ISD::UNDEF)
12813 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12818 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12819 VT.getSizeInBits() / SVT.getSizeInBits());
12820 return DAG.getNode(ISD::BITCAST, DL, VT,
12821 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12824 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12825 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12826 // most two distinct vectors the same size as the result, attempt to turn this
12827 // into a legal shuffle.
12828 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12829 EVT VT = N->getValueType(0);
12830 EVT OpVT = N->getOperand(0).getValueType();
12831 int NumElts = VT.getVectorNumElements();
12832 int NumOpElts = OpVT.getVectorNumElements();
12834 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12835 SmallVector<int, 8> Mask;
12837 for (SDValue Op : N->ops()) {
12838 // Peek through any bitcast.
12839 while (Op.getOpcode() == ISD::BITCAST)
12840 Op = Op.getOperand(0);
12842 // UNDEF nodes convert to UNDEF shuffle mask values.
12843 if (Op.getOpcode() == ISD::UNDEF) {
12844 Mask.append((unsigned)NumOpElts, -1);
12848 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12851 // What vector are we extracting the subvector from and at what index?
12852 SDValue ExtVec = Op.getOperand(0);
12854 // We want the EVT of the original extraction to correctly scale the
12855 // extraction index.
12856 EVT ExtVT = ExtVec.getValueType();
12858 // Peek through any bitcast.
12859 while (ExtVec.getOpcode() == ISD::BITCAST)
12860 ExtVec = ExtVec.getOperand(0);
12862 // UNDEF nodes convert to UNDEF shuffle mask values.
12863 if (ExtVec.getOpcode() == ISD::UNDEF) {
12864 Mask.append((unsigned)NumOpElts, -1);
12868 if (!isa<ConstantSDNode>(Op.getOperand(1)))
12870 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12872 // Ensure that we are extracting a subvector from a vector the same
12873 // size as the result.
12874 if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12877 // Scale the subvector index to account for any bitcast.
12878 int NumExtElts = ExtVT.getVectorNumElements();
12879 if (0 == (NumExtElts % NumElts))
12880 ExtIdx /= (NumExtElts / NumElts);
12881 else if (0 == (NumElts % NumExtElts))
12882 ExtIdx *= (NumElts / NumExtElts);
12886 // At most we can reference 2 inputs in the final shuffle.
12887 if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) {
12889 for (int i = 0; i != NumOpElts; ++i)
12890 Mask.push_back(i + ExtIdx);
12891 } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) {
12893 for (int i = 0; i != NumOpElts; ++i)
12894 Mask.push_back(i + ExtIdx + NumElts);
12900 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
12903 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
12904 DAG.getBitcast(VT, SV1), Mask);
12907 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12908 // If we only have one input vector, we don't need to do any concatenation.
12909 if (N->getNumOperands() == 1)
12910 return N->getOperand(0);
12912 // Check if all of the operands are undefs.
12913 EVT VT = N->getValueType(0);
12914 if (ISD::allOperandsUndef(N))
12915 return DAG.getUNDEF(VT);
12917 // Optimize concat_vectors where all but the first of the vectors are undef.
12918 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12919 return Op.getOpcode() == ISD::UNDEF;
12921 SDValue In = N->getOperand(0);
12922 assert(In.getValueType().isVector() && "Must concat vectors");
12924 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12925 if (In->getOpcode() == ISD::BITCAST &&
12926 !In->getOperand(0)->getValueType(0).isVector()) {
12927 SDValue Scalar = In->getOperand(0);
12929 // If the bitcast type isn't legal, it might be a trunc of a legal type;
12930 // look through the trunc so we can still do the transform:
12931 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12932 if (Scalar->getOpcode() == ISD::TRUNCATE &&
12933 !TLI.isTypeLegal(Scalar.getValueType()) &&
12934 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12935 Scalar = Scalar->getOperand(0);
12937 EVT SclTy = Scalar->getValueType(0);
12939 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12942 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12943 VT.getSizeInBits() / SclTy.getSizeInBits());
12944 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12947 SDLoc dl = SDLoc(N);
12948 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12949 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12953 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12954 // We have already tested above for an UNDEF only concatenation.
12955 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12956 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12957 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12958 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12960 bool AllBuildVectorsOrUndefs =
12961 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12962 if (AllBuildVectorsOrUndefs) {
12963 SmallVector<SDValue, 8> Opnds;
12964 EVT SVT = VT.getScalarType();
12967 if (!SVT.isFloatingPoint()) {
12968 // If BUILD_VECTOR are from built from integer, they may have different
12969 // operand types. Get the smallest type and truncate all operands to it.
12970 bool FoundMinVT = false;
12971 for (const SDValue &Op : N->ops())
12972 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12973 EVT OpSVT = Op.getOperand(0)->getValueType(0);
12974 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12977 assert(FoundMinVT && "Concat vector type mismatch");
12980 for (const SDValue &Op : N->ops()) {
12981 EVT OpVT = Op.getValueType();
12982 unsigned NumElts = OpVT.getVectorNumElements();
12984 if (ISD::UNDEF == Op.getOpcode())
12985 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12987 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12988 if (SVT.isFloatingPoint()) {
12989 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12990 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12992 for (unsigned i = 0; i != NumElts; ++i)
12994 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12999 assert(VT.getVectorNumElements() == Opnds.size() &&
13000 "Concat vector type mismatch");
13001 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
13004 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
13005 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
13008 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
13009 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
13010 if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
13013 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
13014 // nodes often generate nop CONCAT_VECTOR nodes.
13015 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
13016 // place the incoming vectors at the exact same location.
13017 SDValue SingleSource = SDValue();
13018 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
13020 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13021 SDValue Op = N->getOperand(i);
13023 if (Op.getOpcode() == ISD::UNDEF)
13026 // Check if this is the identity extract:
13027 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13030 // Find the single incoming vector for the extract_subvector.
13031 if (SingleSource.getNode()) {
13032 if (Op.getOperand(0) != SingleSource)
13035 SingleSource = Op.getOperand(0);
13037 // Check the source type is the same as the type of the result.
13038 // If not, this concat may extend the vector, so we can not
13039 // optimize it away.
13040 if (SingleSource.getValueType() != N->getValueType(0))
13044 unsigned IdentityIndex = i * PartNumElem;
13045 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13046 // The extract index must be constant.
13050 // Check that we are reading from the identity index.
13051 if (CS->getZExtValue() != IdentityIndex)
13055 if (SingleSource.getNode())
13056 return SingleSource;
13061 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
13062 EVT NVT = N->getValueType(0);
13063 SDValue V = N->getOperand(0);
13065 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
13067 // (extract_subvec (concat V1, V2, ...), i)
13070 // Only operand 0 is checked as 'concat' assumes all inputs of the same
13072 if (V->getOperand(0).getValueType() != NVT)
13074 unsigned Idx = N->getConstantOperandVal(1);
13075 unsigned NumElems = NVT.getVectorNumElements();
13076 assert((Idx % NumElems) == 0 &&
13077 "IDX in concat is not a multiple of the result vector length.");
13078 return V->getOperand(Idx / NumElems);
13082 if (V->getOpcode() == ISD::BITCAST)
13083 V = V.getOperand(0);
13085 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
13087 // Handle only simple case where vector being inserted and vector
13088 // being extracted are of same type, and are half size of larger vectors.
13089 EVT BigVT = V->getOperand(0).getValueType();
13090 EVT SmallVT = V->getOperand(1).getValueType();
13091 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
13094 // Only handle cases where both indexes are constants with the same type.
13095 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
13096 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
13098 if (InsIdx && ExtIdx &&
13099 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
13100 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
13102 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
13104 // indices are equal or bit offsets are equal => V1
13105 // otherwise => (extract_subvec V1, ExtIdx)
13106 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
13107 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
13108 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
13109 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
13110 DAG.getNode(ISD::BITCAST, dl,
13111 N->getOperand(0).getValueType(),
13112 V->getOperand(0)), N->getOperand(1));
13119 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
13120 SDValue V, SelectionDAG &DAG) {
13122 EVT VT = V.getValueType();
13124 switch (V.getOpcode()) {
13128 case ISD::CONCAT_VECTORS: {
13129 EVT OpVT = V->getOperand(0).getValueType();
13130 int OpSize = OpVT.getVectorNumElements();
13131 SmallBitVector OpUsedElements(OpSize, false);
13132 bool FoundSimplification = false;
13133 SmallVector<SDValue, 4> NewOps;
13134 NewOps.reserve(V->getNumOperands());
13135 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
13136 SDValue Op = V->getOperand(i);
13137 bool OpUsed = false;
13138 for (int j = 0; j < OpSize; ++j)
13139 if (UsedElements[i * OpSize + j]) {
13140 OpUsedElements[j] = true;
13144 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
13145 : DAG.getUNDEF(OpVT));
13146 FoundSimplification |= Op == NewOps.back();
13147 OpUsedElements.reset();
13149 if (FoundSimplification)
13150 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
13154 case ISD::INSERT_SUBVECTOR: {
13155 SDValue BaseV = V->getOperand(0);
13156 SDValue SubV = V->getOperand(1);
13157 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
13161 int SubSize = SubV.getValueType().getVectorNumElements();
13162 int Idx = IdxN->getZExtValue();
13163 bool SubVectorUsed = false;
13164 SmallBitVector SubUsedElements(SubSize, false);
13165 for (int i = 0; i < SubSize; ++i)
13166 if (UsedElements[i + Idx]) {
13167 SubVectorUsed = true;
13168 SubUsedElements[i] = true;
13169 UsedElements[i + Idx] = false;
13172 // Now recurse on both the base and sub vectors.
13173 SDValue SimplifiedSubV =
13175 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
13176 : DAG.getUNDEF(SubV.getValueType());
13177 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
13178 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
13179 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
13180 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
13186 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
13187 SDValue N1, SelectionDAG &DAG) {
13188 EVT VT = SVN->getValueType(0);
13189 int NumElts = VT.getVectorNumElements();
13190 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
13191 for (int M : SVN->getMask())
13192 if (M >= 0 && M < NumElts)
13193 N0UsedElements[M] = true;
13194 else if (M >= NumElts)
13195 N1UsedElements[M - NumElts] = true;
13197 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
13198 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
13199 if (S0 == N0 && S1 == N1)
13202 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
13205 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
13206 // or turn a shuffle of a single concat into simpler shuffle then concat.
13207 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
13208 EVT VT = N->getValueType(0);
13209 unsigned NumElts = VT.getVectorNumElements();
13211 SDValue N0 = N->getOperand(0);
13212 SDValue N1 = N->getOperand(1);
13213 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13215 SmallVector<SDValue, 4> Ops;
13216 EVT ConcatVT = N0.getOperand(0).getValueType();
13217 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
13218 unsigned NumConcats = NumElts / NumElemsPerConcat;
13220 // Special case: shuffle(concat(A,B)) can be more efficiently represented
13221 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
13222 // half vector elements.
13223 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
13224 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
13225 SVN->getMask().end(), [](int i) { return i == -1; })) {
13226 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
13227 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
13228 N1 = DAG.getUNDEF(ConcatVT);
13229 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
13232 // Look at every vector that's inserted. We're looking for exact
13233 // subvector-sized copies from a concatenated vector
13234 for (unsigned I = 0; I != NumConcats; ++I) {
13235 // Make sure we're dealing with a copy.
13236 unsigned Begin = I * NumElemsPerConcat;
13237 bool AllUndef = true, NoUndef = true;
13238 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
13239 if (SVN->getMaskElt(J) >= 0)
13246 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
13249 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
13250 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
13253 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
13254 if (FirstElt < N0.getNumOperands())
13255 Ops.push_back(N0.getOperand(FirstElt));
13257 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
13259 } else if (AllUndef) {
13260 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
13261 } else { // Mixed with general masks and undefs, can't do optimization.
13266 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
13269 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
13270 EVT VT = N->getValueType(0);
13271 unsigned NumElts = VT.getVectorNumElements();
13273 SDValue N0 = N->getOperand(0);
13274 SDValue N1 = N->getOperand(1);
13276 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
13278 // Canonicalize shuffle undef, undef -> undef
13279 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
13280 return DAG.getUNDEF(VT);
13282 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13284 // Canonicalize shuffle v, v -> v, undef
13286 SmallVector<int, 8> NewMask;
13287 for (unsigned i = 0; i != NumElts; ++i) {
13288 int Idx = SVN->getMaskElt(i);
13289 if (Idx >= (int)NumElts) Idx -= NumElts;
13290 NewMask.push_back(Idx);
13292 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
13296 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
13297 if (N0.getOpcode() == ISD::UNDEF) {
13298 SmallVector<int, 8> NewMask;
13299 for (unsigned i = 0; i != NumElts; ++i) {
13300 int Idx = SVN->getMaskElt(i);
13302 if (Idx >= (int)NumElts)
13305 Idx = -1; // remove reference to lhs
13307 NewMask.push_back(Idx);
13309 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
13313 // Remove references to rhs if it is undef
13314 if (N1.getOpcode() == ISD::UNDEF) {
13315 bool Changed = false;
13316 SmallVector<int, 8> NewMask;
13317 for (unsigned i = 0; i != NumElts; ++i) {
13318 int Idx = SVN->getMaskElt(i);
13319 if (Idx >= (int)NumElts) {
13323 NewMask.push_back(Idx);
13326 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
13329 // If it is a splat, check if the argument vector is another splat or a
13331 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
13332 SDNode *V = N0.getNode();
13334 // If this is a bit convert that changes the element type of the vector but
13335 // not the number of vector elements, look through it. Be careful not to
13336 // look though conversions that change things like v4f32 to v2f64.
13337 if (V->getOpcode() == ISD::BITCAST) {
13338 SDValue ConvInput = V->getOperand(0);
13339 if (ConvInput.getValueType().isVector() &&
13340 ConvInput.getValueType().getVectorNumElements() == NumElts)
13341 V = ConvInput.getNode();
13344 if (V->getOpcode() == ISD::BUILD_VECTOR) {
13345 assert(V->getNumOperands() == NumElts &&
13346 "BUILD_VECTOR has wrong number of operands");
13348 bool AllSame = true;
13349 for (unsigned i = 0; i != NumElts; ++i) {
13350 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
13351 Base = V->getOperand(i);
13355 // Splat of <u, u, u, u>, return <u, u, u, u>
13356 if (!Base.getNode())
13358 for (unsigned i = 0; i != NumElts; ++i) {
13359 if (V->getOperand(i) != Base) {
13364 // Splat of <x, x, x, x>, return <x, x, x, x>
13368 // Canonicalize any other splat as a build_vector.
13369 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
13370 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
13371 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
13372 V->getValueType(0), Ops);
13374 // We may have jumped through bitcasts, so the type of the
13375 // BUILD_VECTOR may not match the type of the shuffle.
13376 if (V->getValueType(0) != VT)
13377 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
13382 // There are various patterns used to build up a vector from smaller vectors,
13383 // subvectors, or elements. Scan chains of these and replace unused insertions
13384 // or components with undef.
13385 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13388 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13389 Level < AfterLegalizeVectorOps &&
13390 (N1.getOpcode() == ISD::UNDEF ||
13391 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13392 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13393 SDValue V = partitionShuffleOfConcats(N, DAG);
13399 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13400 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13401 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
13402 SmallVector<SDValue, 8> Ops;
13403 for (int M : SVN->getMask()) {
13404 SDValue Op = DAG.getUNDEF(VT.getScalarType());
13406 int Idx = M % NumElts;
13407 SDValue &S = (M < (int)NumElts ? N0 : N1);
13408 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
13409 Op = S.getOperand(Idx);
13410 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
13412 Op = S.getOperand(0);
13414 // Operand can't be combined - bail out.
13420 if (Ops.size() == VT.getVectorNumElements()) {
13421 // BUILD_VECTOR requires all inputs to be of the same type, find the
13422 // maximum type and extend them all.
13423 EVT SVT = VT.getScalarType();
13424 if (SVT.isInteger())
13425 for (SDValue &Op : Ops)
13426 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13427 if (SVT != VT.getScalarType())
13428 for (SDValue &Op : Ops)
13429 Op = TLI.isZExtFree(Op.getValueType(), SVT)
13430 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
13431 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
13432 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
13436 // If this shuffle only has a single input that is a bitcasted shuffle,
13437 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13438 // back to their original types.
13439 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13440 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
13441 TLI.isTypeLegal(VT)) {
13443 // Peek through the bitcast only if there is one user.
13445 while (BC0.getOpcode() == ISD::BITCAST) {
13446 if (!BC0.hasOneUse())
13448 BC0 = BC0.getOperand(0);
13451 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13453 return SmallVector<int, 8>(Mask.begin(), Mask.end());
13455 SmallVector<int, 8> NewMask;
13457 for (int s = 0; s != Scale; ++s)
13458 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13462 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13463 EVT SVT = VT.getScalarType();
13464 EVT InnerVT = BC0->getValueType(0);
13465 EVT InnerSVT = InnerVT.getScalarType();
13467 // Determine which shuffle works with the smaller scalar type.
13468 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13469 EVT ScaleSVT = ScaleVT.getScalarType();
13471 if (TLI.isTypeLegal(ScaleVT) &&
13472 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13473 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13475 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13476 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13478 // Scale the shuffle masks to the smaller scalar type.
13479 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13480 SmallVector<int, 8> InnerMask =
13481 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13482 SmallVector<int, 8> OuterMask =
13483 ScaleShuffleMask(SVN->getMask(), OuterScale);
13485 // Merge the shuffle masks.
13486 SmallVector<int, 8> NewMask;
13487 for (int M : OuterMask)
13488 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13490 // Test for shuffle mask legality over both commutations.
13491 SDValue SV0 = BC0->getOperand(0);
13492 SDValue SV1 = BC0->getOperand(1);
13493 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13495 std::swap(SV0, SV1);
13496 ShuffleVectorSDNode::commuteMask(NewMask);
13497 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13501 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
13502 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
13503 return DAG.getNode(
13504 ISD::BITCAST, SDLoc(N), VT,
13505 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13511 // Canonicalize shuffles according to rules:
13512 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13513 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13514 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13515 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13516 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
13517 TLI.isTypeLegal(VT)) {
13518 // The incoming shuffle must be of the same type as the result of the
13519 // current shuffle.
13520 assert(N1->getOperand(0).getValueType() == VT &&
13521 "Shuffle types don't match");
13523 SDValue SV0 = N1->getOperand(0);
13524 SDValue SV1 = N1->getOperand(1);
13525 bool HasSameOp0 = N0 == SV0;
13526 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
13527 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13528 // Commute the operands of this shuffle so that next rule
13530 return DAG.getCommutedVectorShuffle(*SVN);
13533 // Try to fold according to rules:
13534 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13535 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13536 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13537 // Don't try to fold shuffles with illegal type.
13538 // Only fold if this shuffle is the only user of the other shuffle.
13539 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13540 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13541 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13543 // The incoming shuffle must be of the same type as the result of the
13544 // current shuffle.
13545 assert(OtherSV->getOperand(0).getValueType() == VT &&
13546 "Shuffle types don't match");
13549 SmallVector<int, 4> Mask;
13550 // Compute the combined shuffle mask for a shuffle with SV0 as the first
13551 // operand, and SV1 as the second operand.
13552 for (unsigned i = 0; i != NumElts; ++i) {
13553 int Idx = SVN->getMaskElt(i);
13555 // Propagate Undef.
13556 Mask.push_back(Idx);
13560 SDValue CurrentVec;
13561 if (Idx < (int)NumElts) {
13562 // This shuffle index refers to the inner shuffle N0. Lookup the inner
13563 // shuffle mask to identify which vector is actually referenced.
13564 Idx = OtherSV->getMaskElt(Idx);
13566 // Propagate Undef.
13567 Mask.push_back(Idx);
13571 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13572 : OtherSV->getOperand(1);
13574 // This shuffle index references an element within N1.
13578 // Simple case where 'CurrentVec' is UNDEF.
13579 if (CurrentVec.getOpcode() == ISD::UNDEF) {
13580 Mask.push_back(-1);
13584 // Canonicalize the shuffle index. We don't know yet if CurrentVec
13585 // will be the first or second operand of the combined shuffle.
13586 Idx = Idx % NumElts;
13587 if (!SV0.getNode() || SV0 == CurrentVec) {
13588 // Ok. CurrentVec is the left hand side.
13589 // Update the mask accordingly.
13591 Mask.push_back(Idx);
13595 // Bail out if we cannot convert the shuffle pair into a single shuffle.
13596 if (SV1.getNode() && SV1 != CurrentVec)
13599 // Ok. CurrentVec is the right hand side.
13600 // Update the mask accordingly.
13602 Mask.push_back(Idx + NumElts);
13605 // Check if all indices in Mask are Undef. In case, propagate Undef.
13606 bool isUndefMask = true;
13607 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13608 isUndefMask &= Mask[i] < 0;
13611 return DAG.getUNDEF(VT);
13613 if (!SV0.getNode())
13614 SV0 = DAG.getUNDEF(VT);
13615 if (!SV1.getNode())
13616 SV1 = DAG.getUNDEF(VT);
13618 // Avoid introducing shuffles with illegal mask.
13619 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13620 ShuffleVectorSDNode::commuteMask(Mask);
13622 if (!TLI.isShuffleMaskLegal(Mask, VT))
13625 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13626 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13627 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13628 std::swap(SV0, SV1);
13631 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13632 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13633 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13634 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13640 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13641 SDValue InVal = N->getOperand(0);
13642 EVT VT = N->getValueType(0);
13644 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13645 // with a VECTOR_SHUFFLE.
13646 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13647 SDValue InVec = InVal->getOperand(0);
13648 SDValue EltNo = InVal->getOperand(1);
13650 // FIXME: We could support implicit truncation if the shuffle can be
13651 // scaled to a smaller vector scalar type.
13652 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13653 if (C0 && VT == InVec.getValueType() &&
13654 VT.getScalarType() == InVal.getValueType()) {
13655 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13656 int Elt = C0->getZExtValue();
13659 if (TLI.isShuffleMaskLegal(NewMask, VT))
13660 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13668 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13669 SDValue N0 = N->getOperand(0);
13670 SDValue N2 = N->getOperand(2);
13672 // If the input vector is a concatenation, and the insert replaces
13673 // one of the halves, we can optimize into a single concat_vectors.
13674 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13675 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13676 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13677 EVT VT = N->getValueType(0);
13679 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13680 // (concat_vectors Z, Y)
13682 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13683 N->getOperand(1), N0.getOperand(1));
13685 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13686 // (concat_vectors X, Z)
13687 if (InsIdx == VT.getVectorNumElements()/2)
13688 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13689 N0.getOperand(0), N->getOperand(1));
13695 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13696 SDValue N0 = N->getOperand(0);
13698 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13699 if (N0->getOpcode() == ISD::FP16_TO_FP)
13700 return N0->getOperand(0);
13705 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13706 SDValue N0 = N->getOperand(0);
13708 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13709 if (N0->getOpcode() == ISD::AND) {
13710 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13711 if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13712 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13720 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13721 /// with the destination vector and a zero vector.
13722 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13723 /// vector_shuffle V, Zero, <0, 4, 2, 4>
13724 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13725 EVT VT = N->getValueType(0);
13726 SDValue LHS = N->getOperand(0);
13727 SDValue RHS = N->getOperand(1);
13730 // Make sure we're not running after operation legalization where it
13731 // may have custom lowered the vector shuffles.
13732 if (LegalOperations)
13735 if (N->getOpcode() != ISD::AND)
13738 if (RHS.getOpcode() == ISD::BITCAST)
13739 RHS = RHS.getOperand(0);
13741 if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13744 EVT RVT = RHS.getValueType();
13745 unsigned NumElts = RHS.getNumOperands();
13747 // Attempt to create a valid clear mask, splitting the mask into
13748 // sub elements and checking to see if each is
13749 // all zeros or all ones - suitable for shuffle masking.
13750 auto BuildClearMask = [&](int Split) {
13751 int NumSubElts = NumElts * Split;
13752 int NumSubBits = RVT.getScalarSizeInBits() / Split;
13754 SmallVector<int, 8> Indices;
13755 for (int i = 0; i != NumSubElts; ++i) {
13756 int EltIdx = i / Split;
13757 int SubIdx = i % Split;
13758 SDValue Elt = RHS.getOperand(EltIdx);
13759 if (Elt.getOpcode() == ISD::UNDEF) {
13760 Indices.push_back(-1);
13765 if (isa<ConstantSDNode>(Elt))
13766 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13767 else if (isa<ConstantFPSDNode>(Elt))
13768 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13772 // Extract the sub element from the constant bit mask.
13773 if (DAG.getDataLayout().isBigEndian()) {
13774 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13776 Bits = Bits.lshr(SubIdx * NumSubBits);
13780 Bits = Bits.trunc(NumSubBits);
13782 if (Bits.isAllOnesValue())
13783 Indices.push_back(i);
13784 else if (Bits == 0)
13785 Indices.push_back(i + NumSubElts);
13790 // Let's see if the target supports this vector_shuffle.
13791 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13792 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13793 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13796 SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13797 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13798 DAG.getBitcast(ClearVT, LHS),
13799 Zero, &Indices[0]));
13802 // Determine maximum split level (byte level masking).
13804 if (RVT.getScalarSizeInBits() % 8 == 0)
13805 MaxSplit = RVT.getScalarSizeInBits() / 8;
13807 for (int Split = 1; Split <= MaxSplit; ++Split)
13808 if (RVT.getScalarSizeInBits() % Split == 0)
13809 if (SDValue S = BuildClearMask(Split))
13815 /// Visit a binary vector operation, like ADD.
13816 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13817 assert(N->getValueType(0).isVector() &&
13818 "SimplifyVBinOp only works on vectors!");
13820 SDValue LHS = N->getOperand(0);
13821 SDValue RHS = N->getOperand(1);
13822 SDValue Ops[] = {LHS, RHS};
13824 // See if we can constant fold the vector operation.
13825 if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
13826 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
13829 // Try to convert a constant mask AND into a shuffle clear mask.
13830 if (SDValue Shuffle = XformToShuffleWithZero(N))
13833 // Type legalization might introduce new shuffles in the DAG.
13834 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13835 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
13836 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13837 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13838 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13839 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13840 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13841 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13843 if (SVN0->getMask().equals(SVN1->getMask())) {
13844 EVT VT = N->getValueType(0);
13845 SDValue UndefVector = LHS.getOperand(1);
13846 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13847 LHS.getOperand(0), RHS.getOperand(0),
13849 AddUsersToWorklist(N);
13850 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13851 &SVN0->getMask()[0]);
13858 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13859 SDValue N1, SDValue N2){
13860 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13862 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13863 cast<CondCodeSDNode>(N0.getOperand(2))->get());
13865 // If we got a simplified select_cc node back from SimplifySelectCC, then
13866 // break it down into a new SETCC node, and a new SELECT node, and then return
13867 // the SELECT node, since we were called with a SELECT node.
13868 if (SCC.getNode()) {
13869 // Check to see if we got a select_cc back (to turn into setcc/select).
13870 // Otherwise, just return whatever node we got back, like fabs.
13871 if (SCC.getOpcode() == ISD::SELECT_CC) {
13872 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13874 SCC.getOperand(0), SCC.getOperand(1),
13875 SCC.getOperand(4));
13876 AddToWorklist(SETCC.getNode());
13877 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13878 SCC.getOperand(2), SCC.getOperand(3));
13886 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13887 /// being selected between, see if we can simplify the select. Callers of this
13888 /// should assume that TheSelect is deleted if this returns true. As such, they
13889 /// should return the appropriate thing (e.g. the node) back to the top-level of
13890 /// the DAG combiner loop to avoid it being looked at.
13891 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13894 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13895 // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13896 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13897 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13898 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13899 SDValue Sqrt = RHS;
13902 const ConstantFPSDNode *NegZero = nullptr;
13904 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13905 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13906 CmpLHS = TheSelect->getOperand(0);
13907 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13909 // SELECT or VSELECT
13910 SDValue Cmp = TheSelect->getOperand(0);
13911 if (Cmp.getOpcode() == ISD::SETCC) {
13912 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13913 CmpLHS = Cmp.getOperand(0);
13914 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13917 if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13918 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13919 CC == ISD::SETULT || CC == ISD::SETLT)) {
13920 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13921 CombineTo(TheSelect, Sqrt);
13926 // Cannot simplify select with vector condition
13927 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13929 // If this is a select from two identical things, try to pull the operation
13930 // through the select.
13931 if (LHS.getOpcode() != RHS.getOpcode() ||
13932 !LHS.hasOneUse() || !RHS.hasOneUse())
13935 // If this is a load and the token chain is identical, replace the select
13936 // of two loads with a load through a select of the address to load from.
13937 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13938 // constants have been dropped into the constant pool.
13939 if (LHS.getOpcode() == ISD::LOAD) {
13940 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13941 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13943 // Token chains must be identical.
13944 if (LHS.getOperand(0) != RHS.getOperand(0) ||
13945 // Do not let this transformation reduce the number of volatile loads.
13946 LLD->isVolatile() || RLD->isVolatile() ||
13947 // FIXME: If either is a pre/post inc/dec load,
13948 // we'd need to split out the address adjustment.
13949 LLD->isIndexed() || RLD->isIndexed() ||
13950 // If this is an EXTLOAD, the VT's must match.
13951 LLD->getMemoryVT() != RLD->getMemoryVT() ||
13952 // If this is an EXTLOAD, the kind of extension must match.
13953 (LLD->getExtensionType() != RLD->getExtensionType() &&
13954 // The only exception is if one of the extensions is anyext.
13955 LLD->getExtensionType() != ISD::EXTLOAD &&
13956 RLD->getExtensionType() != ISD::EXTLOAD) ||
13957 // FIXME: this discards src value information. This is
13958 // over-conservative. It would be beneficial to be able to remember
13959 // both potential memory locations. Since we are discarding
13960 // src value info, don't do the transformation if the memory
13961 // locations are not in the default address space.
13962 LLD->getPointerInfo().getAddrSpace() != 0 ||
13963 RLD->getPointerInfo().getAddrSpace() != 0 ||
13964 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13965 LLD->getBasePtr().getValueType()))
13968 // Check that the select condition doesn't reach either load. If so,
13969 // folding this will induce a cycle into the DAG. If not, this is safe to
13970 // xform, so create a select of the addresses.
13972 if (TheSelect->getOpcode() == ISD::SELECT) {
13973 SDNode *CondNode = TheSelect->getOperand(0).getNode();
13974 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13975 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13977 // The loads must not depend on one another.
13978 if (LLD->isPredecessorOf(RLD) ||
13979 RLD->isPredecessorOf(LLD))
13981 Addr = DAG.getSelect(SDLoc(TheSelect),
13982 LLD->getBasePtr().getValueType(),
13983 TheSelect->getOperand(0), LLD->getBasePtr(),
13984 RLD->getBasePtr());
13985 } else { // Otherwise SELECT_CC
13986 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13987 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13989 if ((LLD->hasAnyUseOfValue(1) &&
13990 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13991 (RLD->hasAnyUseOfValue(1) &&
13992 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13995 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13996 LLD->getBasePtr().getValueType(),
13997 TheSelect->getOperand(0),
13998 TheSelect->getOperand(1),
13999 LLD->getBasePtr(), RLD->getBasePtr(),
14000 TheSelect->getOperand(4));
14004 // It is safe to replace the two loads if they have different alignments,
14005 // but the new load must be the minimum (most restrictive) alignment of the
14007 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
14008 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
14009 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
14010 Load = DAG.getLoad(TheSelect->getValueType(0),
14012 // FIXME: Discards pointer and AA info.
14013 LLD->getChain(), Addr, MachinePointerInfo(),
14014 LLD->isVolatile(), LLD->isNonTemporal(),
14015 isInvariant, Alignment);
14017 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
14018 RLD->getExtensionType() : LLD->getExtensionType(),
14020 TheSelect->getValueType(0),
14021 // FIXME: Discards pointer and AA info.
14022 LLD->getChain(), Addr, MachinePointerInfo(),
14023 LLD->getMemoryVT(), LLD->isVolatile(),
14024 LLD->isNonTemporal(), isInvariant, Alignment);
14027 // Users of the select now use the result of the load.
14028 CombineTo(TheSelect, Load);
14030 // Users of the old loads now use the new load's chain. We know the
14031 // old-load value is dead now.
14032 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
14033 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
14040 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
14041 /// where 'cond' is the comparison specified by CC.
14042 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
14043 SDValue N2, SDValue N3,
14044 ISD::CondCode CC, bool NotExtCompare) {
14045 // (x ? y : y) -> y.
14046 if (N2 == N3) return N2;
14048 EVT VT = N2.getValueType();
14049 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
14050 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
14052 // Determine if the condition we're dealing with is constant
14053 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
14054 N0, N1, CC, DL, false);
14055 if (SCC.getNode()) AddToWorklist(SCC.getNode());
14057 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
14058 // fold select_cc true, x, y -> x
14059 // fold select_cc false, x, y -> y
14060 return !SCCC->isNullValue() ? N2 : N3;
14063 // Check to see if we can simplify the select into an fabs node
14064 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
14065 // Allow either -0.0 or 0.0
14066 if (CFP->isZero()) {
14067 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
14068 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
14069 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
14070 N2 == N3.getOperand(0))
14071 return DAG.getNode(ISD::FABS, DL, VT, N0);
14073 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
14074 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
14075 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
14076 N2.getOperand(0) == N3)
14077 return DAG.getNode(ISD::FABS, DL, VT, N3);
14081 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
14082 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
14083 // in it. This is a win when the constant is not otherwise available because
14084 // it replaces two constant pool loads with one. We only do this if the FP
14085 // type is known to be legal, because if it isn't, then we are before legalize
14086 // types an we want the other legalization to happen first (e.g. to avoid
14087 // messing with soft float) and if the ConstantFP is not legal, because if
14088 // it is legal, we may not need to store the FP constant in a constant pool.
14089 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
14090 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
14091 if (TLI.isTypeLegal(N2.getValueType()) &&
14092 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
14093 TargetLowering::Legal &&
14094 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
14095 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
14096 // If both constants have multiple uses, then we won't need to do an
14097 // extra load, they are likely around in registers for other users.
14098 (TV->hasOneUse() || FV->hasOneUse())) {
14099 Constant *Elts[] = {
14100 const_cast<ConstantFP*>(FV->getConstantFPValue()),
14101 const_cast<ConstantFP*>(TV->getConstantFPValue())
14103 Type *FPTy = Elts[0]->getType();
14104 const DataLayout &TD = DAG.getDataLayout();
14106 // Create a ConstantArray of the two constants.
14107 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
14109 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
14110 TD.getPrefTypeAlignment(FPTy));
14111 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
14113 // Get the offsets to the 0 and 1 element of the array so that we can
14114 // select between them.
14115 SDValue Zero = DAG.getIntPtrConstant(0, DL);
14116 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
14117 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
14119 SDValue Cond = DAG.getSetCC(DL,
14120 getSetCCResultType(N0.getValueType()),
14122 AddToWorklist(Cond.getNode());
14123 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
14125 AddToWorklist(CstOffset.getNode());
14126 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
14128 AddToWorklist(CPIdx.getNode());
14129 return DAG.getLoad(
14130 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
14131 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
14132 false, false, false, Alignment);
14136 // Check to see if we can perform the "gzip trick", transforming
14137 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
14138 if (isNullConstant(N3) && CC == ISD::SETLT &&
14139 (isNullConstant(N1) || // (a < 0) ? b : 0
14140 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0
14141 EVT XType = N0.getValueType();
14142 EVT AType = N2.getValueType();
14143 if (XType.bitsGE(AType)) {
14144 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
14145 // single-bit constant.
14146 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
14147 unsigned ShCtV = N2C->getAPIntValue().logBase2();
14148 ShCtV = XType.getSizeInBits() - ShCtV - 1;
14149 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
14150 getShiftAmountTy(N0.getValueType()));
14151 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
14153 AddToWorklist(Shift.getNode());
14155 if (XType.bitsGT(AType)) {
14156 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14157 AddToWorklist(Shift.getNode());
14160 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14163 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
14165 DAG.getConstant(XType.getSizeInBits() - 1,
14167 getShiftAmountTy(N0.getValueType())));
14168 AddToWorklist(Shift.getNode());
14170 if (XType.bitsGT(AType)) {
14171 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14172 AddToWorklist(Shift.getNode());
14175 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14179 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
14180 // where y is has a single bit set.
14181 // A plaintext description would be, we can turn the SELECT_CC into an AND
14182 // when the condition can be materialized as an all-ones register. Any
14183 // single bit-test can be materialized as an all-ones register with
14184 // shift-left and shift-right-arith.
14185 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
14186 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
14187 SDValue AndLHS = N0->getOperand(0);
14188 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
14189 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
14190 // Shift the tested bit over the sign bit.
14191 APInt AndMask = ConstAndRHS->getAPIntValue();
14193 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
14194 getShiftAmountTy(AndLHS.getValueType()));
14195 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
14197 // Now arithmetic right shift it all the way over, so the result is either
14198 // all-ones, or zero.
14200 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
14201 getShiftAmountTy(Shl.getValueType()));
14202 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
14204 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
14208 // fold select C, 16, 0 -> shl C, 4
14209 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
14210 TLI.getBooleanContents(N0.getValueType()) ==
14211 TargetLowering::ZeroOrOneBooleanContent) {
14213 // If the caller doesn't want us to simplify this into a zext of a compare,
14215 if (NotExtCompare && N2C->isOne())
14218 // Get a SetCC of the condition
14219 // NOTE: Don't create a SETCC if it's not legal on this target.
14220 if (!LegalOperations ||
14221 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
14223 // cast from setcc result type to select result type
14225 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
14227 if (N2.getValueType().bitsLT(SCC.getValueType()))
14228 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
14229 N2.getValueType());
14231 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14232 N2.getValueType(), SCC);
14234 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
14235 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14236 N2.getValueType(), SCC);
14239 AddToWorklist(SCC.getNode());
14240 AddToWorklist(Temp.getNode());
14245 // shl setcc result by log2 n2c
14246 return DAG.getNode(
14247 ISD::SHL, DL, N2.getValueType(), Temp,
14248 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
14249 getShiftAmountTy(Temp.getValueType())));
14253 // Check to see if this is an integer abs.
14254 // select_cc setg[te] X, 0, X, -X ->
14255 // select_cc setgt X, -1, X, -X ->
14256 // select_cc setl[te] X, 0, -X, X ->
14257 // select_cc setlt X, 1, -X, X ->
14258 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
14260 ConstantSDNode *SubC = nullptr;
14261 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
14262 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
14263 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
14264 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
14265 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
14266 (N1C->isOne() && CC == ISD::SETLT)) &&
14267 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
14268 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
14270 EVT XType = N0.getValueType();
14271 if (SubC && SubC->isNullValue() && XType.isInteger()) {
14273 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
14275 DAG.getConstant(XType.getSizeInBits() - 1, DL,
14276 getShiftAmountTy(N0.getValueType())));
14277 SDValue Add = DAG.getNode(ISD::ADD, DL,
14279 AddToWorklist(Shift.getNode());
14280 AddToWorklist(Add.getNode());
14281 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
14288 /// This is a stub for TargetLowering::SimplifySetCC.
14289 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
14290 SDValue N1, ISD::CondCode Cond,
14291 SDLoc DL, bool foldBooleans) {
14292 TargetLowering::DAGCombinerInfo
14293 DagCombineInfo(DAG, Level, false, this);
14294 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
14297 /// Given an ISD::SDIV node expressing a divide by constant, return
14298 /// a DAG expression to select that will generate the same value by multiplying
14299 /// by a magic number.
14300 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14301 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
14302 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14306 // Avoid division by zero.
14307 if (C->isNullValue())
14310 std::vector<SDNode*> Built;
14312 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14314 for (SDNode *N : Built)
14319 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
14320 /// DAG expression that will generate the same value by right shifting.
14321 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
14322 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14326 // Avoid division by zero.
14327 if (C->isNullValue())
14330 std::vector<SDNode *> Built;
14331 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
14333 for (SDNode *N : Built)
14338 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
14339 /// expression that will generate the same value by multiplying by a magic
14341 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14342 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
14343 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14347 // Avoid division by zero.
14348 if (C->isNullValue())
14351 std::vector<SDNode*> Built;
14353 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14355 for (SDNode *N : Built)
14360 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
14361 if (Level >= AfterLegalizeDAG)
14364 // Expose the DAG combiner to the target combiner implementations.
14365 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14367 unsigned Iterations = 0;
14368 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
14370 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14371 // For the reciprocal, we need to find the zero of the function:
14372 // F(X) = A X - 1 [which has a zero at X = 1/A]
14374 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
14375 // does not require additional intermediate precision]
14376 EVT VT = Op.getValueType();
14378 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
14380 AddToWorklist(Est.getNode());
14382 // Newton iterations: Est = Est + Est (1 - Arg * Est)
14383 for (unsigned i = 0; i < Iterations; ++i) {
14384 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14385 AddToWorklist(NewEst.getNode());
14387 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14388 AddToWorklist(NewEst.getNode());
14390 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14391 AddToWorklist(NewEst.getNode());
14393 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14394 AddToWorklist(Est.getNode());
14403 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14404 /// For the reciprocal sqrt, we need to find the zero of the function:
14405 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14407 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14408 /// As a result, we precompute A/2 prior to the iteration loop.
14409 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
14410 unsigned Iterations,
14411 SDNodeFlags *Flags) {
14412 EVT VT = Arg.getValueType();
14414 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14416 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14417 // this entire sequence requires only one FP constant.
14418 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14419 AddToWorklist(HalfArg.getNode());
14421 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14422 AddToWorklist(HalfArg.getNode());
14424 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14425 for (unsigned i = 0; i < Iterations; ++i) {
14426 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14427 AddToWorklist(NewEst.getNode());
14429 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14430 AddToWorklist(NewEst.getNode());
14432 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14433 AddToWorklist(NewEst.getNode());
14435 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14436 AddToWorklist(Est.getNode());
14441 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14442 /// For the reciprocal sqrt, we need to find the zero of the function:
14443 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14445 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14446 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
14447 unsigned Iterations,
14448 SDNodeFlags *Flags) {
14449 EVT VT = Arg.getValueType();
14451 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
14452 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
14454 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
14455 for (unsigned i = 0; i < Iterations; ++i) {
14456 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
14457 AddToWorklist(HalfEst.getNode());
14459 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14460 AddToWorklist(Est.getNode());
14462 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14463 AddToWorklist(Est.getNode());
14465 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags);
14466 AddToWorklist(Est.getNode());
14468 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags);
14469 AddToWorklist(Est.getNode());
14474 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14475 if (Level >= AfterLegalizeDAG)
14478 // Expose the DAG combiner to the target combiner implementations.
14479 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14480 unsigned Iterations = 0;
14481 bool UseOneConstNR = false;
14482 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
14483 AddToWorklist(Est.getNode());
14485 Est = UseOneConstNR ?
14486 BuildRsqrtNROneConst(Op, Est, Iterations, Flags) :
14487 BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags);
14495 /// Return true if base is a frame index, which is known not to alias with
14496 /// anything but itself. Provides base object and offset as results.
14497 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14498 const GlobalValue *&GV, const void *&CV) {
14499 // Assume it is a primitive operation.
14500 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14502 // If it's an adding a simple constant then integrate the offset.
14503 if (Base.getOpcode() == ISD::ADD) {
14504 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14505 Base = Base.getOperand(0);
14506 Offset += C->getZExtValue();
14510 // Return the underlying GlobalValue, and update the Offset. Return false
14511 // for GlobalAddressSDNode since the same GlobalAddress may be represented
14512 // by multiple nodes with different offsets.
14513 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14514 GV = G->getGlobal();
14515 Offset += G->getOffset();
14519 // Return the underlying Constant value, and update the Offset. Return false
14520 // for ConstantSDNodes since the same constant pool entry may be represented
14521 // by multiple nodes with different offsets.
14522 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14523 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14524 : (const void *)C->getConstVal();
14525 Offset += C->getOffset();
14528 // If it's any of the following then it can't alias with anything but itself.
14529 return isa<FrameIndexSDNode>(Base);
14532 /// Return true if there is any possibility that the two addresses overlap.
14533 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14534 // If they are the same then they must be aliases.
14535 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14537 // If they are both volatile then they cannot be reordered.
14538 if (Op0->isVolatile() && Op1->isVolatile()) return true;
14540 // If one operation reads from invariant memory, and the other may store, they
14541 // cannot alias. These should really be checking the equivalent of mayWrite,
14542 // but it only matters for memory nodes other than load /store.
14543 if (Op0->isInvariant() && Op1->writeMem())
14546 if (Op1->isInvariant() && Op0->writeMem())
14549 // Gather base node and offset information.
14550 SDValue Base1, Base2;
14551 int64_t Offset1, Offset2;
14552 const GlobalValue *GV1, *GV2;
14553 const void *CV1, *CV2;
14554 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14555 Base1, Offset1, GV1, CV1);
14556 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14557 Base2, Offset2, GV2, CV2);
14559 // If they have a same base address then check to see if they overlap.
14560 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14561 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14562 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14564 // It is possible for different frame indices to alias each other, mostly
14565 // when tail call optimization reuses return address slots for arguments.
14566 // To catch this case, look up the actual index of frame indices to compute
14567 // the real alias relationship.
14568 if (isFrameIndex1 && isFrameIndex2) {
14569 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14570 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14571 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14572 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14573 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14576 // Otherwise, if we know what the bases are, and they aren't identical, then
14577 // we know they cannot alias.
14578 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14581 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14582 // compared to the size and offset of the access, we may be able to prove they
14583 // do not alias. This check is conservative for now to catch cases created by
14584 // splitting vector types.
14585 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14586 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14587 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14588 Op1->getMemoryVT().getSizeInBits() >> 3) &&
14589 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14590 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14591 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14593 // There is no overlap between these relatively aligned accesses of similar
14594 // size, return no alias.
14595 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14596 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14600 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14602 : DAG.getSubtarget().useAA();
14604 if (CombinerAAOnlyFunc.getNumOccurrences() &&
14605 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14609 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14610 // Use alias analysis information.
14611 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14612 Op1->getSrcValueOffset());
14613 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14614 Op0->getSrcValueOffset() - MinOffset;
14615 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14616 Op1->getSrcValueOffset() - MinOffset;
14617 AliasResult AAResult =
14618 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14619 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14620 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14621 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14622 if (AAResult == NoAlias)
14626 // Otherwise we have to assume they alias.
14630 /// Walk up chain skipping non-aliasing memory nodes,
14631 /// looking for aliasing nodes and adding them to the Aliases vector.
14632 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14633 SmallVectorImpl<SDValue> &Aliases) {
14634 SmallVector<SDValue, 8> Chains; // List of chains to visit.
14635 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
14637 // Get alias information for node.
14638 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14641 Chains.push_back(OriginalChain);
14642 unsigned Depth = 0;
14644 // Look at each chain and determine if it is an alias. If so, add it to the
14645 // aliases list. If not, then continue up the chain looking for the next
14647 while (!Chains.empty()) {
14648 SDValue Chain = Chains.pop_back_val();
14650 // For TokenFactor nodes, look at each operand and only continue up the
14651 // chain until we reach the depth limit.
14653 // FIXME: The depth check could be made to return the last non-aliasing
14654 // chain we found before we hit a tokenfactor rather than the original
14656 if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
14658 Aliases.push_back(OriginalChain);
14662 // Don't bother if we've been before.
14663 if (!Visited.insert(Chain.getNode()).second)
14666 switch (Chain.getOpcode()) {
14667 case ISD::EntryToken:
14668 // Entry token is ideal chain operand, but handled in FindBetterChain.
14673 // Get alias information for Chain.
14674 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14675 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14677 // If chain is alias then stop here.
14678 if (!(IsLoad && IsOpLoad) &&
14679 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14680 Aliases.push_back(Chain);
14682 // Look further up the chain.
14683 Chains.push_back(Chain.getOperand(0));
14689 case ISD::TokenFactor:
14690 // We have to check each of the operands of the token factor for "small"
14691 // token factors, so we queue them up. Adding the operands to the queue
14692 // (stack) in reverse order maintains the original order and increases the
14693 // likelihood that getNode will find a matching token factor (CSE.)
14694 if (Chain.getNumOperands() > 16) {
14695 Aliases.push_back(Chain);
14698 for (unsigned n = Chain.getNumOperands(); n;)
14699 Chains.push_back(Chain.getOperand(--n));
14704 // For all other instructions we will just have to take what we can get.
14705 Aliases.push_back(Chain);
14710 // We need to be careful here to also search for aliases through the
14711 // value operand of a store, etc. Consider the following situation:
14713 // L1 = load Token1, %52
14714 // S1 = store Token1, L1, %51
14715 // L2 = load Token1, %52+8
14716 // S2 = store Token1, L2, %51+8
14717 // Token2 = Token(S1, S2)
14718 // L3 = load Token2, %53
14719 // S3 = store Token2, L3, %52
14720 // L4 = load Token2, %53+8
14721 // S4 = store Token2, L4, %52+8
14722 // If we search for aliases of S3 (which loads address %52), and we look
14723 // only through the chain, then we'll miss the trivial dependence on L1
14724 // (which also loads from %52). We then might change all loads and
14725 // stores to use Token1 as their chain operand, which could result in
14726 // copying %53 into %52 before copying %52 into %51 (which should
14729 // The problem is, however, that searching for such data dependencies
14730 // can become expensive, and the cost is not directly related to the
14731 // chain depth. Instead, we'll rule out such configurations here by
14732 // insisting that we've visited all chain users (except for users
14733 // of the original chain, which is not necessary). When doing this,
14734 // we need to look through nodes we don't care about (otherwise, things
14735 // like register copies will interfere with trivial cases).
14737 SmallVector<const SDNode *, 16> Worklist;
14738 for (const SDNode *N : Visited)
14739 if (N != OriginalChain.getNode())
14740 Worklist.push_back(N);
14742 while (!Worklist.empty()) {
14743 const SDNode *M = Worklist.pop_back_val();
14745 // We have already visited M, and want to make sure we've visited any uses
14746 // of M that we care about. For uses that we've not visisted, and don't
14747 // care about, queue them to the worklist.
14749 for (SDNode::use_iterator UI = M->use_begin(),
14750 UIE = M->use_end(); UI != UIE; ++UI)
14751 if (UI.getUse().getValueType() == MVT::Other &&
14752 Visited.insert(*UI).second) {
14753 if (isa<MemSDNode>(*UI)) {
14754 // We've not visited this use, and we care about it (it could have an
14755 // ordering dependency with the original node).
14757 Aliases.push_back(OriginalChain);
14761 // We've not visited this use, but we don't care about it. Mark it as
14762 // visited and enqueue it to the worklist.
14763 Worklist.push_back(*UI);
14768 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14769 /// (aliasing node.)
14770 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14771 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
14773 // Accumulate all the aliases to this node.
14774 GatherAllAliases(N, OldChain, Aliases);
14776 // If no operands then chain to entry token.
14777 if (Aliases.size() == 0)
14778 return DAG.getEntryNode();
14780 // If a single operand then chain to it. We don't need to revisit it.
14781 if (Aliases.size() == 1)
14784 // Construct a custom tailored token factor.
14785 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14788 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) {
14789 // This holds the base pointer, index, and the offset in bytes from the base
14791 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
14793 // We must have a base and an offset.
14794 if (!BasePtr.Base.getNode())
14797 // Do not handle stores to undef base pointers.
14798 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
14801 SmallVector<StoreSDNode *, 8> ChainedStores;
14802 ChainedStores.push_back(St);
14804 // Walk up the chain and look for nodes with offsets from the same
14805 // base pointer. Stop when reaching an instruction with a different kind
14806 // or instruction which has a different base pointer.
14807 StoreSDNode *Index = St;
14809 // If the chain has more than one use, then we can't reorder the mem ops.
14810 if (Index != St && !SDValue(Index, 0)->hasOneUse())
14813 if (Index->isVolatile() || Index->isIndexed())
14816 // Find the base pointer and offset for this memory node.
14817 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
14819 // Check that the base pointer is the same as the original one.
14820 if (!Ptr.equalBaseIndex(BasePtr))
14823 // Find the next memory operand in the chain. If the next operand in the
14824 // chain is a store then move up and continue the scan with the next
14825 // memory operand. If the next operand is a load save it and use alias
14826 // information to check if it interferes with anything.
14827 SDNode *NextInChain = Index->getChain().getNode();
14829 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
14830 // We found a store node. Use it for the next iteration.
14831 ChainedStores.push_back(STn);
14834 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
14835 NextInChain = Ldn->getChain().getNode();
14844 bool MadeChange = false;
14845 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
14847 for (StoreSDNode *ChainedStore : ChainedStores) {
14848 SDValue Chain = ChainedStore->getChain();
14849 SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
14851 if (Chain != BetterChain) {
14853 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
14857 // Do all replacements after finding the replacements to make to avoid making
14858 // the chains more complicated by introducing new TokenFactors.
14859 for (auto Replacement : BetterChains)
14860 replaceStoreChain(Replacement.first, Replacement.second);
14865 /// This is the entry point for the file.
14866 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14867 CodeGenOpt::Level OptLevel) {
14868 /// This is the main entry point to this class.
14869 DAGCombiner(*this, AA, OptLevel).Run(Level);