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;
927 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
931 AddToWorklist(Op.getNode());
933 // Replace the old value with the new one.
935 DEBUG(dbgs() << "\nReplacing.2 ";
936 TLO.Old.getNode()->dump(&DAG);
937 dbgs() << "\nWith: ";
938 TLO.New.getNode()->dump(&DAG);
941 CommitTargetLoweringOpt(TLO);
945 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
947 EVT VT = Load->getValueType(0);
948 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
950 DEBUG(dbgs() << "\nReplacing.9 ";
952 dbgs() << "\nWith: ";
953 Trunc.getNode()->dump(&DAG);
955 WorklistRemover DeadNodes(*this);
956 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
957 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
958 deleteAndRecombine(Load);
959 AddToWorklist(Trunc.getNode());
962 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
965 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
966 EVT MemVT = LD->getMemoryVT();
967 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
968 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
970 : LD->getExtensionType();
972 return DAG.getExtLoad(ExtType, dl, PVT,
973 LD->getChain(), LD->getBasePtr(),
974 MemVT, LD->getMemOperand());
977 unsigned Opc = Op.getOpcode();
980 case ISD::AssertSext:
981 return DAG.getNode(ISD::AssertSext, dl, PVT,
982 SExtPromoteOperand(Op.getOperand(0), PVT),
984 case ISD::AssertZext:
985 return DAG.getNode(ISD::AssertZext, dl, PVT,
986 ZExtPromoteOperand(Op.getOperand(0), PVT),
988 case ISD::Constant: {
990 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
991 return DAG.getNode(ExtOpc, dl, PVT, Op);
995 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
997 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
1000 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1001 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1003 EVT OldVT = Op.getValueType();
1005 bool Replace = false;
1006 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1007 if (!NewOp.getNode())
1009 AddToWorklist(NewOp.getNode());
1012 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1013 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
1014 DAG.getValueType(OldVT));
1017 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1018 EVT OldVT = Op.getValueType();
1020 bool Replace = false;
1021 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1022 if (!NewOp.getNode())
1024 AddToWorklist(NewOp.getNode());
1027 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1028 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
1031 /// Promote the specified integer binary operation if the target indicates it is
1032 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1033 /// i32 since i16 instructions are longer.
1034 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1035 if (!LegalOperations)
1038 EVT VT = Op.getValueType();
1039 if (VT.isVector() || !VT.isInteger())
1042 // If operation type is 'undesirable', e.g. i16 on x86, consider
1044 unsigned Opc = Op.getOpcode();
1045 if (TLI.isTypeDesirableForOp(Opc, VT))
1049 // Consult target whether it is a good idea to promote this operation and
1050 // what's the right type to promote it to.
1051 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1052 assert(PVT != VT && "Don't know what type to promote to!");
1054 bool Replace0 = false;
1055 SDValue N0 = Op.getOperand(0);
1056 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1060 bool Replace1 = false;
1061 SDValue N1 = Op.getOperand(1);
1066 NN1 = PromoteOperand(N1, PVT, Replace1);
1071 AddToWorklist(NN0.getNode());
1073 AddToWorklist(NN1.getNode());
1076 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1078 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1080 DEBUG(dbgs() << "\nPromoting ";
1081 Op.getNode()->dump(&DAG));
1083 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1084 DAG.getNode(Opc, dl, PVT, NN0, NN1));
1089 /// Promote the specified integer shift operation if the target indicates it is
1090 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1091 /// i32 since i16 instructions are longer.
1092 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1093 if (!LegalOperations)
1096 EVT VT = Op.getValueType();
1097 if (VT.isVector() || !VT.isInteger())
1100 // If operation type is 'undesirable', e.g. i16 on x86, consider
1102 unsigned Opc = Op.getOpcode();
1103 if (TLI.isTypeDesirableForOp(Opc, VT))
1107 // Consult target whether it is a good idea to promote this operation and
1108 // what's the right type to promote it to.
1109 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1110 assert(PVT != VT && "Don't know what type to promote to!");
1112 bool Replace = false;
1113 SDValue N0 = Op.getOperand(0);
1114 if (Opc == ISD::SRA)
1115 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1116 else if (Opc == ISD::SRL)
1117 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1119 N0 = PromoteOperand(N0, PVT, Replace);
1123 AddToWorklist(N0.getNode());
1125 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1127 DEBUG(dbgs() << "\nPromoting ";
1128 Op.getNode()->dump(&DAG));
1130 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1131 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1136 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1137 if (!LegalOperations)
1140 EVT VT = Op.getValueType();
1141 if (VT.isVector() || !VT.isInteger())
1144 // If operation type is 'undesirable', e.g. i16 on x86, consider
1146 unsigned Opc = Op.getOpcode();
1147 if (TLI.isTypeDesirableForOp(Opc, VT))
1151 // Consult target whether it is a good idea to promote this operation and
1152 // what's the right type to promote it to.
1153 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1154 assert(PVT != VT && "Don't know what type to promote to!");
1155 // fold (aext (aext x)) -> (aext x)
1156 // fold (aext (zext x)) -> (zext x)
1157 // fold (aext (sext x)) -> (sext x)
1158 DEBUG(dbgs() << "\nPromoting ";
1159 Op.getNode()->dump(&DAG));
1160 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1165 bool DAGCombiner::PromoteLoad(SDValue Op) {
1166 if (!LegalOperations)
1169 EVT VT = Op.getValueType();
1170 if (VT.isVector() || !VT.isInteger())
1173 // If operation type is 'undesirable', e.g. i16 on x86, consider
1175 unsigned Opc = Op.getOpcode();
1176 if (TLI.isTypeDesirableForOp(Opc, VT))
1180 // Consult target whether it is a good idea to promote this operation and
1181 // what's the right type to promote it to.
1182 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1183 assert(PVT != VT && "Don't know what type to promote to!");
1186 SDNode *N = Op.getNode();
1187 LoadSDNode *LD = cast<LoadSDNode>(N);
1188 EVT MemVT = LD->getMemoryVT();
1189 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1190 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1192 : LD->getExtensionType();
1193 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1194 LD->getChain(), LD->getBasePtr(),
1195 MemVT, LD->getMemOperand());
1196 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1198 DEBUG(dbgs() << "\nPromoting ";
1201 Result.getNode()->dump(&DAG);
1203 WorklistRemover DeadNodes(*this);
1204 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1205 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1206 deleteAndRecombine(N);
1207 AddToWorklist(Result.getNode());
1213 /// \brief Recursively delete a node which has no uses and any operands for
1214 /// which it is the only use.
1216 /// Note that this both deletes the nodes and removes them from the worklist.
1217 /// It also adds any nodes who have had a user deleted to the worklist as they
1218 /// may now have only one use and subject to other combines.
1219 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1220 if (!N->use_empty())
1223 SmallSetVector<SDNode *, 16> Nodes;
1226 N = Nodes.pop_back_val();
1230 if (N->use_empty()) {
1231 for (const SDValue &ChildN : N->op_values())
1232 Nodes.insert(ChildN.getNode());
1234 removeFromWorklist(N);
1239 } while (!Nodes.empty());
1243 //===----------------------------------------------------------------------===//
1244 // Main DAG Combiner implementation
1245 //===----------------------------------------------------------------------===//
1247 void DAGCombiner::Run(CombineLevel AtLevel) {
1248 // set the instance variables, so that the various visit routines may use it.
1250 LegalOperations = Level >= AfterLegalizeVectorOps;
1251 LegalTypes = Level >= AfterLegalizeTypes;
1253 // Add all the dag nodes to the worklist.
1254 for (SDNode &Node : DAG.allnodes())
1255 AddToWorklist(&Node);
1257 // Create a dummy node (which is not added to allnodes), that adds a reference
1258 // to the root node, preventing it from being deleted, and tracking any
1259 // changes of the root.
1260 HandleSDNode Dummy(DAG.getRoot());
1262 // while the worklist isn't empty, find a node and
1263 // try and combine it.
1264 while (!WorklistMap.empty()) {
1266 // The Worklist holds the SDNodes in order, but it may contain null entries.
1268 N = Worklist.pop_back_val();
1271 bool GoodWorklistEntry = WorklistMap.erase(N);
1272 (void)GoodWorklistEntry;
1273 assert(GoodWorklistEntry &&
1274 "Found a worklist entry without a corresponding map entry!");
1276 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1277 // N is deleted from the DAG, since they too may now be dead or may have a
1278 // reduced number of uses, allowing other xforms.
1279 if (recursivelyDeleteUnusedNodes(N))
1282 WorklistRemover DeadNodes(*this);
1284 // If this combine is running after legalizing the DAG, re-legalize any
1285 // nodes pulled off the worklist.
1286 if (Level == AfterLegalizeDAG) {
1287 SmallSetVector<SDNode *, 16> UpdatedNodes;
1288 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1290 for (SDNode *LN : UpdatedNodes) {
1292 AddUsersToWorklist(LN);
1298 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1300 // Add any operands of the new node which have not yet been combined to the
1301 // worklist as well. Because the worklist uniques things already, this
1302 // won't repeatedly process the same operand.
1303 CombinedNodes.insert(N);
1304 for (const SDValue &ChildN : N->op_values())
1305 if (!CombinedNodes.count(ChildN.getNode()))
1306 AddToWorklist(ChildN.getNode());
1308 SDValue RV = combine(N);
1315 // If we get back the same node we passed in, rather than a new node or
1316 // zero, we know that the node must have defined multiple values and
1317 // CombineTo was used. Since CombineTo takes care of the worklist
1318 // mechanics for us, we have no work to do in this case.
1319 if (RV.getNode() == N)
1322 assert(N->getOpcode() != ISD::DELETED_NODE &&
1323 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1324 "Node was deleted but visit returned new node!");
1326 DEBUG(dbgs() << " ... into: ";
1327 RV.getNode()->dump(&DAG));
1329 // Transfer debug value.
1330 DAG.TransferDbgValues(SDValue(N, 0), RV);
1331 if (N->getNumValues() == RV.getNode()->getNumValues())
1332 DAG.ReplaceAllUsesWith(N, RV.getNode());
1334 assert(N->getValueType(0) == RV.getValueType() &&
1335 N->getNumValues() == 1 && "Type mismatch");
1337 DAG.ReplaceAllUsesWith(N, &OpV);
1340 // Push the new node and any users onto the worklist
1341 AddToWorklist(RV.getNode());
1342 AddUsersToWorklist(RV.getNode());
1344 // Finally, if the node is now dead, remove it from the graph. The node
1345 // may not be dead if the replacement process recursively simplified to
1346 // something else needing this node. This will also take care of adding any
1347 // operands which have lost a user to the worklist.
1348 recursivelyDeleteUnusedNodes(N);
1351 // If the root changed (e.g. it was a dead load, update the root).
1352 DAG.setRoot(Dummy.getValue());
1353 DAG.RemoveDeadNodes();
1356 SDValue DAGCombiner::visit(SDNode *N) {
1357 switch (N->getOpcode()) {
1359 case ISD::TokenFactor: return visitTokenFactor(N);
1360 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1361 case ISD::ADD: return visitADD(N);
1362 case ISD::SUB: return visitSUB(N);
1363 case ISD::ADDC: return visitADDC(N);
1364 case ISD::SUBC: return visitSUBC(N);
1365 case ISD::ADDE: return visitADDE(N);
1366 case ISD::SUBE: return visitSUBE(N);
1367 case ISD::MUL: return visitMUL(N);
1368 case ISD::SDIV: return visitSDIV(N);
1369 case ISD::UDIV: return visitUDIV(N);
1371 case ISD::UREM: return visitREM(N);
1372 case ISD::MULHU: return visitMULHU(N);
1373 case ISD::MULHS: return visitMULHS(N);
1374 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1375 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1376 case ISD::SMULO: return visitSMULO(N);
1377 case ISD::UMULO: return visitUMULO(N);
1381 case ISD::UMAX: return visitIMINMAX(N);
1382 case ISD::AND: return visitAND(N);
1383 case ISD::OR: return visitOR(N);
1384 case ISD::XOR: return visitXOR(N);
1385 case ISD::SHL: return visitSHL(N);
1386 case ISD::SRA: return visitSRA(N);
1387 case ISD::SRL: return visitSRL(N);
1389 case ISD::ROTL: return visitRotate(N);
1390 case ISD::BSWAP: return visitBSWAP(N);
1391 case ISD::CTLZ: return visitCTLZ(N);
1392 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1393 case ISD::CTTZ: return visitCTTZ(N);
1394 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1395 case ISD::CTPOP: return visitCTPOP(N);
1396 case ISD::SELECT: return visitSELECT(N);
1397 case ISD::VSELECT: return visitVSELECT(N);
1398 case ISD::SELECT_CC: return visitSELECT_CC(N);
1399 case ISD::SETCC: return visitSETCC(N);
1400 case ISD::SETCCE: return visitSETCCE(N);
1401 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1402 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1403 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1404 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1405 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1406 case ISD::TRUNCATE: return visitTRUNCATE(N);
1407 case ISD::BITCAST: return visitBITCAST(N);
1408 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1409 case ISD::FADD: return visitFADD(N);
1410 case ISD::FSUB: return visitFSUB(N);
1411 case ISD::FMUL: return visitFMUL(N);
1412 case ISD::FMA: return visitFMA(N);
1413 case ISD::FDIV: return visitFDIV(N);
1414 case ISD::FREM: return visitFREM(N);
1415 case ISD::FSQRT: return visitFSQRT(N);
1416 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1417 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1418 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1419 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1420 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1421 case ISD::FP_ROUND: return visitFP_ROUND(N);
1422 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1423 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1424 case ISD::FNEG: return visitFNEG(N);
1425 case ISD::FABS: return visitFABS(N);
1426 case ISD::FFLOOR: return visitFFLOOR(N);
1427 case ISD::FMINNUM: return visitFMINNUM(N);
1428 case ISD::FMAXNUM: return visitFMAXNUM(N);
1429 case ISD::FCEIL: return visitFCEIL(N);
1430 case ISD::FTRUNC: return visitFTRUNC(N);
1431 case ISD::BRCOND: return visitBRCOND(N);
1432 case ISD::BR_CC: return visitBR_CC(N);
1433 case ISD::LOAD: return visitLOAD(N);
1434 case ISD::STORE: return visitSTORE(N);
1435 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1436 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1437 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1438 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1439 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1440 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1441 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1442 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1443 case ISD::MGATHER: return visitMGATHER(N);
1444 case ISD::MLOAD: return visitMLOAD(N);
1445 case ISD::MSCATTER: return visitMSCATTER(N);
1446 case ISD::MSTORE: return visitMSTORE(N);
1447 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
1448 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N);
1453 SDValue DAGCombiner::combine(SDNode *N) {
1454 SDValue RV = visit(N);
1456 // If nothing happened, try a target-specific DAG combine.
1457 if (!RV.getNode()) {
1458 assert(N->getOpcode() != ISD::DELETED_NODE &&
1459 "Node was deleted but visit returned NULL!");
1461 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1462 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1464 // Expose the DAG combiner to the target combiner impls.
1465 TargetLowering::DAGCombinerInfo
1466 DagCombineInfo(DAG, Level, false, this);
1468 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1472 // If nothing happened still, try promoting the operation.
1473 if (!RV.getNode()) {
1474 switch (N->getOpcode()) {
1482 RV = PromoteIntBinOp(SDValue(N, 0));
1487 RV = PromoteIntShiftOp(SDValue(N, 0));
1489 case ISD::SIGN_EXTEND:
1490 case ISD::ZERO_EXTEND:
1491 case ISD::ANY_EXTEND:
1492 RV = PromoteExtend(SDValue(N, 0));
1495 if (PromoteLoad(SDValue(N, 0)))
1501 // If N is a commutative binary node, try commuting it to enable more
1503 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1504 N->getNumValues() == 1) {
1505 SDValue N0 = N->getOperand(0);
1506 SDValue N1 = N->getOperand(1);
1508 // Constant operands are canonicalized to RHS.
1509 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1510 SDValue Ops[] = {N1, N0};
1511 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1514 return SDValue(CSENode, 0);
1521 /// Given a node, return its input chain if it has one, otherwise return a null
1523 static SDValue getInputChainForNode(SDNode *N) {
1524 if (unsigned NumOps = N->getNumOperands()) {
1525 if (N->getOperand(0).getValueType() == MVT::Other)
1526 return N->getOperand(0);
1527 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1528 return N->getOperand(NumOps-1);
1529 for (unsigned i = 1; i < NumOps-1; ++i)
1530 if (N->getOperand(i).getValueType() == MVT::Other)
1531 return N->getOperand(i);
1536 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1537 // If N has two operands, where one has an input chain equal to the other,
1538 // the 'other' chain is redundant.
1539 if (N->getNumOperands() == 2) {
1540 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1541 return N->getOperand(0);
1542 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1543 return N->getOperand(1);
1546 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1547 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1548 SmallPtrSet<SDNode*, 16> SeenOps;
1549 bool Changed = false; // If we should replace this token factor.
1551 // Start out with this token factor.
1554 // Iterate through token factors. The TFs grows when new token factors are
1556 for (unsigned i = 0; i < TFs.size(); ++i) {
1557 SDNode *TF = TFs[i];
1559 // Check each of the operands.
1560 for (const SDValue &Op : TF->op_values()) {
1562 switch (Op.getOpcode()) {
1563 case ISD::EntryToken:
1564 // Entry tokens don't need to be added to the list. They are
1569 case ISD::TokenFactor:
1570 if (Op.hasOneUse() &&
1571 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1572 // Queue up for processing.
1573 TFs.push_back(Op.getNode());
1574 // Clean up in case the token factor is removed.
1575 AddToWorklist(Op.getNode());
1582 // Only add if it isn't already in the list.
1583 if (SeenOps.insert(Op.getNode()).second)
1594 // If we've changed things around then replace token factor.
1597 // The entry token is the only possible outcome.
1598 Result = DAG.getEntryNode();
1600 // New and improved token factor.
1601 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1604 // Add users to worklist if AA is enabled, since it may introduce
1605 // a lot of new chained token factors while removing memory deps.
1606 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1607 : DAG.getSubtarget().useAA();
1608 return CombineTo(N, Result, UseAA /*add to worklist*/);
1614 /// MERGE_VALUES can always be eliminated.
1615 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1616 WorklistRemover DeadNodes(*this);
1617 // Replacing results may cause a different MERGE_VALUES to suddenly
1618 // be CSE'd with N, and carry its uses with it. Iterate until no
1619 // uses remain, to ensure that the node can be safely deleted.
1620 // First add the users of this node to the work list so that they
1621 // can be tried again once they have new operands.
1622 AddUsersToWorklist(N);
1624 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1625 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1626 } while (!N->use_empty());
1627 deleteAndRecombine(N);
1628 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1631 static bool isNullConstant(SDValue V) {
1632 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1633 return Const != nullptr && Const->isNullValue();
1636 static bool isNullFPConstant(SDValue V) {
1637 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1638 return Const != nullptr && Const->isZero() && !Const->isNegative();
1641 static bool isAllOnesConstant(SDValue V) {
1642 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1643 return Const != nullptr && Const->isAllOnesValue();
1646 static bool isOneConstant(SDValue V) {
1647 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1648 return Const != nullptr && Const->isOne();
1651 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1652 /// ContantSDNode pointer else nullptr.
1653 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1654 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1655 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1658 SDValue DAGCombiner::visitADD(SDNode *N) {
1659 SDValue N0 = N->getOperand(0);
1660 SDValue N1 = N->getOperand(1);
1661 EVT VT = N0.getValueType();
1664 if (VT.isVector()) {
1665 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1668 // fold (add x, 0) -> x, vector edition
1669 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1671 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1675 // fold (add x, undef) -> undef
1676 if (N0.getOpcode() == ISD::UNDEF)
1678 if (N1.getOpcode() == ISD::UNDEF)
1680 // fold (add c1, c2) -> c1+c2
1681 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1682 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1684 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1685 // canonicalize constant to RHS
1686 if (isConstantIntBuildVectorOrConstantInt(N0) &&
1687 !isConstantIntBuildVectorOrConstantInt(N1))
1688 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1689 // fold (add x, 0) -> x
1690 if (isNullConstant(N1))
1692 // fold (add Sym, c) -> Sym+c
1693 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1694 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1695 GA->getOpcode() == ISD::GlobalAddress)
1696 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1698 (uint64_t)N1C->getSExtValue());
1699 // fold ((c1-A)+c2) -> (c1+c2)-A
1700 if (N1C && N0.getOpcode() == ISD::SUB)
1701 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1703 return DAG.getNode(ISD::SUB, DL, VT,
1704 DAG.getConstant(N1C->getAPIntValue()+
1705 N0C->getAPIntValue(), DL, VT),
1709 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1711 // fold ((0-A) + B) -> B-A
1712 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1713 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1714 // fold (A + (0-B)) -> A-B
1715 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1716 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1717 // fold (A+(B-A)) -> B
1718 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1719 return N1.getOperand(0);
1720 // fold ((B-A)+A) -> B
1721 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1722 return N0.getOperand(0);
1723 // fold (A+(B-(A+C))) to (B-C)
1724 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1725 N0 == N1.getOperand(1).getOperand(0))
1726 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1727 N1.getOperand(1).getOperand(1));
1728 // fold (A+(B-(C+A))) to (B-C)
1729 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1730 N0 == N1.getOperand(1).getOperand(1))
1731 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1732 N1.getOperand(1).getOperand(0));
1733 // fold (A+((B-A)+or-C)) to (B+or-C)
1734 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1735 N1.getOperand(0).getOpcode() == ISD::SUB &&
1736 N0 == N1.getOperand(0).getOperand(1))
1737 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1738 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1740 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1741 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1742 SDValue N00 = N0.getOperand(0);
1743 SDValue N01 = N0.getOperand(1);
1744 SDValue N10 = N1.getOperand(0);
1745 SDValue N11 = N1.getOperand(1);
1747 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1748 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1749 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1750 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1753 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1754 return SDValue(N, 0);
1756 // fold (a+b) -> (a|b) iff a and b share no bits.
1757 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
1758 VT.isInteger() && !VT.isVector() && DAG.haveNoCommonBitsSet(N0, N1))
1759 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1761 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1762 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1763 isNullConstant(N1.getOperand(0).getOperand(0)))
1764 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1765 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1766 N1.getOperand(0).getOperand(1),
1768 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1769 isNullConstant(N0.getOperand(0).getOperand(0)))
1770 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1771 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1772 N0.getOperand(0).getOperand(1),
1775 if (N1.getOpcode() == ISD::AND) {
1776 SDValue AndOp0 = N1.getOperand(0);
1777 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1778 unsigned DestBits = VT.getScalarType().getSizeInBits();
1780 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1781 // and similar xforms where the inner op is either ~0 or 0.
1782 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1784 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1788 // add (sext i1), X -> sub X, (zext i1)
1789 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1790 N0.getOperand(0).getValueType() == MVT::i1 &&
1791 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1793 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1794 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1797 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1798 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1799 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1800 if (TN->getVT() == MVT::i1) {
1802 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1803 DAG.getConstant(1, DL, VT));
1804 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1811 SDValue DAGCombiner::visitADDC(SDNode *N) {
1812 SDValue N0 = N->getOperand(0);
1813 SDValue N1 = N->getOperand(1);
1814 EVT VT = N0.getValueType();
1816 // If the flag result is dead, turn this into an ADD.
1817 if (!N->hasAnyUseOfValue(1))
1818 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1819 DAG.getNode(ISD::CARRY_FALSE,
1820 SDLoc(N), MVT::Glue));
1822 // canonicalize constant to RHS.
1823 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1824 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1826 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1828 // fold (addc x, 0) -> x + no carry out
1829 if (isNullConstant(N1))
1830 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1831 SDLoc(N), MVT::Glue));
1833 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1834 APInt LHSZero, LHSOne;
1835 APInt RHSZero, RHSOne;
1836 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1838 if (LHSZero.getBoolValue()) {
1839 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1841 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1842 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1843 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1844 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1845 DAG.getNode(ISD::CARRY_FALSE,
1846 SDLoc(N), MVT::Glue));
1852 SDValue DAGCombiner::visitADDE(SDNode *N) {
1853 SDValue N0 = N->getOperand(0);
1854 SDValue N1 = N->getOperand(1);
1855 SDValue CarryIn = N->getOperand(2);
1857 // canonicalize constant to RHS
1858 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1859 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1861 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1864 // fold (adde x, y, false) -> (addc x, y)
1865 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1866 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1871 // Since it may not be valid to emit a fold to zero for vector initializers
1872 // check if we can before folding.
1873 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1875 bool LegalOperations, bool LegalTypes) {
1877 return DAG.getConstant(0, DL, VT);
1878 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1879 return DAG.getConstant(0, DL, VT);
1883 SDValue DAGCombiner::visitSUB(SDNode *N) {
1884 SDValue N0 = N->getOperand(0);
1885 SDValue N1 = N->getOperand(1);
1886 EVT VT = N0.getValueType();
1889 if (VT.isVector()) {
1890 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1893 // fold (sub x, 0) -> x, vector edition
1894 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1898 // fold (sub x, x) -> 0
1899 // FIXME: Refactor this and xor and other similar operations together.
1901 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1902 // fold (sub c1, c2) -> c1-c2
1903 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1904 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1906 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1907 // fold (sub x, c) -> (add x, -c)
1910 return DAG.getNode(ISD::ADD, DL, VT, N0,
1911 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1913 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1914 if (isAllOnesConstant(N0))
1915 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1916 // fold A-(A-B) -> B
1917 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1918 return N1.getOperand(1);
1919 // fold (A+B)-A -> B
1920 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1921 return N0.getOperand(1);
1922 // fold (A+B)-B -> A
1923 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1924 return N0.getOperand(0);
1925 // fold C2-(A+C1) -> (C2-C1)-A
1926 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1927 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1928 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1930 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1932 return DAG.getNode(ISD::SUB, DL, VT, NewC,
1935 // fold ((A+(B+or-C))-B) -> A+or-C
1936 if (N0.getOpcode() == ISD::ADD &&
1937 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1938 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1939 N0.getOperand(1).getOperand(0) == N1)
1940 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1941 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1942 // fold ((A+(C+B))-B) -> A+C
1943 if (N0.getOpcode() == ISD::ADD &&
1944 N0.getOperand(1).getOpcode() == ISD::ADD &&
1945 N0.getOperand(1).getOperand(1) == N1)
1946 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1947 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1948 // fold ((A-(B-C))-C) -> A-B
1949 if (N0.getOpcode() == ISD::SUB &&
1950 N0.getOperand(1).getOpcode() == ISD::SUB &&
1951 N0.getOperand(1).getOperand(1) == N1)
1952 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1953 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1955 // If either operand of a sub is undef, the result is undef
1956 if (N0.getOpcode() == ISD::UNDEF)
1958 if (N1.getOpcode() == ISD::UNDEF)
1961 // If the relocation model supports it, consider symbol offsets.
1962 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1963 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1964 // fold (sub Sym, c) -> Sym-c
1965 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1966 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1968 (uint64_t)N1C->getSExtValue());
1969 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1970 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1971 if (GA->getGlobal() == GB->getGlobal())
1972 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1976 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1977 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1978 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1979 if (TN->getVT() == MVT::i1) {
1981 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1982 DAG.getConstant(1, DL, VT));
1983 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1990 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1991 SDValue N0 = N->getOperand(0);
1992 SDValue N1 = N->getOperand(1);
1993 EVT VT = N0.getValueType();
1996 // If the flag result is dead, turn this into an SUB.
1997 if (!N->hasAnyUseOfValue(1))
1998 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
1999 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2001 // fold (subc x, x) -> 0 + no borrow
2003 return CombineTo(N, DAG.getConstant(0, DL, VT),
2004 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2006 // fold (subc x, 0) -> x + no borrow
2007 if (isNullConstant(N1))
2008 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2010 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2011 if (isAllOnesConstant(N0))
2012 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2013 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2018 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2019 SDValue N0 = N->getOperand(0);
2020 SDValue N1 = N->getOperand(1);
2021 SDValue CarryIn = N->getOperand(2);
2023 // fold (sube x, y, false) -> (subc x, y)
2024 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2025 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2030 SDValue DAGCombiner::visitMUL(SDNode *N) {
2031 SDValue N0 = N->getOperand(0);
2032 SDValue N1 = N->getOperand(1);
2033 EVT VT = N0.getValueType();
2035 // fold (mul x, undef) -> 0
2036 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2037 return DAG.getConstant(0, SDLoc(N), VT);
2039 bool N0IsConst = false;
2040 bool N1IsConst = false;
2041 bool N1IsOpaqueConst = false;
2042 bool N0IsOpaqueConst = false;
2043 APInt ConstValue0, ConstValue1;
2045 if (VT.isVector()) {
2046 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2049 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2050 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2052 N0IsConst = isa<ConstantSDNode>(N0);
2054 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2055 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2057 N1IsConst = isa<ConstantSDNode>(N1);
2059 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2060 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2064 // fold (mul c1, c2) -> c1*c2
2065 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2066 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2067 N0.getNode(), N1.getNode());
2069 // canonicalize constant to RHS (vector doesn't have to splat)
2070 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2071 !isConstantIntBuildVectorOrConstantInt(N1))
2072 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2073 // fold (mul x, 0) -> 0
2074 if (N1IsConst && ConstValue1 == 0)
2076 // We require a splat of the entire scalar bit width for non-contiguous
2079 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2080 // fold (mul x, 1) -> x
2081 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2083 // fold (mul x, -1) -> 0-x
2084 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2086 return DAG.getNode(ISD::SUB, DL, VT,
2087 DAG.getConstant(0, DL, VT), N0);
2089 // fold (mul x, (1 << c)) -> x << c
2090 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2093 return DAG.getNode(ISD::SHL, DL, VT, N0,
2094 DAG.getConstant(ConstValue1.logBase2(), DL,
2095 getShiftAmountTy(N0.getValueType())));
2097 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2098 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2100 unsigned Log2Val = (-ConstValue1).logBase2();
2102 // FIXME: If the input is something that is easily negated (e.g. a
2103 // single-use add), we should put the negate there.
2104 return DAG.getNode(ISD::SUB, DL, VT,
2105 DAG.getConstant(0, DL, VT),
2106 DAG.getNode(ISD::SHL, DL, VT, N0,
2107 DAG.getConstant(Log2Val, DL,
2108 getShiftAmountTy(N0.getValueType()))));
2112 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2113 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2114 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2115 isa<ConstantSDNode>(N0.getOperand(1)))) {
2116 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2117 N1, N0.getOperand(1));
2118 AddToWorklist(C3.getNode());
2119 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2120 N0.getOperand(0), C3);
2123 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2126 SDValue Sh(nullptr,0), Y(nullptr,0);
2127 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2128 if (N0.getOpcode() == ISD::SHL &&
2129 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2130 isa<ConstantSDNode>(N0.getOperand(1))) &&
2131 N0.getNode()->hasOneUse()) {
2133 } else if (N1.getOpcode() == ISD::SHL &&
2134 isa<ConstantSDNode>(N1.getOperand(1)) &&
2135 N1.getNode()->hasOneUse()) {
2140 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2141 Sh.getOperand(0), Y);
2142 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2143 Mul, Sh.getOperand(1));
2147 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2148 if (isConstantIntBuildVectorOrConstantInt(N1) &&
2149 N0.getOpcode() == ISD::ADD &&
2150 isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2151 isMulAddWithConstProfitable(N, N0, N1))
2152 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2153 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2154 N0.getOperand(0), N1),
2155 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2156 N0.getOperand(1), N1));
2159 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2165 /// Return true if divmod libcall is available.
2166 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2167 const TargetLowering &TLI) {
2169 switch (Node->getSimpleValueType(0).SimpleTy) {
2170 default: return false; // No libcall for vector types.
2171 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
2172 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2173 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2174 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2175 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2178 return TLI.getLibcallName(LC) != nullptr;
2181 /// Issue divrem if both quotient and remainder are needed.
2182 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2183 if (Node->use_empty())
2184 return SDValue(); // This is a dead node, leave it alone.
2186 EVT VT = Node->getValueType(0);
2187 if (!TLI.isTypeLegal(VT))
2190 unsigned Opcode = Node->getOpcode();
2191 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2193 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2194 // If DIVREM is going to get expanded into a libcall,
2195 // but there is no libcall available, then don't combine.
2196 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2197 !isDivRemLibcallAvailable(Node, isSigned, TLI))
2200 // If div is legal, it's better to do the normal expansion
2201 unsigned OtherOpcode = 0;
2202 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2203 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2204 if (TLI.isOperationLegalOrCustom(Opcode, VT))
2207 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2208 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2212 SDValue Op0 = Node->getOperand(0);
2213 SDValue Op1 = Node->getOperand(1);
2215 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2216 UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2218 if (User == Node || User->use_empty())
2220 // Convert the other matching node(s), too;
2221 // otherwise, the DIVREM may get target-legalized into something
2222 // target-specific that we won't be able to recognize.
2223 unsigned UserOpc = User->getOpcode();
2224 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2225 User->getOperand(0) == Op0 &&
2226 User->getOperand(1) == Op1) {
2228 if (UserOpc == OtherOpcode) {
2229 SDVTList VTs = DAG.getVTList(VT, VT);
2230 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2231 } else if (UserOpc == DivRemOpc) {
2232 combined = SDValue(User, 0);
2234 assert(UserOpc == Opcode);
2238 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2239 CombineTo(User, combined);
2240 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2241 CombineTo(User, combined.getValue(1));
2247 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2248 SDValue N0 = N->getOperand(0);
2249 SDValue N1 = N->getOperand(1);
2250 EVT VT = N->getValueType(0);
2254 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2259 // fold (sdiv c1, c2) -> c1/c2
2260 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2261 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2262 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2263 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2264 // fold (sdiv X, 1) -> X
2265 if (N1C && N1C->isOne())
2267 // fold (sdiv X, -1) -> 0-X
2268 if (N1C && N1C->isAllOnesValue())
2269 return DAG.getNode(ISD::SUB, DL, VT,
2270 DAG.getConstant(0, DL, VT), N0);
2272 // If we know the sign bits of both operands are zero, strength reduce to a
2273 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2274 if (!VT.isVector()) {
2275 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2276 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2279 // fold (sdiv X, pow2) -> simple ops after legalize
2280 // FIXME: We check for the exact bit here because the generic lowering gives
2281 // better results in that case. The target-specific lowering should learn how
2282 // to handle exact sdivs efficiently.
2283 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2284 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2285 (N1C->getAPIntValue().isPowerOf2() ||
2286 (-N1C->getAPIntValue()).isPowerOf2())) {
2287 // Target-specific implementation of sdiv x, pow2.
2288 if (SDValue Res = BuildSDIVPow2(N))
2291 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2293 // Splat the sign bit into the register
2295 DAG.getNode(ISD::SRA, DL, VT, N0,
2296 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2297 getShiftAmountTy(N0.getValueType())));
2298 AddToWorklist(SGN.getNode());
2300 // Add (N0 < 0) ? abs2 - 1 : 0;
2302 DAG.getNode(ISD::SRL, DL, VT, SGN,
2303 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2304 getShiftAmountTy(SGN.getValueType())));
2305 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2306 AddToWorklist(SRL.getNode());
2307 AddToWorklist(ADD.getNode()); // Divide by pow2
2308 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2309 DAG.getConstant(lg2, DL,
2310 getShiftAmountTy(ADD.getValueType())));
2312 // If we're dividing by a positive value, we're done. Otherwise, we must
2313 // negate the result.
2314 if (N1C->getAPIntValue().isNonNegative())
2317 AddToWorklist(SRA.getNode());
2318 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2321 // If integer divide is expensive and we satisfy the requirements, emit an
2322 // alternate sequence. Targets may check function attributes for size/speed
2324 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2325 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2326 if (SDValue Op = BuildSDIV(N))
2329 // sdiv, srem -> sdivrem
2330 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2331 // Otherwise, we break the simplification logic in visitREM().
2332 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2333 if (SDValue DivRem = useDivRem(N))
2337 if (N0.getOpcode() == ISD::UNDEF)
2338 return DAG.getConstant(0, DL, VT);
2339 // X / undef -> undef
2340 if (N1.getOpcode() == ISD::UNDEF)
2346 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2347 SDValue N0 = N->getOperand(0);
2348 SDValue N1 = N->getOperand(1);
2349 EVT VT = N->getValueType(0);
2353 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2358 // fold (udiv c1, c2) -> c1/c2
2359 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2360 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2362 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2365 // fold (udiv x, (1 << c)) -> x >>u c
2366 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2())
2367 return DAG.getNode(ISD::SRL, DL, VT, N0,
2368 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2369 getShiftAmountTy(N0.getValueType())));
2371 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2372 if (N1.getOpcode() == ISD::SHL) {
2373 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2374 if (SHC->getAPIntValue().isPowerOf2()) {
2375 EVT ADDVT = N1.getOperand(1).getValueType();
2376 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2378 DAG.getConstant(SHC->getAPIntValue()
2381 AddToWorklist(Add.getNode());
2382 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2387 // fold (udiv x, c) -> alternate
2388 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2389 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2390 if (SDValue Op = BuildUDIV(N))
2393 // sdiv, srem -> sdivrem
2394 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2395 // Otherwise, we break the simplification logic in visitREM().
2396 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2397 if (SDValue DivRem = useDivRem(N))
2401 if (N0.getOpcode() == ISD::UNDEF)
2402 return DAG.getConstant(0, DL, VT);
2403 // X / undef -> undef
2404 if (N1.getOpcode() == ISD::UNDEF)
2410 // handles ISD::SREM and ISD::UREM
2411 SDValue DAGCombiner::visitREM(SDNode *N) {
2412 unsigned Opcode = N->getOpcode();
2413 SDValue N0 = N->getOperand(0);
2414 SDValue N1 = N->getOperand(1);
2415 EVT VT = N->getValueType(0);
2416 bool isSigned = (Opcode == ISD::SREM);
2419 // fold (rem c1, c2) -> c1%c2
2420 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2421 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2423 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2427 // If we know the sign bits of both operands are zero, strength reduce to a
2428 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2429 if (!VT.isVector()) {
2430 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2431 return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2434 // fold (urem x, pow2) -> (and x, pow2-1)
2435 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2436 N1C->getAPIntValue().isPowerOf2()) {
2437 return DAG.getNode(ISD::AND, DL, VT, N0,
2438 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2440 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2441 if (N1.getOpcode() == ISD::SHL) {
2442 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2443 if (SHC->getAPIntValue().isPowerOf2()) {
2445 DAG.getNode(ISD::ADD, DL, VT, N1,
2446 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2448 AddToWorklist(Add.getNode());
2449 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2455 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2457 // If X/C can be simplified by the division-by-constant logic, lower
2458 // X%C to the equivalent of X-X/C*C.
2459 // To avoid mangling nodes, this simplification requires that the combine()
2460 // call for the speculative DIV must not cause a DIVREM conversion. We guard
2461 // against this by skipping the simplification if isIntDivCheap(). When
2462 // div is not cheap, combine will not return a DIVREM. Regardless,
2463 // checking cheapness here makes sense since the simplification results in
2465 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2466 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2467 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2468 AddToWorklist(Div.getNode());
2469 SDValue OptimizedDiv = combine(Div.getNode());
2470 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2471 assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2472 (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2473 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2474 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2475 AddToWorklist(Mul.getNode());
2480 // sdiv, srem -> sdivrem
2481 if (SDValue DivRem = useDivRem(N))
2482 return DivRem.getValue(1);
2485 if (N0.getOpcode() == ISD::UNDEF)
2486 return DAG.getConstant(0, DL, VT);
2487 // X % undef -> undef
2488 if (N1.getOpcode() == ISD::UNDEF)
2494 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2495 SDValue N0 = N->getOperand(0);
2496 SDValue N1 = N->getOperand(1);
2497 EVT VT = N->getValueType(0);
2500 // fold (mulhs x, 0) -> 0
2501 if (isNullConstant(N1))
2503 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2504 if (isOneConstant(N1)) {
2506 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2507 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2509 getShiftAmountTy(N0.getValueType())));
2511 // fold (mulhs x, undef) -> 0
2512 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2513 return DAG.getConstant(0, SDLoc(N), VT);
2515 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2517 if (VT.isSimple() && !VT.isVector()) {
2518 MVT Simple = VT.getSimpleVT();
2519 unsigned SimpleSize = Simple.getSizeInBits();
2520 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2521 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2522 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2523 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2524 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2525 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2526 DAG.getConstant(SimpleSize, DL,
2527 getShiftAmountTy(N1.getValueType())));
2528 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2535 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2536 SDValue N0 = N->getOperand(0);
2537 SDValue N1 = N->getOperand(1);
2538 EVT VT = N->getValueType(0);
2541 // fold (mulhu x, 0) -> 0
2542 if (isNullConstant(N1))
2544 // fold (mulhu x, 1) -> 0
2545 if (isOneConstant(N1))
2546 return DAG.getConstant(0, DL, N0.getValueType());
2547 // fold (mulhu x, undef) -> 0
2548 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2549 return DAG.getConstant(0, DL, VT);
2551 // If the type twice as wide is legal, transform the mulhu 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::ZERO_EXTEND, DL, NewVT, N0);
2559 N1 = DAG.getNode(ISD::ZERO_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 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2572 /// give the opcodes for the two computations that are being performed. Return
2573 /// true if a simplification was made.
2574 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2576 // If the high half is not needed, just compute the low half.
2577 bool HiExists = N->hasAnyUseOfValue(1);
2579 (!LegalOperations ||
2580 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2581 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2582 return CombineTo(N, Res, Res);
2585 // If the low half is not needed, just compute the high half.
2586 bool LoExists = N->hasAnyUseOfValue(0);
2588 (!LegalOperations ||
2589 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2590 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2591 return CombineTo(N, Res, Res);
2594 // If both halves are used, return as it is.
2595 if (LoExists && HiExists)
2598 // If the two computed results can be simplified separately, separate them.
2600 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2601 AddToWorklist(Lo.getNode());
2602 SDValue LoOpt = combine(Lo.getNode());
2603 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2604 (!LegalOperations ||
2605 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2606 return CombineTo(N, LoOpt, LoOpt);
2610 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2611 AddToWorklist(Hi.getNode());
2612 SDValue HiOpt = combine(Hi.getNode());
2613 if (HiOpt.getNode() && HiOpt != Hi &&
2614 (!LegalOperations ||
2615 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2616 return CombineTo(N, HiOpt, HiOpt);
2622 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2623 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2626 EVT VT = N->getValueType(0);
2629 // If the type is twice as wide is legal, transform the mulhu to a wider
2630 // multiply plus a shift.
2631 if (VT.isSimple() && !VT.isVector()) {
2632 MVT Simple = VT.getSimpleVT();
2633 unsigned SimpleSize = Simple.getSizeInBits();
2634 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2635 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2636 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2637 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2638 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2639 // Compute the high part as N1.
2640 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2641 DAG.getConstant(SimpleSize, DL,
2642 getShiftAmountTy(Lo.getValueType())));
2643 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2644 // Compute the low part as N0.
2645 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2646 return CombineTo(N, Lo, Hi);
2653 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2654 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2657 EVT VT = N->getValueType(0);
2660 // If the type is twice as wide is legal, transform the mulhu to a wider
2661 // multiply plus a shift.
2662 if (VT.isSimple() && !VT.isVector()) {
2663 MVT Simple = VT.getSimpleVT();
2664 unsigned SimpleSize = Simple.getSizeInBits();
2665 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2666 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2667 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2668 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2669 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2670 // Compute the high part as N1.
2671 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2672 DAG.getConstant(SimpleSize, DL,
2673 getShiftAmountTy(Lo.getValueType())));
2674 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2675 // Compute the low part as N0.
2676 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2677 return CombineTo(N, Lo, Hi);
2684 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2685 // (smulo x, 2) -> (saddo x, x)
2686 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2687 if (C2->getAPIntValue() == 2)
2688 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2689 N->getOperand(0), N->getOperand(0));
2694 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2695 // (umulo x, 2) -> (uaddo x, x)
2696 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2697 if (C2->getAPIntValue() == 2)
2698 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2699 N->getOperand(0), N->getOperand(0));
2704 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2705 SDValue N0 = N->getOperand(0);
2706 SDValue N1 = N->getOperand(1);
2707 EVT VT = N0.getValueType();
2711 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2714 // fold (add c1, c2) -> c1+c2
2715 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2716 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2718 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2720 // canonicalize constant to RHS
2721 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2722 !isConstantIntBuildVectorOrConstantInt(N1))
2723 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2728 /// If this is a binary operator with two operands of the same opcode, try to
2730 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2731 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2732 EVT VT = N0.getValueType();
2733 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2735 // Bail early if none of these transforms apply.
2736 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2738 // For each of OP in AND/OR/XOR:
2739 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2740 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2741 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2742 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2743 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2745 // do not sink logical op inside of a vector extend, since it may combine
2747 EVT Op0VT = N0.getOperand(0).getValueType();
2748 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2749 N0.getOpcode() == ISD::SIGN_EXTEND ||
2750 N0.getOpcode() == ISD::BSWAP ||
2751 // Avoid infinite looping with PromoteIntBinOp.
2752 (N0.getOpcode() == ISD::ANY_EXTEND &&
2753 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2754 (N0.getOpcode() == ISD::TRUNCATE &&
2755 (!TLI.isZExtFree(VT, Op0VT) ||
2756 !TLI.isTruncateFree(Op0VT, VT)) &&
2757 TLI.isTypeLegal(Op0VT))) &&
2759 Op0VT == N1.getOperand(0).getValueType() &&
2760 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2761 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2762 N0.getOperand(0).getValueType(),
2763 N0.getOperand(0), N1.getOperand(0));
2764 AddToWorklist(ORNode.getNode());
2765 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2768 // For each of OP in SHL/SRL/SRA/AND...
2769 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2770 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2771 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2772 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2773 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2774 N0.getOperand(1) == N1.getOperand(1)) {
2775 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2776 N0.getOperand(0).getValueType(),
2777 N0.getOperand(0), N1.getOperand(0));
2778 AddToWorklist(ORNode.getNode());
2779 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2780 ORNode, N0.getOperand(1));
2783 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2784 // Only perform this optimization after type legalization and before
2785 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2786 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2787 // we don't want to undo this promotion.
2788 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2790 if ((N0.getOpcode() == ISD::BITCAST ||
2791 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2792 Level == AfterLegalizeTypes) {
2793 SDValue In0 = N0.getOperand(0);
2794 SDValue In1 = N1.getOperand(0);
2795 EVT In0Ty = In0.getValueType();
2796 EVT In1Ty = In1.getValueType();
2798 // If both incoming values are integers, and the original types are the
2800 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2801 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2802 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2803 AddToWorklist(Op.getNode());
2808 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2809 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2810 // If both shuffles use the same mask, and both shuffle within a single
2811 // vector, then it is worthwhile to move the swizzle after the operation.
2812 // The type-legalizer generates this pattern when loading illegal
2813 // vector types from memory. In many cases this allows additional shuffle
2815 // There are other cases where moving the shuffle after the xor/and/or
2816 // is profitable even if shuffles don't perform a swizzle.
2817 // If both shuffles use the same mask, and both shuffles have the same first
2818 // or second operand, then it might still be profitable to move the shuffle
2819 // after the xor/and/or operation.
2820 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2821 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2822 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2824 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2825 "Inputs to shuffles are not the same type");
2827 // Check that both shuffles use the same mask. The masks are known to be of
2828 // the same length because the result vector type is the same.
2829 // Check also that shuffles have only one use to avoid introducing extra
2831 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2832 SVN0->getMask().equals(SVN1->getMask())) {
2833 SDValue ShOp = N0->getOperand(1);
2835 // Don't try to fold this node if it requires introducing a
2836 // build vector of all zeros that might be illegal at this stage.
2837 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2839 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2844 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2845 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2846 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2847 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2848 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2849 N0->getOperand(0), N1->getOperand(0));
2850 AddToWorklist(NewNode.getNode());
2851 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2852 &SVN0->getMask()[0]);
2855 // Don't try to fold this node if it requires introducing a
2856 // build vector of all zeros that might be illegal at this stage.
2857 ShOp = N0->getOperand(0);
2858 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2860 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2865 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2866 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2867 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2868 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2869 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2870 N0->getOperand(1), N1->getOperand(1));
2871 AddToWorklist(NewNode.getNode());
2872 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2873 &SVN0->getMask()[0]);
2881 /// This contains all DAGCombine rules which reduce two values combined by
2882 /// an And operation to a single value. This makes them reusable in the context
2883 /// of visitSELECT(). Rules involving constants are not included as
2884 /// visitSELECT() already handles those cases.
2885 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2886 SDNode *LocReference) {
2887 EVT VT = N1.getValueType();
2889 // fold (and x, undef) -> 0
2890 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2891 return DAG.getConstant(0, SDLoc(LocReference), VT);
2892 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2893 SDValue LL, LR, RL, RR, CC0, CC1;
2894 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2895 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2896 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2898 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2899 LL.getValueType().isInteger()) {
2900 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2901 if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2902 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2903 LR.getValueType(), LL, RL);
2904 AddToWorklist(ORNode.getNode());
2905 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2907 if (isAllOnesConstant(LR)) {
2908 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2909 if (Op1 == ISD::SETEQ) {
2910 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2911 LR.getValueType(), LL, RL);
2912 AddToWorklist(ANDNode.getNode());
2913 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2915 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2916 if (Op1 == ISD::SETGT) {
2917 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2918 LR.getValueType(), LL, RL);
2919 AddToWorklist(ORNode.getNode());
2920 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2924 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2925 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2926 Op0 == Op1 && LL.getValueType().isInteger() &&
2927 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2928 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2930 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2931 LL, DAG.getConstant(1, DL,
2932 LL.getValueType()));
2933 AddToWorklist(ADDNode.getNode());
2934 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2935 DAG.getConstant(2, DL, LL.getValueType()),
2938 // canonicalize equivalent to ll == rl
2939 if (LL == RR && LR == RL) {
2940 Op1 = ISD::getSetCCSwappedOperands(Op1);
2943 if (LL == RL && LR == RR) {
2944 bool isInteger = LL.getValueType().isInteger();
2945 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2946 if (Result != ISD::SETCC_INVALID &&
2947 (!LegalOperations ||
2948 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2949 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
2950 EVT CCVT = getSetCCResultType(LL.getValueType());
2951 if (N0.getValueType() == CCVT ||
2952 (!LegalOperations && N0.getValueType() == MVT::i1))
2953 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2959 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2960 VT.getSizeInBits() <= 64) {
2961 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2962 APInt ADDC = ADDI->getAPIntValue();
2963 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2964 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2965 // immediate for an add, but it is legal if its top c2 bits are set,
2966 // transform the ADD so the immediate doesn't need to be materialized
2968 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2969 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2970 SRLI->getZExtValue());
2971 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2973 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2976 DAG.getNode(ISD::ADD, DL, VT,
2977 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2978 CombineTo(N0.getNode(), NewAdd);
2979 // Return N so it doesn't get rechecked!
2980 return SDValue(LocReference, 0);
2991 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
2992 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
2994 uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
2996 if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue()))
2999 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3000 LoadedVT = LoadN->getMemoryVT();
3002 if (ExtVT == LoadedVT &&
3003 (!LegalOperations ||
3004 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3005 // ZEXTLOAD will match without needing to change the size of the value being
3011 // Do not change the width of a volatile load.
3012 if (LoadN->isVolatile())
3015 // Do not generate loads of non-round integer types since these can
3016 // be expensive (and would be wrong if the type is not byte sized).
3017 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3020 if (LegalOperations &&
3021 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3024 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3031 SDValue DAGCombiner::visitAND(SDNode *N) {
3032 SDValue N0 = N->getOperand(0);
3033 SDValue N1 = N->getOperand(1);
3034 EVT VT = N1.getValueType();
3037 if (VT.isVector()) {
3038 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3041 // fold (and x, 0) -> 0, vector edition
3042 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3043 // do not return N0, because undef node may exist in N0
3044 return DAG.getConstant(
3045 APInt::getNullValue(
3046 N0.getValueType().getScalarType().getSizeInBits()),
3047 SDLoc(N), N0.getValueType());
3048 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3049 // do not return N1, because undef node may exist in N1
3050 return DAG.getConstant(
3051 APInt::getNullValue(
3052 N1.getValueType().getScalarType().getSizeInBits()),
3053 SDLoc(N), N1.getValueType());
3055 // fold (and x, -1) -> x, vector edition
3056 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3058 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3062 // fold (and c1, c2) -> c1&c2
3063 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3064 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3065 if (N0C && N1C && !N1C->isOpaque())
3066 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3067 // canonicalize constant to RHS
3068 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3069 !isConstantIntBuildVectorOrConstantInt(N1))
3070 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3071 // fold (and x, -1) -> x
3072 if (isAllOnesConstant(N1))
3074 // if (and x, c) is known to be zero, return 0
3075 unsigned BitWidth = VT.getScalarType().getSizeInBits();
3076 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3077 APInt::getAllOnesValue(BitWidth)))
3078 return DAG.getConstant(0, SDLoc(N), VT);
3080 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3082 // fold (and (or x, C), D) -> D if (C & D) == D
3083 if (N1C && N0.getOpcode() == ISD::OR)
3084 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3085 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3087 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3088 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3089 SDValue N0Op0 = N0.getOperand(0);
3090 APInt Mask = ~N1C->getAPIntValue();
3091 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
3092 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3093 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3094 N0.getValueType(), N0Op0);
3096 // Replace uses of the AND with uses of the Zero extend node.
3099 // We actually want to replace all uses of the any_extend with the
3100 // zero_extend, to avoid duplicating things. This will later cause this
3101 // AND to be folded.
3102 CombineTo(N0.getNode(), Zext);
3103 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3106 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3107 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3108 // already be zero by virtue of the width of the base type of the load.
3110 // the 'X' node here can either be nothing or an extract_vector_elt to catch
3112 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3113 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
3114 N0.getOpcode() == ISD::LOAD) {
3115 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3116 N0 : N0.getOperand(0) );
3118 // Get the constant (if applicable) the zero'th operand is being ANDed with.
3119 // This can be a pure constant or a vector splat, in which case we treat the
3120 // vector as a scalar and use the splat value.
3121 APInt Constant = APInt::getNullValue(1);
3122 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3123 Constant = C->getAPIntValue();
3124 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3125 APInt SplatValue, SplatUndef;
3126 unsigned SplatBitSize;
3128 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3129 SplatBitSize, HasAnyUndefs);
3131 // Undef bits can contribute to a possible optimisation if set, so
3133 SplatValue |= SplatUndef;
3135 // The splat value may be something like "0x00FFFFFF", which means 0 for
3136 // the first vector value and FF for the rest, repeating. We need a mask
3137 // that will apply equally to all members of the vector, so AND all the
3138 // lanes of the constant together.
3139 EVT VT = Vector->getValueType(0);
3140 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3142 // If the splat value has been compressed to a bitlength lower
3143 // than the size of the vector lane, we need to re-expand it to
3145 if (BitWidth > SplatBitSize)
3146 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3147 SplatBitSize < BitWidth;
3148 SplatBitSize = SplatBitSize * 2)
3149 SplatValue |= SplatValue.shl(SplatBitSize);
3151 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3152 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3153 if (SplatBitSize % BitWidth == 0) {
3154 Constant = APInt::getAllOnesValue(BitWidth);
3155 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3156 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3161 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3162 // actually legal and isn't going to get expanded, else this is a false
3164 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3165 Load->getValueType(0),
3166 Load->getMemoryVT());
3168 // Resize the constant to the same size as the original memory access before
3169 // extension. If it is still the AllOnesValue then this AND is completely
3172 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3175 switch (Load->getExtensionType()) {
3176 default: B = false; break;
3177 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3179 case ISD::NON_EXTLOAD: B = true; break;
3182 if (B && Constant.isAllOnesValue()) {
3183 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3184 // preserve semantics once we get rid of the AND.
3185 SDValue NewLoad(Load, 0);
3186 if (Load->getExtensionType() == ISD::EXTLOAD) {
3187 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3188 Load->getValueType(0), SDLoc(Load),
3189 Load->getChain(), Load->getBasePtr(),
3190 Load->getOffset(), Load->getMemoryVT(),
3191 Load->getMemOperand());
3192 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3193 if (Load->getNumValues() == 3) {
3194 // PRE/POST_INC loads have 3 values.
3195 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3196 NewLoad.getValue(2) };
3197 CombineTo(Load, To, 3, true);
3199 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3203 // Fold the AND away, taking care not to fold to the old load node if we
3205 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3207 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3211 // fold (and (load x), 255) -> (zextload x, i8)
3212 // fold (and (extload x, i16), 255) -> (zextload x, i8)
3213 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3214 if (N1C && (N0.getOpcode() == ISD::LOAD ||
3215 (N0.getOpcode() == ISD::ANY_EXTEND &&
3216 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3217 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3218 LoadSDNode *LN0 = HasAnyExt
3219 ? cast<LoadSDNode>(N0.getOperand(0))
3220 : cast<LoadSDNode>(N0);
3221 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3222 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3223 auto NarrowLoad = false;
3224 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3225 EVT ExtVT, LoadedVT;
3226 if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3230 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3231 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3232 LN0->getMemOperand());
3234 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3235 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3237 EVT PtrType = LN0->getOperand(1).getValueType();
3239 unsigned Alignment = LN0->getAlignment();
3240 SDValue NewPtr = LN0->getBasePtr();
3242 // For big endian targets, we need to add an offset to the pointer
3243 // to load the correct bytes. For little endian systems, we merely
3244 // need to read fewer bytes from the same pointer.
3245 if (DAG.getDataLayout().isBigEndian()) {
3246 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3247 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3248 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3250 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3251 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3252 Alignment = MinAlign(Alignment, PtrOff);
3255 AddToWorklist(NewPtr.getNode());
3258 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3259 LN0->getChain(), NewPtr,
3260 LN0->getPointerInfo(),
3261 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3262 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3264 CombineTo(LN0, Load, Load.getValue(1));
3265 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3271 if (SDValue Combined = visitANDLike(N0, N1, N))
3274 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3275 if (N0.getOpcode() == N1.getOpcode())
3276 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3279 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3280 // fold (and (sra)) -> (and (srl)) when possible.
3281 if (!VT.isVector() &&
3282 SimplifyDemandedBits(SDValue(N, 0)))
3283 return SDValue(N, 0);
3285 // fold (zext_inreg (extload x)) -> (zextload x)
3286 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3287 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3288 EVT MemVT = LN0->getMemoryVT();
3289 // If we zero all the possible extended bits, then we can turn this into
3290 // a zextload if we are running before legalize or the operation is legal.
3291 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3292 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3293 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3294 ((!LegalOperations && !LN0->isVolatile()) ||
3295 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3296 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3297 LN0->getChain(), LN0->getBasePtr(),
3298 MemVT, LN0->getMemOperand());
3300 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3301 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3304 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3305 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3307 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3308 EVT MemVT = LN0->getMemoryVT();
3309 // If we zero all the possible extended bits, then we can turn this into
3310 // a zextload if we are running before legalize or the operation is legal.
3311 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3312 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3313 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3314 ((!LegalOperations && !LN0->isVolatile()) ||
3315 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3316 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3317 LN0->getChain(), LN0->getBasePtr(),
3318 MemVT, LN0->getMemOperand());
3320 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3321 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3324 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3325 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3326 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3327 N0.getOperand(1), false);
3328 if (BSwap.getNode())
3335 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3336 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3337 bool DemandHighBits) {
3338 if (!LegalOperations)
3341 EVT VT = N->getValueType(0);
3342 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3344 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3347 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3348 bool LookPassAnd0 = false;
3349 bool LookPassAnd1 = false;
3350 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3352 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3354 if (N0.getOpcode() == ISD::AND) {
3355 if (!N0.getNode()->hasOneUse())
3357 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3358 if (!N01C || N01C->getZExtValue() != 0xFF00)
3360 N0 = N0.getOperand(0);
3361 LookPassAnd0 = true;
3364 if (N1.getOpcode() == ISD::AND) {
3365 if (!N1.getNode()->hasOneUse())
3367 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3368 if (!N11C || N11C->getZExtValue() != 0xFF)
3370 N1 = N1.getOperand(0);
3371 LookPassAnd1 = true;
3374 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3376 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3378 if (!N0.getNode()->hasOneUse() ||
3379 !N1.getNode()->hasOneUse())
3382 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3383 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3386 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3389 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3390 SDValue N00 = N0->getOperand(0);
3391 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3392 if (!N00.getNode()->hasOneUse())
3394 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3395 if (!N001C || N001C->getZExtValue() != 0xFF)
3397 N00 = N00.getOperand(0);
3398 LookPassAnd0 = true;
3401 SDValue N10 = N1->getOperand(0);
3402 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3403 if (!N10.getNode()->hasOneUse())
3405 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3406 if (!N101C || N101C->getZExtValue() != 0xFF00)
3408 N10 = N10.getOperand(0);
3409 LookPassAnd1 = true;
3415 // Make sure everything beyond the low halfword gets set to zero since the SRL
3416 // 16 will clear the top bits.
3417 unsigned OpSizeInBits = VT.getSizeInBits();
3418 if (DemandHighBits && OpSizeInBits > 16) {
3419 // If the left-shift isn't masked out then the only way this is a bswap is
3420 // if all bits beyond the low 8 are 0. In that case the entire pattern
3421 // reduces to a left shift anyway: leave it for other parts of the combiner.
3425 // However, if the right shift isn't masked out then it might be because
3426 // it's not needed. See if we can spot that too.
3427 if (!LookPassAnd1 &&
3428 !DAG.MaskedValueIsZero(
3429 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3433 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3434 if (OpSizeInBits > 16) {
3436 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3437 DAG.getConstant(OpSizeInBits - 16, DL,
3438 getShiftAmountTy(VT)));
3443 /// Return true if the specified node is an element that makes up a 32-bit
3444 /// packed halfword byteswap.
3445 /// ((x & 0x000000ff) << 8) |
3446 /// ((x & 0x0000ff00) >> 8) |
3447 /// ((x & 0x00ff0000) << 8) |
3448 /// ((x & 0xff000000) >> 8)
3449 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3450 if (!N.getNode()->hasOneUse())
3453 unsigned Opc = N.getOpcode();
3454 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3457 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3462 switch (N1C->getZExtValue()) {
3465 case 0xFF: Num = 0; break;
3466 case 0xFF00: Num = 1; break;
3467 case 0xFF0000: Num = 2; break;
3468 case 0xFF000000: Num = 3; break;
3471 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3472 SDValue N0 = N.getOperand(0);
3473 if (Opc == ISD::AND) {
3474 if (Num == 0 || Num == 2) {
3476 // (x >> 8) & 0xff0000
3477 if (N0.getOpcode() != ISD::SRL)
3479 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3480 if (!C || C->getZExtValue() != 8)
3483 // (x << 8) & 0xff00
3484 // (x << 8) & 0xff000000
3485 if (N0.getOpcode() != ISD::SHL)
3487 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3488 if (!C || C->getZExtValue() != 8)
3491 } else if (Opc == ISD::SHL) {
3493 // (x & 0xff0000) << 8
3494 if (Num != 0 && Num != 2)
3496 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3497 if (!C || C->getZExtValue() != 8)
3499 } else { // Opc == ISD::SRL
3500 // (x & 0xff00) >> 8
3501 // (x & 0xff000000) >> 8
3502 if (Num != 1 && Num != 3)
3504 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3505 if (!C || C->getZExtValue() != 8)
3512 Parts[Num] = N0.getOperand(0).getNode();
3516 /// Match a 32-bit packed halfword bswap. That is
3517 /// ((x & 0x000000ff) << 8) |
3518 /// ((x & 0x0000ff00) >> 8) |
3519 /// ((x & 0x00ff0000) << 8) |
3520 /// ((x & 0xff000000) >> 8)
3521 /// => (rotl (bswap x), 16)
3522 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3523 if (!LegalOperations)
3526 EVT VT = N->getValueType(0);
3529 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3533 // (or (or (and), (and)), (or (and), (and)))
3534 // (or (or (or (and), (and)), (and)), (and))
3535 if (N0.getOpcode() != ISD::OR)
3537 SDValue N00 = N0.getOperand(0);
3538 SDValue N01 = N0.getOperand(1);
3539 SDNode *Parts[4] = {};
3541 if (N1.getOpcode() == ISD::OR &&
3542 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3543 // (or (or (and), (and)), (or (and), (and)))
3544 SDValue N000 = N00.getOperand(0);
3545 if (!isBSwapHWordElement(N000, Parts))
3548 SDValue N001 = N00.getOperand(1);
3549 if (!isBSwapHWordElement(N001, Parts))
3551 SDValue N010 = N01.getOperand(0);
3552 if (!isBSwapHWordElement(N010, Parts))
3554 SDValue N011 = N01.getOperand(1);
3555 if (!isBSwapHWordElement(N011, Parts))
3558 // (or (or (or (and), (and)), (and)), (and))
3559 if (!isBSwapHWordElement(N1, Parts))
3561 if (!isBSwapHWordElement(N01, Parts))
3563 if (N00.getOpcode() != ISD::OR)
3565 SDValue N000 = N00.getOperand(0);
3566 if (!isBSwapHWordElement(N000, Parts))
3568 SDValue N001 = N00.getOperand(1);
3569 if (!isBSwapHWordElement(N001, Parts))
3573 // Make sure the parts are all coming from the same node.
3574 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3578 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3579 SDValue(Parts[0], 0));
3581 // Result of the bswap should be rotated by 16. If it's not legal, then
3582 // do (x << 16) | (x >> 16).
3583 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3584 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3585 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3586 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3587 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3588 return DAG.getNode(ISD::OR, DL, VT,
3589 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3590 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3593 /// This contains all DAGCombine rules which reduce two values combined by
3594 /// an Or operation to a single value \see visitANDLike().
3595 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3596 EVT VT = N1.getValueType();
3597 // fold (or x, undef) -> -1
3598 if (!LegalOperations &&
3599 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3600 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3601 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3602 SDLoc(LocReference), VT);
3604 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3605 SDValue LL, LR, RL, RR, CC0, CC1;
3606 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3607 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3608 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3610 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3611 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3612 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3613 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3614 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3615 LR.getValueType(), LL, RL);
3616 AddToWorklist(ORNode.getNode());
3617 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3619 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3620 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3621 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3622 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3623 LR.getValueType(), LL, RL);
3624 AddToWorklist(ANDNode.getNode());
3625 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3628 // canonicalize equivalent to ll == rl
3629 if (LL == RR && LR == RL) {
3630 Op1 = ISD::getSetCCSwappedOperands(Op1);
3633 if (LL == RL && LR == RR) {
3634 bool isInteger = LL.getValueType().isInteger();
3635 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3636 if (Result != ISD::SETCC_INVALID &&
3637 (!LegalOperations ||
3638 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3639 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3640 EVT CCVT = getSetCCResultType(LL.getValueType());
3641 if (N0.getValueType() == CCVT ||
3642 (!LegalOperations && N0.getValueType() == MVT::i1))
3643 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3649 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3650 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3651 // Don't increase # computations.
3652 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3653 // We can only do this xform if we know that bits from X that are set in C2
3654 // but not in C1 are already zero. Likewise for Y.
3655 if (const ConstantSDNode *N0O1C =
3656 getAsNonOpaqueConstant(N0.getOperand(1))) {
3657 if (const ConstantSDNode *N1O1C =
3658 getAsNonOpaqueConstant(N1.getOperand(1))) {
3659 // We can only do this xform if we know that bits from X that are set in
3660 // C2 but not in C1 are already zero. Likewise for Y.
3661 const APInt &LHSMask = N0O1C->getAPIntValue();
3662 const APInt &RHSMask = N1O1C->getAPIntValue();
3664 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3665 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3666 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3667 N0.getOperand(0), N1.getOperand(0));
3668 SDLoc DL(LocReference);
3669 return DAG.getNode(ISD::AND, DL, VT, X,
3670 DAG.getConstant(LHSMask | RHSMask, DL, VT));
3676 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3677 if (N0.getOpcode() == ISD::AND &&
3678 N1.getOpcode() == ISD::AND &&
3679 N0.getOperand(0) == N1.getOperand(0) &&
3680 // Don't increase # computations.
3681 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3682 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3683 N0.getOperand(1), N1.getOperand(1));
3684 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3690 SDValue DAGCombiner::visitOR(SDNode *N) {
3691 SDValue N0 = N->getOperand(0);
3692 SDValue N1 = N->getOperand(1);
3693 EVT VT = N1.getValueType();
3696 if (VT.isVector()) {
3697 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3700 // fold (or x, 0) -> x, vector edition
3701 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3703 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3706 // fold (or x, -1) -> -1, vector edition
3707 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3708 // do not return N0, because undef node may exist in N0
3709 return DAG.getConstant(
3710 APInt::getAllOnesValue(
3711 N0.getValueType().getScalarType().getSizeInBits()),
3712 SDLoc(N), N0.getValueType());
3713 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3714 // do not return N1, because undef node may exist in N1
3715 return DAG.getConstant(
3716 APInt::getAllOnesValue(
3717 N1.getValueType().getScalarType().getSizeInBits()),
3718 SDLoc(N), N1.getValueType());
3720 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3721 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3722 // Do this only if the resulting shuffle is legal.
3723 if (isa<ShuffleVectorSDNode>(N0) &&
3724 isa<ShuffleVectorSDNode>(N1) &&
3725 // Avoid folding a node with illegal type.
3726 TLI.isTypeLegal(VT) &&
3727 N0->getOperand(1) == N1->getOperand(1) &&
3728 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3729 bool CanFold = true;
3730 unsigned NumElts = VT.getVectorNumElements();
3731 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3732 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3733 // We construct two shuffle masks:
3734 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3735 // and N1 as the second operand.
3736 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3737 // and N0 as the second operand.
3738 // We do this because OR is commutable and therefore there might be
3739 // two ways to fold this node into a shuffle.
3740 SmallVector<int,4> Mask1;
3741 SmallVector<int,4> Mask2;
3743 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3744 int M0 = SV0->getMaskElt(i);
3745 int M1 = SV1->getMaskElt(i);
3747 // Both shuffle indexes are undef. Propagate Undef.
3748 if (M0 < 0 && M1 < 0) {
3749 Mask1.push_back(M0);
3750 Mask2.push_back(M0);
3754 if (M0 < 0 || M1 < 0 ||
3755 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3756 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3761 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3762 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3766 // Fold this sequence only if the resulting shuffle is 'legal'.
3767 if (TLI.isShuffleMaskLegal(Mask1, VT))
3768 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3769 N1->getOperand(0), &Mask1[0]);
3770 if (TLI.isShuffleMaskLegal(Mask2, VT))
3771 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3772 N0->getOperand(0), &Mask2[0]);
3777 // fold (or c1, c2) -> c1|c2
3778 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3779 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3780 if (N0C && N1C && !N1C->isOpaque())
3781 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3782 // canonicalize constant to RHS
3783 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3784 !isConstantIntBuildVectorOrConstantInt(N1))
3785 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3786 // fold (or x, 0) -> x
3787 if (isNullConstant(N1))
3789 // fold (or x, -1) -> -1
3790 if (isAllOnesConstant(N1))
3792 // fold (or x, c) -> c iff (x & ~c) == 0
3793 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3796 if (SDValue Combined = visitORLike(N0, N1, N))
3799 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3800 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3802 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3806 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3808 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3809 // iff (c1 & c2) == 0.
3810 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3811 isa<ConstantSDNode>(N0.getOperand(1))) {
3812 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3813 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3814 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3817 ISD::AND, SDLoc(N), VT,
3818 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3822 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3823 if (N0.getOpcode() == N1.getOpcode())
3824 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3827 // See if this is some rotate idiom.
3828 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3829 return SDValue(Rot, 0);
3831 // Simplify the operands using demanded-bits information.
3832 if (!VT.isVector() &&
3833 SimplifyDemandedBits(SDValue(N, 0)))
3834 return SDValue(N, 0);
3839 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3840 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3841 if (Op.getOpcode() == ISD::AND) {
3842 if (isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
3843 Mask = Op.getOperand(1);
3844 Op = Op.getOperand(0);
3850 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3858 // Return true if we can prove that, whenever Neg and Pos are both in the
3859 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that
3860 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3862 // (or (shift1 X, Neg), (shift2 X, Pos))
3864 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3865 // in direction shift1 by Neg. The range [0, EltSize) means that we only need
3866 // to consider shift amounts with defined behavior.
3867 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
3868 // If EltSize is a power of 2 then:
3870 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
3871 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
3873 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
3874 // for the stronger condition:
3876 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A]
3878 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
3879 // we can just replace Neg with Neg' for the rest of the function.
3881 // In other cases we check for the even stronger condition:
3883 // Neg == EltSize - Pos [B]
3885 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3886 // behavior if Pos == 0 (and consequently Neg == EltSize).
3888 // We could actually use [A] whenever EltSize is a power of 2, but the
3889 // only extra cases that it would match are those uninteresting ones
3890 // where Neg and Pos are never in range at the same time. E.g. for
3891 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3892 // as well as (sub 32, Pos), but:
3894 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3896 // always invokes undefined behavior for 32-bit X.
3898 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
3899 unsigned MaskLoBits = 0;
3900 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
3901 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
3902 if (NegC->getAPIntValue() == EltSize - 1) {
3903 Neg = Neg.getOperand(0);
3904 MaskLoBits = Log2_64(EltSize);
3909 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3910 if (Neg.getOpcode() != ISD::SUB)
3912 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
3915 SDValue NegOp1 = Neg.getOperand(1);
3917 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
3918 // Pos'. The truncation is redundant for the purpose of the equality.
3919 if (MaskLoBits && Pos.getOpcode() == ISD::AND)
3920 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3921 if (PosC->getAPIntValue() == EltSize - 1)
3922 Pos = Pos.getOperand(0);
3924 // The condition we need is now:
3926 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
3928 // If NegOp1 == Pos then we need:
3930 // EltSize & Mask == NegC & Mask
3932 // (because "x & Mask" is a truncation and distributes through subtraction).
3935 Width = NegC->getAPIntValue();
3937 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3938 // Then the condition we want to prove becomes:
3940 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
3942 // which, again because "x & Mask" is a truncation, becomes:
3944 // NegC & Mask == (EltSize - PosC) & Mask
3945 // EltSize & Mask == (NegC + PosC) & Mask
3946 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
3947 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3948 Width = PosC->getAPIntValue() + NegC->getAPIntValue();
3954 // Now we just need to check that EltSize & Mask == Width & Mask.
3956 // EltSize & Mask is 0 since Mask is EltSize - 1.
3957 return Width.getLoBits(MaskLoBits) == 0;
3958 return Width == EltSize;
3961 // A subroutine of MatchRotate used once we have found an OR of two opposite
3962 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3963 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3964 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3965 // Neg with outer conversions stripped away.
3966 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3967 SDValue Neg, SDValue InnerPos,
3968 SDValue InnerNeg, unsigned PosOpcode,
3969 unsigned NegOpcode, SDLoc DL) {
3970 // fold (or (shl x, (*ext y)),
3971 // (srl x, (*ext (sub 32, y)))) ->
3972 // (rotl x, y) or (rotr x, (sub 32, y))
3974 // fold (or (shl x, (*ext (sub 32, y))),
3975 // (srl x, (*ext y))) ->
3976 // (rotr x, y) or (rotl x, (sub 32, y))
3977 EVT VT = Shifted.getValueType();
3978 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
3979 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3980 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3981 HasPos ? Pos : Neg).getNode();
3987 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3988 // idioms for rotate, and if the target supports rotation instructions, generate
3990 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3991 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3992 EVT VT = LHS.getValueType();
3993 if (!TLI.isTypeLegal(VT)) return nullptr;
3995 // The target must have at least one rotate flavor.
3996 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3997 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3998 if (!HasROTL && !HasROTR) return nullptr;
4000 // Match "(X shl/srl V1) & V2" where V2 may not be present.
4001 SDValue LHSShift; // The shift.
4002 SDValue LHSMask; // AND value if any.
4003 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4004 return nullptr; // Not part of a rotate.
4006 SDValue RHSShift; // The shift.
4007 SDValue RHSMask; // AND value if any.
4008 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4009 return nullptr; // Not part of a rotate.
4011 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4012 return nullptr; // Not shifting the same value.
4014 if (LHSShift.getOpcode() == RHSShift.getOpcode())
4015 return nullptr; // Shifts must disagree.
4017 // Canonicalize shl to left side in a shl/srl pair.
4018 if (RHSShift.getOpcode() == ISD::SHL) {
4019 std::swap(LHS, RHS);
4020 std::swap(LHSShift, RHSShift);
4021 std::swap(LHSMask, RHSMask);
4024 unsigned EltSizeInBits = VT.getScalarSizeInBits();
4025 SDValue LHSShiftArg = LHSShift.getOperand(0);
4026 SDValue LHSShiftAmt = LHSShift.getOperand(1);
4027 SDValue RHSShiftArg = RHSShift.getOperand(0);
4028 SDValue RHSShiftAmt = RHSShift.getOperand(1);
4030 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4031 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4032 if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4033 uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4034 uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4035 if ((LShVal + RShVal) != EltSizeInBits)
4038 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4039 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4041 // If there is an AND of either shifted operand, apply it to the result.
4042 if (LHSMask.getNode() || RHSMask.getNode()) {
4043 APInt AllBits = APInt::getAllOnesValue(EltSizeInBits);
4044 SDValue Mask = DAG.getConstant(AllBits, DL, VT);
4046 if (LHSMask.getNode()) {
4047 APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4048 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4049 DAG.getNode(ISD::OR, DL, VT, LHSMask,
4050 DAG.getConstant(RHSBits, DL, VT)));
4052 if (RHSMask.getNode()) {
4053 APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4054 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4055 DAG.getNode(ISD::OR, DL, VT, RHSMask,
4056 DAG.getConstant(LHSBits, DL, VT)));
4059 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4062 return Rot.getNode();
4065 // If there is a mask here, and we have a variable shift, we can't be sure
4066 // that we're masking out the right stuff.
4067 if (LHSMask.getNode() || RHSMask.getNode())
4070 // If the shift amount is sign/zext/any-extended just peel it off.
4071 SDValue LExtOp0 = LHSShiftAmt;
4072 SDValue RExtOp0 = RHSShiftAmt;
4073 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4074 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4075 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4076 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4077 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4078 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4079 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4080 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4081 LExtOp0 = LHSShiftAmt.getOperand(0);
4082 RExtOp0 = RHSShiftAmt.getOperand(0);
4085 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4086 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4090 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4091 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4098 SDValue DAGCombiner::visitXOR(SDNode *N) {
4099 SDValue N0 = N->getOperand(0);
4100 SDValue N1 = N->getOperand(1);
4101 EVT VT = N0.getValueType();
4104 if (VT.isVector()) {
4105 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4108 // fold (xor x, 0) -> x, vector edition
4109 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4111 if (ISD::isBuildVectorAllZeros(N1.getNode()))
4115 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4116 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
4117 return DAG.getConstant(0, SDLoc(N), VT);
4118 // fold (xor x, undef) -> undef
4119 if (N0.getOpcode() == ISD::UNDEF)
4121 if (N1.getOpcode() == ISD::UNDEF)
4123 // fold (xor c1, c2) -> c1^c2
4124 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4125 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4127 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4128 // canonicalize constant to RHS
4129 if (isConstantIntBuildVectorOrConstantInt(N0) &&
4130 !isConstantIntBuildVectorOrConstantInt(N1))
4131 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4132 // fold (xor x, 0) -> x
4133 if (isNullConstant(N1))
4136 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4139 // fold !(x cc y) -> (x !cc y)
4140 SDValue LHS, RHS, CC;
4141 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4142 bool isInt = LHS.getValueType().isInteger();
4143 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4146 if (!LegalOperations ||
4147 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4148 switch (N0.getOpcode()) {
4150 llvm_unreachable("Unhandled SetCC Equivalent!");
4152 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4153 case ISD::SELECT_CC:
4154 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4155 N0.getOperand(3), NotCC);
4160 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4161 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4162 N0.getNode()->hasOneUse() &&
4163 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4164 SDValue V = N0.getOperand(0);
4166 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4167 DAG.getConstant(1, DL, V.getValueType()));
4168 AddToWorklist(V.getNode());
4169 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4172 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4173 if (isOneConstant(N1) && VT == MVT::i1 &&
4174 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4175 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4176 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4177 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4178 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4179 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4180 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4181 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4184 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4185 if (isAllOnesConstant(N1) &&
4186 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4187 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4188 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4189 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4190 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4191 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4192 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4193 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4196 // fold (xor (and x, y), y) -> (and (not x), y)
4197 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4198 N0->getOperand(1) == N1) {
4199 SDValue X = N0->getOperand(0);
4200 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4201 AddToWorklist(NotX.getNode());
4202 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4204 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4205 if (N1C && N0.getOpcode() == ISD::XOR) {
4206 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4208 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4209 DAG.getConstant(N1C->getAPIntValue() ^
4210 N00C->getAPIntValue(), DL, VT));
4212 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4214 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4215 DAG.getConstant(N1C->getAPIntValue() ^
4216 N01C->getAPIntValue(), DL, VT));
4219 // fold (xor x, x) -> 0
4221 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4223 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4224 // Here is a concrete example of this equivalence:
4226 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
4227 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4231 // i16 ~1 == 0b1111111111111110
4232 // i16 rol(~1, 14) == 0b1011111111111111
4234 // Some additional tips to help conceptualize this transform:
4235 // - Try to see the operation as placing a single zero in a value of all ones.
4236 // - There exists no value for x which would allow the result to contain zero.
4237 // - Values of x larger than the bitwidth are undefined and do not require a
4238 // consistent result.
4239 // - Pushing the zero left requires shifting one bits in from the right.
4240 // A rotate left of ~1 is a nice way of achieving the desired result.
4241 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4242 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4244 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4248 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4249 if (N0.getOpcode() == N1.getOpcode())
4250 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4253 // Simplify the expression using non-local knowledge.
4254 if (!VT.isVector() &&
4255 SimplifyDemandedBits(SDValue(N, 0)))
4256 return SDValue(N, 0);
4261 /// Handle transforms common to the three shifts, when the shift amount is a
4263 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4264 SDNode *LHS = N->getOperand(0).getNode();
4265 if (!LHS->hasOneUse()) return SDValue();
4267 // We want to pull some binops through shifts, so that we have (and (shift))
4268 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4269 // thing happens with address calculations, so it's important to canonicalize
4271 bool HighBitSet = false; // Can we transform this if the high bit is set?
4273 switch (LHS->getOpcode()) {
4274 default: return SDValue();
4277 HighBitSet = false; // We can only transform sra if the high bit is clear.
4280 HighBitSet = true; // We can only transform sra if the high bit is set.
4283 if (N->getOpcode() != ISD::SHL)
4284 return SDValue(); // only shl(add) not sr[al](add).
4285 HighBitSet = false; // We can only transform sra if the high bit is clear.
4289 // We require the RHS of the binop to be a constant and not opaque as well.
4290 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4291 if (!BinOpCst) return SDValue();
4293 // FIXME: disable this unless the input to the binop is a shift by a constant.
4294 // If it is not a shift, it pessimizes some common cases like:
4296 // void foo(int *X, int i) { X[i & 1235] = 1; }
4297 // int bar(int *X, int i) { return X[i & 255]; }
4298 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4299 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4300 BinOpLHSVal->getOpcode() != ISD::SRA &&
4301 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4302 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4305 EVT VT = N->getValueType(0);
4307 // If this is a signed shift right, and the high bit is modified by the
4308 // logical operation, do not perform the transformation. The highBitSet
4309 // boolean indicates the value of the high bit of the constant which would
4310 // cause it to be modified for this operation.
4311 if (N->getOpcode() == ISD::SRA) {
4312 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4313 if (BinOpRHSSignSet != HighBitSet)
4317 if (!TLI.isDesirableToCommuteWithShift(LHS))
4320 // Fold the constants, shifting the binop RHS by the shift amount.
4321 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4323 LHS->getOperand(1), N->getOperand(1));
4324 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4326 // Create the new shift.
4327 SDValue NewShift = DAG.getNode(N->getOpcode(),
4328 SDLoc(LHS->getOperand(0)),
4329 VT, LHS->getOperand(0), N->getOperand(1));
4331 // Create the new binop.
4332 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4335 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4336 assert(N->getOpcode() == ISD::TRUNCATE);
4337 assert(N->getOperand(0).getOpcode() == ISD::AND);
4339 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4340 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4341 SDValue N01 = N->getOperand(0).getOperand(1);
4343 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4344 if (!N01C->isOpaque()) {
4345 EVT TruncVT = N->getValueType(0);
4346 SDValue N00 = N->getOperand(0).getOperand(0);
4347 APInt TruncC = N01C->getAPIntValue();
4348 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4351 return DAG.getNode(ISD::AND, DL, TruncVT,
4352 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4353 DAG.getConstant(TruncC, DL, TruncVT));
4361 SDValue DAGCombiner::visitRotate(SDNode *N) {
4362 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4363 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4364 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4365 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4366 if (NewOp1.getNode())
4367 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4368 N->getOperand(0), NewOp1);
4373 SDValue DAGCombiner::visitSHL(SDNode *N) {
4374 SDValue N0 = N->getOperand(0);
4375 SDValue N1 = N->getOperand(1);
4376 EVT VT = N0.getValueType();
4377 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4380 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4381 if (VT.isVector()) {
4382 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4385 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4386 // If setcc produces all-one true value then:
4387 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4388 if (N1CV && N1CV->isConstant()) {
4389 if (N0.getOpcode() == ISD::AND) {
4390 SDValue N00 = N0->getOperand(0);
4391 SDValue N01 = N0->getOperand(1);
4392 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4394 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4395 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4396 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4397 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4399 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4402 N1C = isConstOrConstSplat(N1);
4407 // fold (shl c1, c2) -> c1<<c2
4408 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4409 if (N0C && N1C && !N1C->isOpaque())
4410 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4411 // fold (shl 0, x) -> 0
4412 if (isNullConstant(N0))
4414 // fold (shl x, c >= size(x)) -> undef
4415 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4416 return DAG.getUNDEF(VT);
4417 // fold (shl x, 0) -> x
4418 if (N1C && N1C->isNullValue())
4420 // fold (shl undef, x) -> 0
4421 if (N0.getOpcode() == ISD::UNDEF)
4422 return DAG.getConstant(0, SDLoc(N), VT);
4423 // if (shl x, c) is known to be zero, return 0
4424 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4425 APInt::getAllOnesValue(OpSizeInBits)))
4426 return DAG.getConstant(0, SDLoc(N), VT);
4427 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4428 if (N1.getOpcode() == ISD::TRUNCATE &&
4429 N1.getOperand(0).getOpcode() == ISD::AND) {
4430 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4431 if (NewOp1.getNode())
4432 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4435 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4436 return SDValue(N, 0);
4438 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4439 if (N1C && N0.getOpcode() == ISD::SHL) {
4440 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4441 uint64_t c1 = N0C1->getZExtValue();
4442 uint64_t c2 = N1C->getZExtValue();
4444 if (c1 + c2 >= OpSizeInBits)
4445 return DAG.getConstant(0, DL, VT);
4446 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4447 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4451 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4452 // For this to be valid, the second form must not preserve any of the bits
4453 // that are shifted out by the inner shift in the first form. This means
4454 // the outer shift size must be >= the number of bits added by the ext.
4455 // As a corollary, we don't care what kind of ext it is.
4456 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4457 N0.getOpcode() == ISD::ANY_EXTEND ||
4458 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4459 N0.getOperand(0).getOpcode() == ISD::SHL) {
4460 SDValue N0Op0 = N0.getOperand(0);
4461 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4462 uint64_t c1 = N0Op0C1->getZExtValue();
4463 uint64_t c2 = N1C->getZExtValue();
4464 EVT InnerShiftVT = N0Op0.getValueType();
4465 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4466 if (c2 >= OpSizeInBits - InnerShiftSize) {
4468 if (c1 + c2 >= OpSizeInBits)
4469 return DAG.getConstant(0, DL, VT);
4470 return DAG.getNode(ISD::SHL, DL, VT,
4471 DAG.getNode(N0.getOpcode(), DL, VT,
4472 N0Op0->getOperand(0)),
4473 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4478 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4479 // Only fold this if the inner zext has no other uses to avoid increasing
4480 // the total number of instructions.
4481 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4482 N0.getOperand(0).getOpcode() == ISD::SRL) {
4483 SDValue N0Op0 = N0.getOperand(0);
4484 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4485 uint64_t c1 = N0Op0C1->getZExtValue();
4486 if (c1 < VT.getScalarSizeInBits()) {
4487 uint64_t c2 = N1C->getZExtValue();
4489 SDValue NewOp0 = N0.getOperand(0);
4490 EVT CountVT = NewOp0.getOperand(1).getValueType();
4492 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4494 DAG.getConstant(c2, DL, CountVT));
4495 AddToWorklist(NewSHL.getNode());
4496 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4502 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
4503 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2
4504 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4505 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4506 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4507 uint64_t C1 = N0C1->getZExtValue();
4508 uint64_t C2 = N1C->getZExtValue();
4511 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4512 DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4513 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4514 DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4518 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4519 // (and (srl x, (sub c1, c2), MASK)
4520 // Only fold this if the inner shift has no other uses -- if it does, folding
4521 // this will increase the total number of instructions.
4522 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4523 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4524 uint64_t c1 = N0C1->getZExtValue();
4525 if (c1 < OpSizeInBits) {
4526 uint64_t c2 = N1C->getZExtValue();
4527 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4530 Mask = Mask.shl(c2 - c1);
4532 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4533 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4535 Mask = Mask.lshr(c1 - c2);
4537 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4538 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4541 return DAG.getNode(ISD::AND, DL, VT, Shift,
4542 DAG.getConstant(Mask, DL, VT));
4546 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4547 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4548 unsigned BitSize = VT.getScalarSizeInBits();
4550 SDValue HiBitsMask =
4551 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4552 BitSize - N1C->getZExtValue()),
4554 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4558 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4559 // Variant of version done on multiply, except mul by a power of 2 is turned
4562 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4563 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4564 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4565 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4566 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4567 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4570 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4571 if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4572 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4573 if (SDValue Folded =
4574 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4575 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4579 if (N1C && !N1C->isOpaque())
4580 if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4586 SDValue DAGCombiner::visitSRA(SDNode *N) {
4587 SDValue N0 = N->getOperand(0);
4588 SDValue N1 = N->getOperand(1);
4589 EVT VT = N0.getValueType();
4590 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4593 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4594 if (VT.isVector()) {
4595 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4598 N1C = isConstOrConstSplat(N1);
4601 // fold (sra c1, c2) -> (sra c1, c2)
4602 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4603 if (N0C && N1C && !N1C->isOpaque())
4604 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4605 // fold (sra 0, x) -> 0
4606 if (isNullConstant(N0))
4608 // fold (sra -1, x) -> -1
4609 if (isAllOnesConstant(N0))
4611 // fold (sra x, (setge c, size(x))) -> undef
4612 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4613 return DAG.getUNDEF(VT);
4614 // fold (sra x, 0) -> x
4615 if (N1C && N1C->isNullValue())
4617 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4619 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4620 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4621 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4623 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4624 ExtVT, VT.getVectorNumElements());
4625 if ((!LegalOperations ||
4626 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4627 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4628 N0.getOperand(0), DAG.getValueType(ExtVT));
4631 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4632 if (N1C && N0.getOpcode() == ISD::SRA) {
4633 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4634 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4635 if (Sum >= OpSizeInBits)
4636 Sum = OpSizeInBits - 1;
4638 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4639 DAG.getConstant(Sum, DL, N1.getValueType()));
4643 // fold (sra (shl X, m), (sub result_size, n))
4644 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4645 // result_size - n != m.
4646 // If truncate is free for the target sext(shl) is likely to result in better
4648 if (N0.getOpcode() == ISD::SHL && N1C) {
4649 // Get the two constanst of the shifts, CN0 = m, CN = n.
4650 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4652 LLVMContext &Ctx = *DAG.getContext();
4653 // Determine what the truncate's result bitsize and type would be.
4654 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4657 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4659 // Determine the residual right-shift amount.
4660 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4662 // If the shift is not a no-op (in which case this should be just a sign
4663 // extend already), the truncated to type is legal, sign_extend is legal
4664 // on that type, and the truncate to that type is both legal and free,
4665 // perform the transform.
4666 if ((ShiftAmt > 0) &&
4667 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4668 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4669 TLI.isTruncateFree(VT, TruncVT)) {
4672 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4673 getShiftAmountTy(N0.getOperand(0).getValueType()));
4674 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4675 N0.getOperand(0), Amt);
4676 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4678 return DAG.getNode(ISD::SIGN_EXTEND, DL,
4679 N->getValueType(0), Trunc);
4684 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4685 if (N1.getOpcode() == ISD::TRUNCATE &&
4686 N1.getOperand(0).getOpcode() == ISD::AND) {
4687 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4688 if (NewOp1.getNode())
4689 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4692 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4693 // if c1 is equal to the number of bits the trunc removes
4694 if (N0.getOpcode() == ISD::TRUNCATE &&
4695 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4696 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4697 N0.getOperand(0).hasOneUse() &&
4698 N0.getOperand(0).getOperand(1).hasOneUse() &&
4700 SDValue N0Op0 = N0.getOperand(0);
4701 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4702 unsigned LargeShiftVal = LargeShift->getZExtValue();
4703 EVT LargeVT = N0Op0.getValueType();
4705 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4708 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4709 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4710 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4711 N0Op0.getOperand(0), Amt);
4712 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4717 // Simplify, based on bits shifted out of the LHS.
4718 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4719 return SDValue(N, 0);
4722 // If the sign bit is known to be zero, switch this to a SRL.
4723 if (DAG.SignBitIsZero(N0))
4724 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4726 if (N1C && !N1C->isOpaque())
4727 if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4733 SDValue DAGCombiner::visitSRL(SDNode *N) {
4734 SDValue N0 = N->getOperand(0);
4735 SDValue N1 = N->getOperand(1);
4736 EVT VT = N0.getValueType();
4737 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4740 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4741 if (VT.isVector()) {
4742 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4745 N1C = isConstOrConstSplat(N1);
4748 // fold (srl c1, c2) -> c1 >>u c2
4749 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4750 if (N0C && N1C && !N1C->isOpaque())
4751 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4752 // fold (srl 0, x) -> 0
4753 if (isNullConstant(N0))
4755 // fold (srl x, c >= size(x)) -> undef
4756 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4757 return DAG.getUNDEF(VT);
4758 // fold (srl x, 0) -> x
4759 if (N1C && N1C->isNullValue())
4761 // if (srl x, c) is known to be zero, return 0
4762 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4763 APInt::getAllOnesValue(OpSizeInBits)))
4764 return DAG.getConstant(0, SDLoc(N), VT);
4766 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4767 if (N1C && N0.getOpcode() == ISD::SRL) {
4768 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4769 uint64_t c1 = N01C->getZExtValue();
4770 uint64_t c2 = N1C->getZExtValue();
4772 if (c1 + c2 >= OpSizeInBits)
4773 return DAG.getConstant(0, DL, VT);
4774 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4775 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4779 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4780 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4781 N0.getOperand(0).getOpcode() == ISD::SRL &&
4782 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4784 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4785 uint64_t c2 = N1C->getZExtValue();
4786 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4787 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4788 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4789 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4790 if (c1 + OpSizeInBits == InnerShiftSize) {
4792 if (c1 + c2 >= InnerShiftSize)
4793 return DAG.getConstant(0, DL, VT);
4794 return DAG.getNode(ISD::TRUNCATE, DL, VT,
4795 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4796 N0.getOperand(0)->getOperand(0),
4797 DAG.getConstant(c1 + c2, DL,
4802 // fold (srl (shl x, c), c) -> (and x, cst2)
4803 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4804 unsigned BitSize = N0.getScalarValueSizeInBits();
4805 if (BitSize <= 64) {
4806 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4808 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4809 DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4813 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4814 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4815 // Shifting in all undef bits?
4816 EVT SmallVT = N0.getOperand(0).getValueType();
4817 unsigned BitSize = SmallVT.getScalarSizeInBits();
4818 if (N1C->getZExtValue() >= BitSize)
4819 return DAG.getUNDEF(VT);
4821 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4822 uint64_t ShiftAmt = N1C->getZExtValue();
4824 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4826 DAG.getConstant(ShiftAmt, DL0,
4827 getShiftAmountTy(SmallVT)));
4828 AddToWorklist(SmallShift.getNode());
4829 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4831 return DAG.getNode(ISD::AND, DL, VT,
4832 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4833 DAG.getConstant(Mask, DL, VT));
4837 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4838 // bit, which is unmodified by sra.
4839 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4840 if (N0.getOpcode() == ISD::SRA)
4841 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4844 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4845 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4846 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4847 APInt KnownZero, KnownOne;
4848 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4850 // If any of the input bits are KnownOne, then the input couldn't be all
4851 // zeros, thus the result of the srl will always be zero.
4852 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4854 // If all of the bits input the to ctlz node are known to be zero, then
4855 // the result of the ctlz is "32" and the result of the shift is one.
4856 APInt UnknownBits = ~KnownZero;
4857 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4859 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4860 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4861 // Okay, we know that only that the single bit specified by UnknownBits
4862 // could be set on input to the CTLZ node. If this bit is set, the SRL
4863 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4864 // to an SRL/XOR pair, which is likely to simplify more.
4865 unsigned ShAmt = UnknownBits.countTrailingZeros();
4866 SDValue Op = N0.getOperand(0);
4870 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4871 DAG.getConstant(ShAmt, DL,
4872 getShiftAmountTy(Op.getValueType())));
4873 AddToWorklist(Op.getNode());
4877 return DAG.getNode(ISD::XOR, DL, VT,
4878 Op, DAG.getConstant(1, DL, VT));
4882 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4883 if (N1.getOpcode() == ISD::TRUNCATE &&
4884 N1.getOperand(0).getOpcode() == ISD::AND) {
4885 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4886 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4889 // fold operands of srl based on knowledge that the low bits are not
4891 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4892 return SDValue(N, 0);
4894 if (N1C && !N1C->isOpaque())
4895 if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4898 // Attempt to convert a srl of a load into a narrower zero-extending load.
4899 if (SDValue NarrowLoad = ReduceLoadWidth(N))
4902 // Here is a common situation. We want to optimize:
4905 // %b = and i32 %a, 2
4906 // %c = srl i32 %b, 1
4907 // brcond i32 %c ...
4913 // %c = setcc eq %b, 0
4916 // However when after the source operand of SRL is optimized into AND, the SRL
4917 // itself may not be optimized further. Look for it and add the BRCOND into
4919 if (N->hasOneUse()) {
4920 SDNode *Use = *N->use_begin();
4921 if (Use->getOpcode() == ISD::BRCOND)
4923 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4924 // Also look pass the truncate.
4925 Use = *Use->use_begin();
4926 if (Use->getOpcode() == ISD::BRCOND)
4934 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4935 SDValue N0 = N->getOperand(0);
4936 EVT VT = N->getValueType(0);
4938 // fold (bswap c1) -> c2
4939 if (isConstantIntBuildVectorOrConstantInt(N0))
4940 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4941 // fold (bswap (bswap x)) -> x
4942 if (N0.getOpcode() == ISD::BSWAP)
4943 return N0->getOperand(0);
4947 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4948 SDValue N0 = N->getOperand(0);
4949 EVT VT = N->getValueType(0);
4951 // fold (ctlz c1) -> c2
4952 if (isConstantIntBuildVectorOrConstantInt(N0))
4953 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4957 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4958 SDValue N0 = N->getOperand(0);
4959 EVT VT = N->getValueType(0);
4961 // fold (ctlz_zero_undef c1) -> c2
4962 if (isConstantIntBuildVectorOrConstantInt(N0))
4963 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4967 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4968 SDValue N0 = N->getOperand(0);
4969 EVT VT = N->getValueType(0);
4971 // fold (cttz c1) -> c2
4972 if (isConstantIntBuildVectorOrConstantInt(N0))
4973 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4977 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4978 SDValue N0 = N->getOperand(0);
4979 EVT VT = N->getValueType(0);
4981 // fold (cttz_zero_undef c1) -> c2
4982 if (isConstantIntBuildVectorOrConstantInt(N0))
4983 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4987 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4988 SDValue N0 = N->getOperand(0);
4989 EVT VT = N->getValueType(0);
4991 // fold (ctpop c1) -> c2
4992 if (isConstantIntBuildVectorOrConstantInt(N0))
4993 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4998 /// \brief Generate Min/Max node
4999 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
5000 SDValue True, SDValue False,
5001 ISD::CondCode CC, const TargetLowering &TLI,
5002 SelectionDAG &DAG) {
5003 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
5013 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
5014 if (TLI.isOperationLegal(Opcode, VT))
5015 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5024 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
5025 if (TLI.isOperationLegal(Opcode, VT))
5026 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5034 SDValue DAGCombiner::visitSELECT(SDNode *N) {
5035 SDValue N0 = N->getOperand(0);
5036 SDValue N1 = N->getOperand(1);
5037 SDValue N2 = N->getOperand(2);
5038 EVT VT = N->getValueType(0);
5039 EVT VT0 = N0.getValueType();
5041 // fold (select C, X, X) -> X
5044 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
5045 // fold (select true, X, Y) -> X
5046 // fold (select false, X, Y) -> Y
5047 return !N0C->isNullValue() ? N1 : N2;
5049 // fold (select C, 1, X) -> (or C, X)
5050 if (VT == MVT::i1 && isOneConstant(N1))
5051 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5052 // fold (select C, 0, 1) -> (xor C, 1)
5053 // We can't do this reliably if integer based booleans have different contents
5054 // to floating point based booleans. This is because we can't tell whether we
5055 // have an integer-based boolean or a floating-point-based boolean unless we
5056 // can find the SETCC that produced it and inspect its operands. This is
5057 // fairly easy if C is the SETCC node, but it can potentially be
5058 // undiscoverable (or not reasonably discoverable). For example, it could be
5059 // in another basic block or it could require searching a complicated
5061 if (VT.isInteger() &&
5062 (VT0 == MVT::i1 || (VT0.isInteger() &&
5063 TLI.getBooleanContents(false, false) ==
5064 TLI.getBooleanContents(false, true) &&
5065 TLI.getBooleanContents(false, false) ==
5066 TargetLowering::ZeroOrOneBooleanContent)) &&
5067 isNullConstant(N1) && isOneConstant(N2)) {
5071 return DAG.getNode(ISD::XOR, DL, VT0,
5072 N0, DAG.getConstant(1, DL, VT0));
5075 XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
5076 N0, DAG.getConstant(1, DL0, VT0));
5077 AddToWorklist(XORNode.getNode());
5079 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
5080 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
5082 // fold (select C, 0, X) -> (and (not C), X)
5083 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
5084 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5085 AddToWorklist(NOTNode.getNode());
5086 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
5088 // fold (select C, X, 1) -> (or (not C), X)
5089 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
5090 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5091 AddToWorklist(NOTNode.getNode());
5092 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
5094 // fold (select C, X, 0) -> (and C, X)
5095 if (VT == MVT::i1 && isNullConstant(N2))
5096 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5097 // fold (select X, X, Y) -> (or X, Y)
5098 // fold (select X, 1, Y) -> (or X, Y)
5099 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5100 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5101 // fold (select X, Y, X) -> (and X, Y)
5102 // fold (select X, Y, 0) -> (and X, Y)
5103 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5104 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5106 // If we can fold this based on the true/false value, do so.
5107 if (SimplifySelectOps(N, N1, N2))
5108 return SDValue(N, 0); // Don't revisit N.
5110 if (VT0 == MVT::i1) {
5111 // The code in this block deals with the following 2 equivalences:
5112 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5113 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5114 // The target can specify its prefered form with the
5115 // shouldNormalizeToSelectSequence() callback. However we always transform
5116 // to the right anyway if we find the inner select exists in the DAG anyway
5117 // and we always transform to the left side if we know that we can further
5118 // optimize the combination of the conditions.
5119 bool normalizeToSequence
5120 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5121 // select (and Cond0, Cond1), X, Y
5122 // -> select Cond0, (select Cond1, X, Y), Y
5123 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5124 SDValue Cond0 = N0->getOperand(0);
5125 SDValue Cond1 = N0->getOperand(1);
5126 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5127 N1.getValueType(), Cond1, N1, N2);
5128 if (normalizeToSequence || !InnerSelect.use_empty())
5129 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5132 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5133 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5134 SDValue Cond0 = N0->getOperand(0);
5135 SDValue Cond1 = N0->getOperand(1);
5136 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5137 N1.getValueType(), Cond1, N1, N2);
5138 if (normalizeToSequence || !InnerSelect.use_empty())
5139 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5143 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5144 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5145 SDValue N1_0 = N1->getOperand(0);
5146 SDValue N1_1 = N1->getOperand(1);
5147 SDValue N1_2 = N1->getOperand(2);
5148 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5149 // Create the actual and node if we can generate good code for it.
5150 if (!normalizeToSequence) {
5151 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5153 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5156 // Otherwise see if we can optimize the "and" to a better pattern.
5157 if (SDValue Combined = visitANDLike(N0, N1_0, N))
5158 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5162 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5163 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5164 SDValue N2_0 = N2->getOperand(0);
5165 SDValue N2_1 = N2->getOperand(1);
5166 SDValue N2_2 = N2->getOperand(2);
5167 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5168 // Create the actual or node if we can generate good code for it.
5169 if (!normalizeToSequence) {
5170 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5172 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5175 // Otherwise see if we can optimize to a better pattern.
5176 if (SDValue Combined = visitORLike(N0, N2_0, N))
5177 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5183 // fold selects based on a setcc into other things, such as min/max/abs
5184 if (N0.getOpcode() == ISD::SETCC) {
5185 // select x, y (fcmp lt x, y) -> fminnum x, y
5186 // select x, y (fcmp gt x, y) -> fmaxnum x, y
5188 // This is OK if we don't care about what happens if either operand is a
5192 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5193 // no signed zeros as well as no nans.
5194 const TargetOptions &Options = DAG.getTarget().Options;
5195 if (Options.UnsafeFPMath &&
5196 VT.isFloatingPoint() && N0.hasOneUse() &&
5197 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5198 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5200 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5201 N0.getOperand(1), N1, N2, CC,
5206 if ((!LegalOperations &&
5207 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5208 TLI.isOperationLegal(ISD::SELECT_CC, VT))
5209 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5210 N0.getOperand(0), N0.getOperand(1),
5211 N1, N2, N0.getOperand(2));
5212 return SimplifySelect(SDLoc(N), N0, N1, N2);
5219 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5222 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5224 // Split the inputs.
5225 SDValue Lo, Hi, LL, LH, RL, RH;
5226 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5227 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5229 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5230 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5232 return std::make_pair(Lo, Hi);
5235 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5236 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5237 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5239 SDValue Cond = N->getOperand(0);
5240 SDValue LHS = N->getOperand(1);
5241 SDValue RHS = N->getOperand(2);
5242 EVT VT = N->getValueType(0);
5243 int NumElems = VT.getVectorNumElements();
5244 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5245 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5246 Cond.getOpcode() == ISD::BUILD_VECTOR);
5248 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5249 // binary ones here.
5250 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5253 // We're sure we have an even number of elements due to the
5254 // concat_vectors we have as arguments to vselect.
5255 // Skip BV elements until we find one that's not an UNDEF
5256 // After we find an UNDEF element, keep looping until we get to half the
5257 // length of the BV and see if all the non-undef nodes are the same.
5258 ConstantSDNode *BottomHalf = nullptr;
5259 for (int i = 0; i < NumElems / 2; ++i) {
5260 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5263 if (BottomHalf == nullptr)
5264 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5265 else if (Cond->getOperand(i).getNode() != BottomHalf)
5269 // Do the same for the second half of the BuildVector
5270 ConstantSDNode *TopHalf = nullptr;
5271 for (int i = NumElems / 2; i < NumElems; ++i) {
5272 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5275 if (TopHalf == nullptr)
5276 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5277 else if (Cond->getOperand(i).getNode() != TopHalf)
5281 assert(TopHalf && BottomHalf &&
5282 "One half of the selector was all UNDEFs and the other was all the "
5283 "same value. This should have been addressed before this function.");
5285 ISD::CONCAT_VECTORS, dl, VT,
5286 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5287 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5290 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5292 if (Level >= AfterLegalizeTypes)
5295 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5296 SDValue Mask = MSC->getMask();
5297 SDValue Data = MSC->getValue();
5300 // If the MSCATTER data type requires splitting and the mask is provided by a
5301 // SETCC, then split both nodes and its operands before legalization. This
5302 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5303 // and enables future optimizations (e.g. min/max pattern matching on X86).
5304 if (Mask.getOpcode() != ISD::SETCC)
5307 // Check if any splitting is required.
5308 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5309 TargetLowering::TypeSplitVector)
5311 SDValue MaskLo, MaskHi, Lo, Hi;
5312 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5315 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5317 SDValue Chain = MSC->getChain();
5319 EVT MemoryVT = MSC->getMemoryVT();
5320 unsigned Alignment = MSC->getOriginalAlignment();
5322 EVT LoMemVT, HiMemVT;
5323 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5325 SDValue DataLo, DataHi;
5326 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5328 SDValue BasePtr = MSC->getBasePtr();
5329 SDValue IndexLo, IndexHi;
5330 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5332 MachineMemOperand *MMO = DAG.getMachineFunction().
5333 getMachineMemOperand(MSC->getPointerInfo(),
5334 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5335 Alignment, MSC->getAAInfo(), MSC->getRanges());
5337 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5338 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5341 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5342 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5345 AddToWorklist(Lo.getNode());
5346 AddToWorklist(Hi.getNode());
5348 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5351 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5353 if (Level >= AfterLegalizeTypes)
5356 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5357 SDValue Mask = MST->getMask();
5358 SDValue Data = MST->getValue();
5361 // If the MSTORE data type requires splitting and the mask is provided by a
5362 // SETCC, then split both nodes and its operands before legalization. This
5363 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5364 // and enables future optimizations (e.g. min/max pattern matching on X86).
5365 if (Mask.getOpcode() == ISD::SETCC) {
5367 // Check if any splitting is required.
5368 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5369 TargetLowering::TypeSplitVector)
5372 SDValue MaskLo, MaskHi, Lo, Hi;
5373 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5376 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5378 SDValue Chain = MST->getChain();
5379 SDValue Ptr = MST->getBasePtr();
5381 EVT MemoryVT = MST->getMemoryVT();
5382 unsigned Alignment = MST->getOriginalAlignment();
5384 // if Alignment is equal to the vector size,
5385 // take the half of it for the second part
5386 unsigned SecondHalfAlignment =
5387 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5388 Alignment/2 : Alignment;
5390 EVT LoMemVT, HiMemVT;
5391 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5393 SDValue DataLo, DataHi;
5394 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5396 MachineMemOperand *MMO = DAG.getMachineFunction().
5397 getMachineMemOperand(MST->getPointerInfo(),
5398 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5399 Alignment, MST->getAAInfo(), MST->getRanges());
5401 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5402 MST->isTruncatingStore());
5404 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5405 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5406 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5408 MMO = DAG.getMachineFunction().
5409 getMachineMemOperand(MST->getPointerInfo(),
5410 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5411 SecondHalfAlignment, MST->getAAInfo(),
5414 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5415 MST->isTruncatingStore());
5417 AddToWorklist(Lo.getNode());
5418 AddToWorklist(Hi.getNode());
5420 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5425 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5427 if (Level >= AfterLegalizeTypes)
5430 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5431 SDValue Mask = MGT->getMask();
5434 // If the MGATHER result requires splitting and the mask is provided by a
5435 // SETCC, then split both nodes and its operands before legalization. This
5436 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5437 // and enables future optimizations (e.g. min/max pattern matching on X86).
5439 if (Mask.getOpcode() != ISD::SETCC)
5442 EVT VT = N->getValueType(0);
5444 // Check if any splitting is required.
5445 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5446 TargetLowering::TypeSplitVector)
5449 SDValue MaskLo, MaskHi, Lo, Hi;
5450 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5452 SDValue Src0 = MGT->getValue();
5453 SDValue Src0Lo, Src0Hi;
5454 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5457 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5459 SDValue Chain = MGT->getChain();
5460 EVT MemoryVT = MGT->getMemoryVT();
5461 unsigned Alignment = MGT->getOriginalAlignment();
5463 EVT LoMemVT, HiMemVT;
5464 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5466 SDValue BasePtr = MGT->getBasePtr();
5467 SDValue Index = MGT->getIndex();
5468 SDValue IndexLo, IndexHi;
5469 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5471 MachineMemOperand *MMO = DAG.getMachineFunction().
5472 getMachineMemOperand(MGT->getPointerInfo(),
5473 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5474 Alignment, MGT->getAAInfo(), MGT->getRanges());
5476 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5477 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5480 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5481 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5484 AddToWorklist(Lo.getNode());
5485 AddToWorklist(Hi.getNode());
5487 // Build a factor node to remember that this load is independent of the
5489 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5492 // Legalized the chain result - switch anything that used the old chain to
5494 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5496 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5498 SDValue RetOps[] = { GatherRes, Chain };
5499 return DAG.getMergeValues(RetOps, DL);
5502 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5504 if (Level >= AfterLegalizeTypes)
5507 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5508 SDValue Mask = MLD->getMask();
5511 // If the MLOAD result requires splitting and the mask is provided by a
5512 // SETCC, then split both nodes and its operands before legalization. This
5513 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5514 // and enables future optimizations (e.g. min/max pattern matching on X86).
5516 if (Mask.getOpcode() == ISD::SETCC) {
5517 EVT VT = N->getValueType(0);
5519 // Check if any splitting is required.
5520 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5521 TargetLowering::TypeSplitVector)
5524 SDValue MaskLo, MaskHi, Lo, Hi;
5525 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5527 SDValue Src0 = MLD->getSrc0();
5528 SDValue Src0Lo, Src0Hi;
5529 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5532 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5534 SDValue Chain = MLD->getChain();
5535 SDValue Ptr = MLD->getBasePtr();
5536 EVT MemoryVT = MLD->getMemoryVT();
5537 unsigned Alignment = MLD->getOriginalAlignment();
5539 // if Alignment is equal to the vector size,
5540 // take the half of it for the second part
5541 unsigned SecondHalfAlignment =
5542 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5543 Alignment/2 : Alignment;
5545 EVT LoMemVT, HiMemVT;
5546 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5548 MachineMemOperand *MMO = DAG.getMachineFunction().
5549 getMachineMemOperand(MLD->getPointerInfo(),
5550 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5551 Alignment, MLD->getAAInfo(), MLD->getRanges());
5553 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5556 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5557 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5558 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5560 MMO = DAG.getMachineFunction().
5561 getMachineMemOperand(MLD->getPointerInfo(),
5562 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5563 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5565 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5568 AddToWorklist(Lo.getNode());
5569 AddToWorklist(Hi.getNode());
5571 // Build a factor node to remember that this load is independent of the
5573 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5576 // Legalized the chain result - switch anything that used the old chain to
5578 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5580 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5582 SDValue RetOps[] = { LoadRes, Chain };
5583 return DAG.getMergeValues(RetOps, DL);
5588 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5589 SDValue N0 = N->getOperand(0);
5590 SDValue N1 = N->getOperand(1);
5591 SDValue N2 = N->getOperand(2);
5594 // Canonicalize integer abs.
5595 // vselect (setg[te] X, 0), X, -X ->
5596 // vselect (setgt X, -1), X, -X ->
5597 // vselect (setl[te] X, 0), -X, X ->
5598 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5599 if (N0.getOpcode() == ISD::SETCC) {
5600 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5601 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5603 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5605 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5606 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5607 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5608 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5609 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5610 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5611 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5614 EVT VT = LHS.getValueType();
5615 SDValue Shift = DAG.getNode(
5616 ISD::SRA, DL, VT, LHS,
5617 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5618 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5619 AddToWorklist(Shift.getNode());
5620 AddToWorklist(Add.getNode());
5621 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5625 if (SimplifySelectOps(N, N1, N2))
5626 return SDValue(N, 0); // Don't revisit N.
5628 // If the VSELECT result requires splitting and the mask is provided by a
5629 // SETCC, then split both nodes and its operands before legalization. This
5630 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5631 // and enables future optimizations (e.g. min/max pattern matching on X86).
5632 if (N0.getOpcode() == ISD::SETCC) {
5633 EVT VT = N->getValueType(0);
5635 // Check if any splitting is required.
5636 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5637 TargetLowering::TypeSplitVector)
5640 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5641 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5642 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5643 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5645 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5646 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5648 // Add the new VSELECT nodes to the work list in case they need to be split
5650 AddToWorklist(Lo.getNode());
5651 AddToWorklist(Hi.getNode());
5653 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5656 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5657 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5659 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5660 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5663 // The ConvertSelectToConcatVector function is assuming both the above
5664 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5666 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5667 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5668 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5669 if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5676 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5677 SDValue N0 = N->getOperand(0);
5678 SDValue N1 = N->getOperand(1);
5679 SDValue N2 = N->getOperand(2);
5680 SDValue N3 = N->getOperand(3);
5681 SDValue N4 = N->getOperand(4);
5682 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5684 // fold select_cc lhs, rhs, x, x, cc -> x
5688 // Determine if the condition we're dealing with is constant
5689 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5690 N0, N1, CC, SDLoc(N), false);
5691 if (SCC.getNode()) {
5692 AddToWorklist(SCC.getNode());
5694 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5695 if (!SCCC->isNullValue())
5696 return N2; // cond always true -> true val
5698 return N3; // cond always false -> false val
5699 } else if (SCC->getOpcode() == ISD::UNDEF) {
5700 // When the condition is UNDEF, just return the first operand. This is
5701 // coherent the DAG creation, no setcc node is created in this case
5703 } else if (SCC.getOpcode() == ISD::SETCC) {
5704 // Fold to a simpler select_cc
5705 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5706 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5711 // If we can fold this based on the true/false value, do so.
5712 if (SimplifySelectOps(N, N2, N3))
5713 return SDValue(N, 0); // Don't revisit N.
5715 // fold select_cc into other things, such as min/max/abs
5716 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5719 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5720 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5721 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5725 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
5726 SDValue LHS = N->getOperand(0);
5727 SDValue RHS = N->getOperand(1);
5728 SDValue Carry = N->getOperand(2);
5729 SDValue Cond = N->getOperand(3);
5731 // If Carry is false, fold to a regular SETCC.
5732 if (Carry.getOpcode() == ISD::CARRY_FALSE)
5733 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
5738 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5739 /// a build_vector of constants.
5740 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5741 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5742 /// Vector extends are not folded if operations are legal; this is to
5743 /// avoid introducing illegal build_vector dag nodes.
5744 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5745 SelectionDAG &DAG, bool LegalTypes,
5746 bool LegalOperations) {
5747 unsigned Opcode = N->getOpcode();
5748 SDValue N0 = N->getOperand(0);
5749 EVT VT = N->getValueType(0);
5751 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5752 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5753 && "Expected EXTEND dag node in input!");
5755 // fold (sext c1) -> c1
5756 // fold (zext c1) -> c1
5757 // fold (aext c1) -> c1
5758 if (isa<ConstantSDNode>(N0))
5759 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5761 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5762 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5763 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5764 EVT SVT = VT.getScalarType();
5765 if (!(VT.isVector() &&
5766 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5767 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5770 // We can fold this node into a build_vector.
5771 unsigned VTBits = SVT.getSizeInBits();
5772 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5773 SmallVector<SDValue, 8> Elts;
5774 unsigned NumElts = VT.getVectorNumElements();
5777 for (unsigned i=0; i != NumElts; ++i) {
5778 SDValue Op = N0->getOperand(i);
5779 if (Op->getOpcode() == ISD::UNDEF) {
5780 Elts.push_back(DAG.getUNDEF(SVT));
5785 // Get the constant value and if needed trunc it to the size of the type.
5786 // Nodes like build_vector might have constants wider than the scalar type.
5787 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5788 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5789 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5791 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5794 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5797 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5798 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5799 // transformation. Returns true if extension are possible and the above
5800 // mentioned transformation is profitable.
5801 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5803 SmallVectorImpl<SDNode *> &ExtendNodes,
5804 const TargetLowering &TLI) {
5805 bool HasCopyToRegUses = false;
5806 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5807 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5808 UE = N0.getNode()->use_end();
5813 if (UI.getUse().getResNo() != N0.getResNo())
5815 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5816 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5817 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5818 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5819 // Sign bits will be lost after a zext.
5822 for (unsigned i = 0; i != 2; ++i) {
5823 SDValue UseOp = User->getOperand(i);
5826 if (!isa<ConstantSDNode>(UseOp))
5831 ExtendNodes.push_back(User);
5834 // If truncates aren't free and there are users we can't
5835 // extend, it isn't worthwhile.
5838 // Remember if this value is live-out.
5839 if (User->getOpcode() == ISD::CopyToReg)
5840 HasCopyToRegUses = true;
5843 if (HasCopyToRegUses) {
5844 bool BothLiveOut = false;
5845 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5847 SDUse &Use = UI.getUse();
5848 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5854 // Both unextended and extended values are live out. There had better be
5855 // a good reason for the transformation.
5856 return ExtendNodes.size();
5861 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5862 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5863 ISD::NodeType ExtType) {
5864 // Extend SetCC uses if necessary.
5865 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5866 SDNode *SetCC = SetCCs[i];
5867 SmallVector<SDValue, 4> Ops;
5869 for (unsigned j = 0; j != 2; ++j) {
5870 SDValue SOp = SetCC->getOperand(j);
5872 Ops.push_back(ExtLoad);
5874 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5877 Ops.push_back(SetCC->getOperand(2));
5878 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5882 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5883 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5884 SDValue N0 = N->getOperand(0);
5885 EVT DstVT = N->getValueType(0);
5886 EVT SrcVT = N0.getValueType();
5888 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5889 N->getOpcode() == ISD::ZERO_EXTEND) &&
5890 "Unexpected node type (not an extend)!");
5892 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5893 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5894 // (v8i32 (sext (v8i16 (load x))))
5896 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5897 // (v4i32 (sextload (x + 16)))))
5898 // Where uses of the original load, i.e.:
5900 // are replaced with:
5902 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5903 // (v4i32 (sextload (x + 16)))))))
5905 // This combine is only applicable to illegal, but splittable, vectors.
5906 // All legal types, and illegal non-vector types, are handled elsewhere.
5907 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5909 if (N0->getOpcode() != ISD::LOAD)
5912 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5914 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5915 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5916 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5919 SmallVector<SDNode *, 4> SetCCs;
5920 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5923 ISD::LoadExtType ExtType =
5924 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5926 // Try to split the vector types to get down to legal types.
5927 EVT SplitSrcVT = SrcVT;
5928 EVT SplitDstVT = DstVT;
5929 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5930 SplitSrcVT.getVectorNumElements() > 1) {
5931 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5932 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5935 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5939 const unsigned NumSplits =
5940 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5941 const unsigned Stride = SplitSrcVT.getStoreSize();
5942 SmallVector<SDValue, 4> Loads;
5943 SmallVector<SDValue, 4> Chains;
5945 SDValue BasePtr = LN0->getBasePtr();
5946 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5947 const unsigned Offset = Idx * Stride;
5948 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5950 SDValue SplitLoad = DAG.getExtLoad(
5951 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5952 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5953 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5954 Align, LN0->getAAInfo());
5956 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5957 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5959 Loads.push_back(SplitLoad.getValue(0));
5960 Chains.push_back(SplitLoad.getValue(1));
5963 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5964 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5966 CombineTo(N, NewValue);
5968 // Replace uses of the original load (before extension)
5969 // with a truncate of the concatenated sextloaded vectors.
5971 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5972 CombineTo(N0.getNode(), Trunc, NewChain);
5973 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5974 (ISD::NodeType)N->getOpcode());
5975 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5978 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5979 SDValue N0 = N->getOperand(0);
5980 EVT VT = N->getValueType(0);
5982 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5984 return SDValue(Res, 0);
5986 // fold (sext (sext x)) -> (sext x)
5987 // fold (sext (aext x)) -> (sext x)
5988 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5989 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5992 if (N0.getOpcode() == ISD::TRUNCATE) {
5993 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5994 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5995 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
5996 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5997 if (NarrowLoad.getNode() != N0.getNode()) {
5998 CombineTo(N0.getNode(), NarrowLoad);
5999 // CombineTo deleted the truncate, if needed, but not what's under it.
6002 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6005 // See if the value being truncated is already sign extended. If so, just
6006 // eliminate the trunc/sext pair.
6007 SDValue Op = N0.getOperand(0);
6008 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
6009 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
6010 unsigned DestBits = VT.getScalarType().getSizeInBits();
6011 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
6013 if (OpBits == DestBits) {
6014 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
6015 // bits, it is already ready.
6016 if (NumSignBits > DestBits-MidBits)
6018 } else if (OpBits < DestBits) {
6019 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
6020 // bits, just sext from i32.
6021 if (NumSignBits > OpBits-MidBits)
6022 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
6024 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
6025 // bits, just truncate to i32.
6026 if (NumSignBits > OpBits-MidBits)
6027 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6030 // fold (sext (truncate x)) -> (sextinreg x).
6031 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
6032 N0.getValueType())) {
6033 if (OpBits < DestBits)
6034 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
6035 else if (OpBits > DestBits)
6036 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
6037 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
6038 DAG.getValueType(N0.getValueType()));
6042 // fold (sext (load x)) -> (sext (truncate (sextload x)))
6043 // Only generate vector extloads when 1) they're legal, and 2) they are
6044 // deemed desirable by the target.
6045 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6046 ((!LegalOperations && !VT.isVector() &&
6047 !cast<LoadSDNode>(N0)->isVolatile()) ||
6048 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
6049 bool DoXform = true;
6050 SmallVector<SDNode*, 4> SetCCs;
6051 if (!N0.hasOneUse())
6052 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
6054 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6056 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6057 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6059 LN0->getBasePtr(), N0.getValueType(),
6060 LN0->getMemOperand());
6061 CombineTo(N, ExtLoad);
6062 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6063 N0.getValueType(), ExtLoad);
6064 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6065 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6067 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6071 // fold (sext (load x)) to multiple smaller sextloads.
6072 // Only on illegal but splittable vectors.
6073 if (SDValue ExtLoad = CombineExtLoad(N))
6076 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6077 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6078 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6079 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6080 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6081 EVT MemVT = LN0->getMemoryVT();
6082 if ((!LegalOperations && !LN0->isVolatile()) ||
6083 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6084 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6086 LN0->getBasePtr(), MemVT,
6087 LN0->getMemOperand());
6088 CombineTo(N, ExtLoad);
6089 CombineTo(N0.getNode(),
6090 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6091 N0.getValueType(), ExtLoad),
6092 ExtLoad.getValue(1));
6093 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6097 // fold (sext (and/or/xor (load x), cst)) ->
6098 // (and/or/xor (sextload x), (sext cst))
6099 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6100 N0.getOpcode() == ISD::XOR) &&
6101 isa<LoadSDNode>(N0.getOperand(0)) &&
6102 N0.getOperand(1).getOpcode() == ISD::Constant &&
6103 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
6104 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6105 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6106 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
6107 bool DoXform = true;
6108 SmallVector<SDNode*, 4> SetCCs;
6109 if (!N0.hasOneUse())
6110 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6113 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6114 LN0->getChain(), LN0->getBasePtr(),
6116 LN0->getMemOperand());
6117 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6118 Mask = Mask.sext(VT.getSizeInBits());
6120 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6121 ExtLoad, DAG.getConstant(Mask, DL, VT));
6122 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6123 SDLoc(N0.getOperand(0)),
6124 N0.getOperand(0).getValueType(), ExtLoad);
6126 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6127 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6129 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6134 if (N0.getOpcode() == ISD::SETCC) {
6135 EVT N0VT = N0.getOperand(0).getValueType();
6136 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6137 // Only do this before legalize for now.
6138 if (VT.isVector() && !LegalOperations &&
6139 TLI.getBooleanContents(N0VT) ==
6140 TargetLowering::ZeroOrNegativeOneBooleanContent) {
6141 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6142 // of the same size as the compared operands. Only optimize sext(setcc())
6143 // if this is the case.
6144 EVT SVT = getSetCCResultType(N0VT);
6146 // We know that the # elements of the results is the same as the
6147 // # elements of the compare (and the # elements of the compare result
6148 // for that matter). Check to see that they are the same size. If so,
6149 // we know that the element size of the sext'd result matches the
6150 // element size of the compare operands.
6151 if (VT.getSizeInBits() == SVT.getSizeInBits())
6152 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6154 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6156 // If the desired elements are smaller or larger than the source
6157 // elements we can use a matching integer vector type and then
6158 // truncate/sign extend
6159 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6160 if (SVT == MatchingVectorType) {
6161 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6162 N0.getOperand(0), N0.getOperand(1),
6163 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6164 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6168 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6169 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6172 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6174 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6175 NegOne, DAG.getConstant(0, DL, VT),
6176 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6177 if (SCC.getNode()) return SCC;
6179 if (!VT.isVector()) {
6180 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6181 if (!LegalOperations ||
6182 TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6184 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6185 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6186 N0.getOperand(0), N0.getOperand(1), CC);
6187 return DAG.getSelect(DL, VT, SetCC,
6188 NegOne, DAG.getConstant(0, DL, VT));
6193 // fold (sext x) -> (zext x) if the sign bit is known zero.
6194 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6195 DAG.SignBitIsZero(N0))
6196 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6201 // isTruncateOf - If N is a truncate of some other value, return true, record
6202 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6203 // This function computes KnownZero to avoid a duplicated call to
6204 // computeKnownBits in the caller.
6205 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6208 if (N->getOpcode() == ISD::TRUNCATE) {
6209 Op = N->getOperand(0);
6210 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6214 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6215 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6218 SDValue Op0 = N->getOperand(0);
6219 SDValue Op1 = N->getOperand(1);
6220 assert(Op0.getValueType() == Op1.getValueType());
6222 if (isNullConstant(Op0))
6224 else if (isNullConstant(Op1))
6229 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6231 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6237 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6238 SDValue N0 = N->getOperand(0);
6239 EVT VT = N->getValueType(0);
6241 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6243 return SDValue(Res, 0);
6245 // fold (zext (zext x)) -> (zext x)
6246 // fold (zext (aext x)) -> (zext x)
6247 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6248 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6251 // fold (zext (truncate x)) -> (zext x) or
6252 // (zext (truncate x)) -> (truncate x)
6253 // This is valid when the truncated bits of x are already zero.
6254 // FIXME: We should extend this to work for vectors too.
6257 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6258 APInt TruncatedBits =
6259 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6260 APInt(Op.getValueSizeInBits(), 0) :
6261 APInt::getBitsSet(Op.getValueSizeInBits(),
6262 N0.getValueSizeInBits(),
6263 std::min(Op.getValueSizeInBits(),
6264 VT.getSizeInBits()));
6265 if (TruncatedBits == (KnownZero & TruncatedBits)) {
6266 if (VT.bitsGT(Op.getValueType()))
6267 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6268 if (VT.bitsLT(Op.getValueType()))
6269 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6275 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6276 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6277 if (N0.getOpcode() == ISD::TRUNCATE) {
6278 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6279 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6280 if (NarrowLoad.getNode() != N0.getNode()) {
6281 CombineTo(N0.getNode(), NarrowLoad);
6282 // CombineTo deleted the truncate, if needed, but not what's under it.
6285 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6289 // fold (zext (truncate x)) -> (and x, mask)
6290 if (N0.getOpcode() == ISD::TRUNCATE) {
6291 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6292 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6293 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6294 SDNode *oye = N0.getNode()->getOperand(0).getNode();
6295 if (NarrowLoad.getNode() != N0.getNode()) {
6296 CombineTo(N0.getNode(), NarrowLoad);
6297 // CombineTo deleted the truncate, if needed, but not what's under it.
6300 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6303 EVT SrcVT = N0.getOperand(0).getValueType();
6304 EVT MinVT = N0.getValueType();
6306 // Try to mask before the extension to avoid having to generate a larger mask,
6307 // possibly over several sub-vectors.
6308 if (SrcVT.bitsLT(VT)) {
6309 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6310 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6311 SDValue Op = N0.getOperand(0);
6312 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6313 AddToWorklist(Op.getNode());
6314 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6318 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6319 SDValue Op = N0.getOperand(0);
6320 if (SrcVT.bitsLT(VT)) {
6321 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6322 AddToWorklist(Op.getNode());
6323 } else if (SrcVT.bitsGT(VT)) {
6324 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6325 AddToWorklist(Op.getNode());
6327 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6331 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6332 // if either of the casts is not free.
6333 if (N0.getOpcode() == ISD::AND &&
6334 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6335 N0.getOperand(1).getOpcode() == ISD::Constant &&
6336 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6337 N0.getValueType()) ||
6338 !TLI.isZExtFree(N0.getValueType(), VT))) {
6339 SDValue X = N0.getOperand(0).getOperand(0);
6340 if (X.getValueType().bitsLT(VT)) {
6341 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6342 } else if (X.getValueType().bitsGT(VT)) {
6343 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6345 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6346 Mask = Mask.zext(VT.getSizeInBits());
6348 return DAG.getNode(ISD::AND, DL, VT,
6349 X, DAG.getConstant(Mask, DL, VT));
6352 // fold (zext (load x)) -> (zext (truncate (zextload x)))
6353 // Only generate vector extloads when 1) they're legal, and 2) they are
6354 // deemed desirable by the target.
6355 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6356 ((!LegalOperations && !VT.isVector() &&
6357 !cast<LoadSDNode>(N0)->isVolatile()) ||
6358 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6359 bool DoXform = true;
6360 SmallVector<SDNode*, 4> SetCCs;
6361 if (!N0.hasOneUse())
6362 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6364 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6366 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6367 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6369 LN0->getBasePtr(), N0.getValueType(),
6370 LN0->getMemOperand());
6371 CombineTo(N, ExtLoad);
6372 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6373 N0.getValueType(), ExtLoad);
6374 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6376 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6378 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6382 // fold (zext (load x)) to multiple smaller zextloads.
6383 // Only on illegal but splittable vectors.
6384 if (SDValue ExtLoad = CombineExtLoad(N))
6387 // fold (zext (and/or/xor (load x), cst)) ->
6388 // (and/or/xor (zextload x), (zext cst))
6389 // Unless (and (load x) cst) will match as a zextload already and has
6390 // additional users.
6391 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6392 N0.getOpcode() == ISD::XOR) &&
6393 isa<LoadSDNode>(N0.getOperand(0)) &&
6394 N0.getOperand(1).getOpcode() == ISD::Constant &&
6395 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6396 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6397 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6398 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6399 bool DoXform = true;
6400 SmallVector<SDNode*, 4> SetCCs;
6401 if (!N0.hasOneUse()) {
6402 if (N0.getOpcode() == ISD::AND) {
6403 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
6404 auto NarrowLoad = false;
6405 EVT LoadResultTy = AndC->getValueType(0);
6406 EVT ExtVT, LoadedVT;
6407 if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
6412 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
6413 ISD::ZERO_EXTEND, SetCCs, TLI);
6416 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6417 LN0->getChain(), LN0->getBasePtr(),
6419 LN0->getMemOperand());
6420 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6421 Mask = Mask.zext(VT.getSizeInBits());
6423 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6424 ExtLoad, DAG.getConstant(Mask, DL, VT));
6425 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6426 SDLoc(N0.getOperand(0)),
6427 N0.getOperand(0).getValueType(), ExtLoad);
6429 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6430 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6432 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6437 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6438 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6439 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6440 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6441 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6442 EVT MemVT = LN0->getMemoryVT();
6443 if ((!LegalOperations && !LN0->isVolatile()) ||
6444 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6445 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6447 LN0->getBasePtr(), MemVT,
6448 LN0->getMemOperand());
6449 CombineTo(N, ExtLoad);
6450 CombineTo(N0.getNode(),
6451 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6453 ExtLoad.getValue(1));
6454 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6458 if (N0.getOpcode() == ISD::SETCC) {
6459 if (!LegalOperations && VT.isVector() &&
6460 N0.getValueType().getVectorElementType() == MVT::i1) {
6461 EVT N0VT = N0.getOperand(0).getValueType();
6462 if (getSetCCResultType(N0VT) == N0.getValueType())
6465 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6466 // Only do this before legalize for now.
6467 EVT EltVT = VT.getVectorElementType();
6469 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6470 DAG.getConstant(1, DL, EltVT));
6471 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6472 // We know that the # elements of the results is the same as the
6473 // # elements of the compare (and the # elements of the compare result
6474 // for that matter). Check to see that they are the same size. If so,
6475 // we know that the element size of the sext'd result matches the
6476 // element size of the compare operands.
6477 return DAG.getNode(ISD::AND, DL, VT,
6478 DAG.getSetCC(DL, VT, N0.getOperand(0),
6480 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6481 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6484 // If the desired elements are smaller or larger than the source
6485 // elements we can use a matching integer vector type and then
6486 // truncate/sign extend
6487 EVT MatchingElementType =
6488 EVT::getIntegerVT(*DAG.getContext(),
6489 N0VT.getScalarType().getSizeInBits());
6490 EVT MatchingVectorType =
6491 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6492 N0VT.getVectorNumElements());
6494 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6496 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6497 return DAG.getNode(ISD::AND, DL, VT,
6498 DAG.getSExtOrTrunc(VsetCC, DL, VT),
6499 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6502 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6505 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6506 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6507 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6508 if (SCC.getNode()) return SCC;
6511 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6512 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6513 isa<ConstantSDNode>(N0.getOperand(1)) &&
6514 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6516 SDValue ShAmt = N0.getOperand(1);
6517 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6518 if (N0.getOpcode() == ISD::SHL) {
6519 SDValue InnerZExt = N0.getOperand(0);
6520 // If the original shl may be shifting out bits, do not perform this
6522 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6523 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6524 if (ShAmtVal > KnownZeroBits)
6530 // Ensure that the shift amount is wide enough for the shifted value.
6531 if (VT.getSizeInBits() >= 256)
6532 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6534 return DAG.getNode(N0.getOpcode(), DL, VT,
6535 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6542 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6543 SDValue N0 = N->getOperand(0);
6544 EVT VT = N->getValueType(0);
6546 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6548 return SDValue(Res, 0);
6550 // fold (aext (aext x)) -> (aext x)
6551 // fold (aext (zext x)) -> (zext x)
6552 // fold (aext (sext x)) -> (sext x)
6553 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6554 N0.getOpcode() == ISD::ZERO_EXTEND ||
6555 N0.getOpcode() == ISD::SIGN_EXTEND)
6556 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6558 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6559 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6560 if (N0.getOpcode() == ISD::TRUNCATE) {
6561 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6562 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6563 if (NarrowLoad.getNode() != N0.getNode()) {
6564 CombineTo(N0.getNode(), NarrowLoad);
6565 // CombineTo deleted the truncate, if needed, but not what's under it.
6568 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6572 // fold (aext (truncate x))
6573 if (N0.getOpcode() == ISD::TRUNCATE) {
6574 SDValue TruncOp = N0.getOperand(0);
6575 if (TruncOp.getValueType() == VT)
6576 return TruncOp; // x iff x size == zext size.
6577 if (TruncOp.getValueType().bitsGT(VT))
6578 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6579 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6582 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6583 // if the trunc is not free.
6584 if (N0.getOpcode() == ISD::AND &&
6585 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6586 N0.getOperand(1).getOpcode() == ISD::Constant &&
6587 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6588 N0.getValueType())) {
6589 SDValue X = N0.getOperand(0).getOperand(0);
6590 if (X.getValueType().bitsLT(VT)) {
6591 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6592 } else if (X.getValueType().bitsGT(VT)) {
6593 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6595 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6596 Mask = Mask.zext(VT.getSizeInBits());
6598 return DAG.getNode(ISD::AND, DL, VT,
6599 X, DAG.getConstant(Mask, DL, VT));
6602 // fold (aext (load x)) -> (aext (truncate (extload x)))
6603 // None of the supported targets knows how to perform load and any_ext
6604 // on vectors in one instruction. We only perform this transformation on
6606 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6607 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6608 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6609 bool DoXform = true;
6610 SmallVector<SDNode*, 4> SetCCs;
6611 if (!N0.hasOneUse())
6612 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6614 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6615 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6617 LN0->getBasePtr(), N0.getValueType(),
6618 LN0->getMemOperand());
6619 CombineTo(N, ExtLoad);
6620 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6621 N0.getValueType(), ExtLoad);
6622 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6623 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6625 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6629 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6630 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6631 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6632 if (N0.getOpcode() == ISD::LOAD &&
6633 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6635 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6636 ISD::LoadExtType ExtType = LN0->getExtensionType();
6637 EVT MemVT = LN0->getMemoryVT();
6638 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6639 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6640 VT, LN0->getChain(), LN0->getBasePtr(),
6641 MemVT, LN0->getMemOperand());
6642 CombineTo(N, ExtLoad);
6643 CombineTo(N0.getNode(),
6644 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6645 N0.getValueType(), ExtLoad),
6646 ExtLoad.getValue(1));
6647 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6651 if (N0.getOpcode() == ISD::SETCC) {
6653 // aext(setcc) -> vsetcc
6654 // aext(setcc) -> truncate(vsetcc)
6655 // aext(setcc) -> aext(vsetcc)
6656 // Only do this before legalize for now.
6657 if (VT.isVector() && !LegalOperations) {
6658 EVT N0VT = N0.getOperand(0).getValueType();
6659 // We know that the # elements of the results is the same as the
6660 // # elements of the compare (and the # elements of the compare result
6661 // for that matter). Check to see that they are the same size. If so,
6662 // we know that the element size of the sext'd result matches the
6663 // element size of the compare operands.
6664 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6665 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6667 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6668 // If the desired elements are smaller or larger than the source
6669 // elements we can use a matching integer vector type and then
6670 // truncate/any extend
6672 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6674 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6676 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6677 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6681 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6684 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6685 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6686 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6694 /// See if the specified operand can be simplified with the knowledge that only
6695 /// the bits specified by Mask are used. If so, return the simpler operand,
6696 /// otherwise return a null SDValue.
6697 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6698 switch (V.getOpcode()) {
6700 case ISD::Constant: {
6701 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6702 assert(CV && "Const value should be ConstSDNode.");
6703 const APInt &CVal = CV->getAPIntValue();
6704 APInt NewVal = CVal & Mask;
6706 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6711 // If the LHS or RHS don't contribute bits to the or, drop them.
6712 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6713 return V.getOperand(1);
6714 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6715 return V.getOperand(0);
6718 // Only look at single-use SRLs.
6719 if (!V.getNode()->hasOneUse())
6721 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6722 // See if we can recursively simplify the LHS.
6723 unsigned Amt = RHSC->getZExtValue();
6725 // Watch out for shift count overflow though.
6726 if (Amt >= Mask.getBitWidth()) break;
6727 APInt NewMask = Mask << Amt;
6728 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6729 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6730 SimplifyLHS, V.getOperand(1));
6736 /// If the result of a wider load is shifted to right of N bits and then
6737 /// truncated to a narrower type and where N is a multiple of number of bits of
6738 /// the narrower type, transform it to a narrower load from address + N / num of
6739 /// bits of new type. If the result is to be extended, also fold the extension
6740 /// to form a extending load.
6741 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6742 unsigned Opc = N->getOpcode();
6744 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6745 SDValue N0 = N->getOperand(0);
6746 EVT VT = N->getValueType(0);
6749 // This transformation isn't valid for vector loads.
6753 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6755 if (Opc == ISD::SIGN_EXTEND_INREG) {
6756 ExtType = ISD::SEXTLOAD;
6757 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6758 } else if (Opc == ISD::SRL) {
6759 // Another special-case: SRL is basically zero-extending a narrower value.
6760 ExtType = ISD::ZEXTLOAD;
6762 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6763 if (!N01) return SDValue();
6764 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6765 VT.getSizeInBits() - N01->getZExtValue());
6767 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6770 unsigned EVTBits = ExtVT.getSizeInBits();
6772 // Do not generate loads of non-round integer types since these can
6773 // be expensive (and would be wrong if the type is not byte sized).
6774 if (!ExtVT.isRound())
6778 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6779 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6780 ShAmt = N01->getZExtValue();
6781 // Is the shift amount a multiple of size of VT?
6782 if ((ShAmt & (EVTBits-1)) == 0) {
6783 N0 = N0.getOperand(0);
6784 // Is the load width a multiple of size of VT?
6785 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6789 // At this point, we must have a load or else we can't do the transform.
6790 if (!isa<LoadSDNode>(N0)) return SDValue();
6792 // Because a SRL must be assumed to *need* to zero-extend the high bits
6793 // (as opposed to anyext the high bits), we can't combine the zextload
6794 // lowering of SRL and an sextload.
6795 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6798 // If the shift amount is larger than the input type then we're not
6799 // accessing any of the loaded bytes. If the load was a zextload/extload
6800 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6801 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6806 // If the load is shifted left (and the result isn't shifted back right),
6807 // we can fold the truncate through the shift.
6808 unsigned ShLeftAmt = 0;
6809 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6810 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6811 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6812 ShLeftAmt = N01->getZExtValue();
6813 N0 = N0.getOperand(0);
6817 // If we haven't found a load, we can't narrow it. Don't transform one with
6818 // multiple uses, this would require adding a new load.
6819 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6822 // Don't change the width of a volatile load.
6823 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6824 if (LN0->isVolatile())
6827 // Verify that we are actually reducing a load width here.
6828 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6831 // For the transform to be legal, the load must produce only two values
6832 // (the value loaded and the chain). Don't transform a pre-increment
6833 // load, for example, which produces an extra value. Otherwise the
6834 // transformation is not equivalent, and the downstream logic to replace
6835 // uses gets things wrong.
6836 if (LN0->getNumValues() > 2)
6839 // If the load that we're shrinking is an extload and we're not just
6840 // discarding the extension we can't simply shrink the load. Bail.
6841 // TODO: It would be possible to merge the extensions in some cases.
6842 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6843 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6846 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6849 EVT PtrType = N0.getOperand(1).getValueType();
6851 if (PtrType == MVT::Untyped || PtrType.isExtended())
6852 // It's not possible to generate a constant of extended or untyped type.
6855 // For big endian targets, we need to adjust the offset to the pointer to
6856 // load the correct bytes.
6857 if (DAG.getDataLayout().isBigEndian()) {
6858 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6859 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6860 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6863 uint64_t PtrOff = ShAmt / 8;
6864 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6866 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6867 PtrType, LN0->getBasePtr(),
6868 DAG.getConstant(PtrOff, DL, PtrType));
6869 AddToWorklist(NewPtr.getNode());
6872 if (ExtType == ISD::NON_EXTLOAD)
6873 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6874 LN0->getPointerInfo().getWithOffset(PtrOff),
6875 LN0->isVolatile(), LN0->isNonTemporal(),
6876 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6878 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6879 LN0->getPointerInfo().getWithOffset(PtrOff),
6880 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6881 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6883 // Replace the old load's chain with the new load's chain.
6884 WorklistRemover DeadNodes(*this);
6885 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6887 // Shift the result left, if we've swallowed a left shift.
6888 SDValue Result = Load;
6889 if (ShLeftAmt != 0) {
6890 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6891 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6893 // If the shift amount is as large as the result size (but, presumably,
6894 // no larger than the source) then the useful bits of the result are
6895 // zero; we can't simply return the shortened shift, because the result
6896 // of that operation is undefined.
6898 if (ShLeftAmt >= VT.getSizeInBits())
6899 Result = DAG.getConstant(0, DL, VT);
6901 Result = DAG.getNode(ISD::SHL, DL, VT,
6902 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6905 // Return the new loaded value.
6909 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6910 SDValue N0 = N->getOperand(0);
6911 SDValue N1 = N->getOperand(1);
6912 EVT VT = N->getValueType(0);
6913 EVT EVT = cast<VTSDNode>(N1)->getVT();
6914 unsigned VTBits = VT.getScalarType().getSizeInBits();
6915 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6918 return DAG.getUNDEF(VT);
6920 // fold (sext_in_reg c1) -> c1
6921 if (isConstantIntBuildVectorOrConstantInt(N0))
6922 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6924 // If the input is already sign extended, just drop the extension.
6925 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6928 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6929 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6930 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6931 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6932 N0.getOperand(0), N1);
6934 // fold (sext_in_reg (sext x)) -> (sext x)
6935 // fold (sext_in_reg (aext x)) -> (sext x)
6936 // if x is small enough.
6937 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6938 SDValue N00 = N0.getOperand(0);
6939 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6940 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6941 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6944 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6945 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6946 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6948 // fold operands of sext_in_reg based on knowledge that the top bits are not
6950 if (SimplifyDemandedBits(SDValue(N, 0)))
6951 return SDValue(N, 0);
6953 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6954 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6955 if (SDValue NarrowLoad = ReduceLoadWidth(N))
6958 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6959 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6960 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6961 if (N0.getOpcode() == ISD::SRL) {
6962 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6963 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6964 // We can turn this into an SRA iff the input to the SRL is already sign
6966 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6967 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6968 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6969 N0.getOperand(0), N0.getOperand(1));
6973 // fold (sext_inreg (extload x)) -> (sextload x)
6974 if (ISD::isEXTLoad(N0.getNode()) &&
6975 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6976 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6977 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6978 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6979 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6980 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6982 LN0->getBasePtr(), EVT,
6983 LN0->getMemOperand());
6984 CombineTo(N, ExtLoad);
6985 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6986 AddToWorklist(ExtLoad.getNode());
6987 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6989 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6990 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6992 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6993 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6994 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6995 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6996 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6998 LN0->getBasePtr(), EVT,
6999 LN0->getMemOperand());
7000 CombineTo(N, ExtLoad);
7001 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7002 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7005 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
7006 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
7007 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
7008 N0.getOperand(1), false);
7009 if (BSwap.getNode())
7010 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7017 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
7018 SDValue N0 = N->getOperand(0);
7019 EVT VT = N->getValueType(0);
7021 if (N0.getOpcode() == ISD::UNDEF)
7022 return DAG.getUNDEF(VT);
7024 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7026 return SDValue(Res, 0);
7031 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
7032 SDValue N0 = N->getOperand(0);
7033 EVT VT = N->getValueType(0);
7034 bool isLE = DAG.getDataLayout().isLittleEndian();
7037 if (N0.getValueType() == N->getValueType(0))
7039 // fold (truncate c1) -> c1
7040 if (isConstantIntBuildVectorOrConstantInt(N0))
7041 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
7042 // fold (truncate (truncate x)) -> (truncate x)
7043 if (N0.getOpcode() == ISD::TRUNCATE)
7044 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7045 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
7046 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
7047 N0.getOpcode() == ISD::SIGN_EXTEND ||
7048 N0.getOpcode() == ISD::ANY_EXTEND) {
7049 if (N0.getOperand(0).getValueType().bitsLT(VT))
7050 // if the source is smaller than the dest, we still need an extend
7051 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
7053 if (N0.getOperand(0).getValueType().bitsGT(VT))
7054 // if the source is larger than the dest, than we just need the truncate
7055 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7056 // if the source and dest are the same type, we can drop both the extend
7057 // and the truncate.
7058 return N0.getOperand(0);
7061 // Fold extract-and-trunc into a narrow extract. For example:
7062 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
7063 // i32 y = TRUNCATE(i64 x)
7065 // v16i8 b = BITCAST (v2i64 val)
7066 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
7068 // Note: We only run this optimization after type legalization (which often
7069 // creates this pattern) and before operation legalization after which
7070 // we need to be more careful about the vector instructions that we generate.
7071 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7072 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
7074 EVT VecTy = N0.getOperand(0).getValueType();
7075 EVT ExTy = N0.getValueType();
7076 EVT TrTy = N->getValueType(0);
7078 unsigned NumElem = VecTy.getVectorNumElements();
7079 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
7081 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
7082 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
7084 SDValue EltNo = N0->getOperand(1);
7085 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
7086 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7087 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7088 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
7090 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
7091 NVT, N0.getOperand(0));
7094 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
7096 DAG.getConstant(Index, DL, IndexTy));
7100 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
7101 if (N0.getOpcode() == ISD::SELECT) {
7102 EVT SrcVT = N0.getValueType();
7103 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
7104 TLI.isTruncateFree(SrcVT, VT)) {
7106 SDValue Cond = N0.getOperand(0);
7107 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7108 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7109 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7113 // Fold a series of buildvector, bitcast, and truncate if possible.
7115 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7116 // (2xi32 (buildvector x, y)).
7117 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7118 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7119 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7120 N0.getOperand(0).hasOneUse()) {
7122 SDValue BuildVect = N0.getOperand(0);
7123 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7124 EVT TruncVecEltTy = VT.getVectorElementType();
7126 // Check that the element types match.
7127 if (BuildVectEltTy == TruncVecEltTy) {
7128 // Now we only need to compute the offset of the truncated elements.
7129 unsigned BuildVecNumElts = BuildVect.getNumOperands();
7130 unsigned TruncVecNumElts = VT.getVectorNumElements();
7131 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7133 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7134 "Invalid number of elements");
7136 SmallVector<SDValue, 8> Opnds;
7137 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7138 Opnds.push_back(BuildVect.getOperand(i));
7140 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
7144 // See if we can simplify the input to this truncate through knowledge that
7145 // only the low bits are being used.
7146 // For example "trunc (or (shl x, 8), y)" // -> trunc y
7147 // Currently we only perform this optimization on scalars because vectors
7148 // may have different active low bits.
7149 if (!VT.isVector()) {
7151 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7152 VT.getSizeInBits()));
7153 if (Shorter.getNode())
7154 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7156 // fold (truncate (load x)) -> (smaller load x)
7157 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7158 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7159 if (SDValue Reduced = ReduceLoadWidth(N))
7162 // Handle the case where the load remains an extending load even
7163 // after truncation.
7164 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7165 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7166 if (!LN0->isVolatile() &&
7167 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7168 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7169 VT, LN0->getChain(), LN0->getBasePtr(),
7171 LN0->getMemOperand());
7172 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7177 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7178 // where ... are all 'undef'.
7179 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7180 SmallVector<EVT, 8> VTs;
7183 unsigned NumDefs = 0;
7185 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7186 SDValue X = N0.getOperand(i);
7187 if (X.getOpcode() != ISD::UNDEF) {
7192 // Stop if more than one members are non-undef.
7195 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7196 VT.getVectorElementType(),
7197 X.getValueType().getVectorNumElements()));
7201 return DAG.getUNDEF(VT);
7204 assert(V.getNode() && "The single defined operand is empty!");
7205 SmallVector<SDValue, 8> Opnds;
7206 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7208 Opnds.push_back(DAG.getUNDEF(VTs[i]));
7211 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7212 AddToWorklist(NV.getNode());
7213 Opnds.push_back(NV);
7215 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7219 // Simplify the operands using demanded-bits information.
7220 if (!VT.isVector() &&
7221 SimplifyDemandedBits(SDValue(N, 0)))
7222 return SDValue(N, 0);
7227 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7228 SDValue Elt = N->getOperand(i);
7229 if (Elt.getOpcode() != ISD::MERGE_VALUES)
7230 return Elt.getNode();
7231 return Elt.getOperand(Elt.getResNo()).getNode();
7234 /// build_pair (load, load) -> load
7235 /// if load locations are consecutive.
7236 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7237 assert(N->getOpcode() == ISD::BUILD_PAIR);
7239 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7240 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7241 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7242 LD1->getAddressSpace() != LD2->getAddressSpace())
7244 EVT LD1VT = LD1->getValueType(0);
7246 if (ISD::isNON_EXTLoad(LD2) &&
7248 // If both are volatile this would reduce the number of volatile loads.
7249 // If one is volatile it might be ok, but play conservative and bail out.
7250 !LD1->isVolatile() &&
7251 !LD2->isVolatile() &&
7252 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7253 unsigned Align = LD1->getAlignment();
7254 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7255 VT.getTypeForEVT(*DAG.getContext()));
7257 if (NewAlign <= Align &&
7258 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7259 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7260 LD1->getBasePtr(), LD1->getPointerInfo(),
7261 false, false, false, Align);
7267 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7268 SDValue N0 = N->getOperand(0);
7269 EVT VT = N->getValueType(0);
7271 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7272 // Only do this before legalize, since afterward the target may be depending
7273 // on the bitconvert.
7274 // First check to see if this is all constant.
7276 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7278 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7280 EVT DestEltVT = N->getValueType(0).getVectorElementType();
7281 assert(!DestEltVT.isVector() &&
7282 "Element type of vector ValueType must not be vector!");
7284 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7287 // If the input is a constant, let getNode fold it.
7288 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7289 // If we can't allow illegal operations, we need to check that this is just
7290 // a fp -> int or int -> conversion and that the resulting operation will
7292 if (!LegalOperations ||
7293 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7294 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7295 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7296 TLI.isOperationLegal(ISD::Constant, VT)))
7297 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7300 // (conv (conv x, t1), t2) -> (conv x, t2)
7301 if (N0.getOpcode() == ISD::BITCAST)
7302 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7305 // fold (conv (load x)) -> (load (conv*)x)
7306 // If the resultant load doesn't need a higher alignment than the original!
7307 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7308 // Do not change the width of a volatile load.
7309 !cast<LoadSDNode>(N0)->isVolatile() &&
7310 // Do not remove the cast if the types differ in endian layout.
7311 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7312 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7313 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7314 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7315 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7316 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7317 VT.getTypeForEVT(*DAG.getContext()));
7318 unsigned OrigAlign = LN0->getAlignment();
7320 if (Align <= OrigAlign) {
7321 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7322 LN0->getBasePtr(), LN0->getPointerInfo(),
7323 LN0->isVolatile(), LN0->isNonTemporal(),
7324 LN0->isInvariant(), OrigAlign,
7326 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7331 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7332 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7333 // This often reduces constant pool loads.
7334 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7335 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7336 N0.getNode()->hasOneUse() && VT.isInteger() &&
7337 !VT.isVector() && !N0.getValueType().isVector()) {
7338 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7340 AddToWorklist(NewConv.getNode());
7343 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7344 if (N0.getOpcode() == ISD::FNEG)
7345 return DAG.getNode(ISD::XOR, DL, VT,
7346 NewConv, DAG.getConstant(SignBit, DL, VT));
7347 assert(N0.getOpcode() == ISD::FABS);
7348 return DAG.getNode(ISD::AND, DL, VT,
7349 NewConv, DAG.getConstant(~SignBit, DL, VT));
7352 // fold (bitconvert (fcopysign cst, x)) ->
7353 // (or (and (bitconvert x), sign), (and cst, (not sign)))
7354 // Note that we don't handle (copysign x, cst) because this can always be
7355 // folded to an fneg or fabs.
7356 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7357 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7358 VT.isInteger() && !VT.isVector()) {
7359 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7360 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7361 if (isTypeLegal(IntXVT)) {
7362 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7363 IntXVT, N0.getOperand(1));
7364 AddToWorklist(X.getNode());
7366 // If X has a different width than the result/lhs, sext it or truncate it.
7367 unsigned VTWidth = VT.getSizeInBits();
7368 if (OrigXWidth < VTWidth) {
7369 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7370 AddToWorklist(X.getNode());
7371 } else if (OrigXWidth > VTWidth) {
7372 // To get the sign bit in the right place, we have to shift it right
7373 // before truncating.
7375 X = DAG.getNode(ISD::SRL, DL,
7376 X.getValueType(), X,
7377 DAG.getConstant(OrigXWidth-VTWidth, DL,
7379 AddToWorklist(X.getNode());
7380 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7381 AddToWorklist(X.getNode());
7384 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7385 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7386 X, DAG.getConstant(SignBit, SDLoc(X), VT));
7387 AddToWorklist(X.getNode());
7389 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7390 VT, N0.getOperand(0));
7391 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7392 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7393 AddToWorklist(Cst.getNode());
7395 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7399 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7400 if (N0.getOpcode() == ISD::BUILD_PAIR)
7401 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7404 // Remove double bitcasts from shuffles - this is often a legacy of
7405 // XformToShuffleWithZero being used to combine bitmaskings (of
7406 // float vectors bitcast to integer vectors) into shuffles.
7407 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7408 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7409 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7410 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7411 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7412 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7414 // If operands are a bitcast, peek through if it casts the original VT.
7415 // If operands are a constant, just bitcast back to original VT.
7416 auto PeekThroughBitcast = [&](SDValue Op) {
7417 if (Op.getOpcode() == ISD::BITCAST &&
7418 Op.getOperand(0).getValueType() == VT)
7419 return SDValue(Op.getOperand(0));
7420 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7421 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7422 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7426 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7427 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7432 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7433 SmallVector<int, 8> NewMask;
7434 for (int M : SVN->getMask())
7435 for (int i = 0; i != MaskScale; ++i)
7436 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7438 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7440 std::swap(SV0, SV1);
7441 ShuffleVectorSDNode::commuteMask(NewMask);
7442 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7446 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7452 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7453 EVT VT = N->getValueType(0);
7454 return CombineConsecutiveLoads(N, VT);
7457 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7458 /// operands. DstEltVT indicates the destination element value type.
7459 SDValue DAGCombiner::
7460 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7461 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7463 // If this is already the right type, we're done.
7464 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7466 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7467 unsigned DstBitSize = DstEltVT.getSizeInBits();
7469 // If this is a conversion of N elements of one type to N elements of another
7470 // type, convert each element. This handles FP<->INT cases.
7471 if (SrcBitSize == DstBitSize) {
7472 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7473 BV->getValueType(0).getVectorNumElements());
7475 // Due to the FP element handling below calling this routine recursively,
7476 // we can end up with a scalar-to-vector node here.
7477 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7478 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7479 DAG.getNode(ISD::BITCAST, SDLoc(BV),
7480 DstEltVT, BV->getOperand(0)));
7482 SmallVector<SDValue, 8> Ops;
7483 for (SDValue Op : BV->op_values()) {
7484 // If the vector element type is not legal, the BUILD_VECTOR operands
7485 // are promoted and implicitly truncated. Make that explicit here.
7486 if (Op.getValueType() != SrcEltVT)
7487 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7488 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7490 AddToWorklist(Ops.back().getNode());
7492 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7495 // Otherwise, we're growing or shrinking the elements. To avoid having to
7496 // handle annoying details of growing/shrinking FP values, we convert them to
7498 if (SrcEltVT.isFloatingPoint()) {
7499 // Convert the input float vector to a int vector where the elements are the
7501 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7502 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7506 // Now we know the input is an integer vector. If the output is a FP type,
7507 // convert to integer first, then to FP of the right size.
7508 if (DstEltVT.isFloatingPoint()) {
7509 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7510 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7512 // Next, convert to FP elements of the same size.
7513 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7518 // Okay, we know the src/dst types are both integers of differing types.
7519 // Handling growing first.
7520 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7521 if (SrcBitSize < DstBitSize) {
7522 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7524 SmallVector<SDValue, 8> Ops;
7525 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7526 i += NumInputsPerOutput) {
7527 bool isLE = DAG.getDataLayout().isLittleEndian();
7528 APInt NewBits = APInt(DstBitSize, 0);
7529 bool EltIsUndef = true;
7530 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7531 // Shift the previously computed bits over.
7532 NewBits <<= SrcBitSize;
7533 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7534 if (Op.getOpcode() == ISD::UNDEF) continue;
7537 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7538 zextOrTrunc(SrcBitSize).zext(DstBitSize);
7542 Ops.push_back(DAG.getUNDEF(DstEltVT));
7544 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7547 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7548 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7551 // Finally, this must be the case where we are shrinking elements: each input
7552 // turns into multiple outputs.
7553 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7554 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7555 NumOutputsPerInput*BV->getNumOperands());
7556 SmallVector<SDValue, 8> Ops;
7558 for (const SDValue &Op : BV->op_values()) {
7559 if (Op.getOpcode() == ISD::UNDEF) {
7560 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7564 APInt OpVal = cast<ConstantSDNode>(Op)->
7565 getAPIntValue().zextOrTrunc(SrcBitSize);
7567 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7568 APInt ThisVal = OpVal.trunc(DstBitSize);
7569 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7570 OpVal = OpVal.lshr(DstBitSize);
7573 // For big endian targets, swap the order of the pieces of each element.
7574 if (DAG.getDataLayout().isBigEndian())
7575 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7578 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7581 /// Try to perform FMA combining on a given FADD node.
7582 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7583 SDValue N0 = N->getOperand(0);
7584 SDValue N1 = N->getOperand(1);
7585 EVT VT = N->getValueType(0);
7588 const TargetOptions &Options = DAG.getTarget().Options;
7590 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7592 // Floating-point multiply-add with intermediate rounding.
7593 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7595 // Floating-point multiply-add without intermediate rounding.
7597 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7598 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7600 // No valid opcode, do not combine.
7601 if (!HasFMAD && !HasFMA)
7604 // Always prefer FMAD to FMA for precision.
7605 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7606 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7607 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7609 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7610 // prefer to fold the multiply with fewer uses.
7611 if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7612 N1.getOpcode() == ISD::FMUL) {
7613 if (N0.getNode()->use_size() > N1.getNode()->use_size())
7617 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7618 if (N0.getOpcode() == ISD::FMUL &&
7619 (Aggressive || N0->hasOneUse())) {
7620 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7621 N0.getOperand(0), N0.getOperand(1), N1);
7624 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7625 // Note: Commutes FADD operands.
7626 if (N1.getOpcode() == ISD::FMUL &&
7627 (Aggressive || N1->hasOneUse())) {
7628 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7629 N1.getOperand(0), N1.getOperand(1), N0);
7632 // Look through FP_EXTEND nodes to do more combining.
7633 if (AllowFusion && LookThroughFPExt) {
7634 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7635 if (N0.getOpcode() == ISD::FP_EXTEND) {
7636 SDValue N00 = N0.getOperand(0);
7637 if (N00.getOpcode() == ISD::FMUL)
7638 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7639 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7641 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7642 N00.getOperand(1)), N1);
7645 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7646 // Note: Commutes FADD operands.
7647 if (N1.getOpcode() == ISD::FP_EXTEND) {
7648 SDValue N10 = N1.getOperand(0);
7649 if (N10.getOpcode() == ISD::FMUL)
7650 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7651 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7653 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7654 N10.getOperand(1)), N0);
7658 // More folding opportunities when target permits.
7659 if ((AllowFusion || HasFMAD) && Aggressive) {
7660 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7661 if (N0.getOpcode() == PreferredFusedOpcode &&
7662 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7663 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7664 N0.getOperand(0), N0.getOperand(1),
7665 DAG.getNode(PreferredFusedOpcode, SL, VT,
7666 N0.getOperand(2).getOperand(0),
7667 N0.getOperand(2).getOperand(1),
7671 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7672 if (N1->getOpcode() == PreferredFusedOpcode &&
7673 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7674 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7675 N1.getOperand(0), N1.getOperand(1),
7676 DAG.getNode(PreferredFusedOpcode, SL, VT,
7677 N1.getOperand(2).getOperand(0),
7678 N1.getOperand(2).getOperand(1),
7682 if (AllowFusion && LookThroughFPExt) {
7683 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7684 // -> (fma x, y, (fma (fpext u), (fpext v), z))
7685 auto FoldFAddFMAFPExtFMul = [&] (
7686 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7687 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7688 DAG.getNode(PreferredFusedOpcode, SL, VT,
7689 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7690 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7693 if (N0.getOpcode() == PreferredFusedOpcode) {
7694 SDValue N02 = N0.getOperand(2);
7695 if (N02.getOpcode() == ISD::FP_EXTEND) {
7696 SDValue N020 = N02.getOperand(0);
7697 if (N020.getOpcode() == ISD::FMUL)
7698 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7699 N020.getOperand(0), N020.getOperand(1),
7704 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7705 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7706 // FIXME: This turns two single-precision and one double-precision
7707 // operation into two double-precision operations, which might not be
7708 // interesting for all targets, especially GPUs.
7709 auto FoldFAddFPExtFMAFMul = [&] (
7710 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7711 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7712 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7713 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7714 DAG.getNode(PreferredFusedOpcode, SL, VT,
7715 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7716 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7719 if (N0.getOpcode() == ISD::FP_EXTEND) {
7720 SDValue N00 = N0.getOperand(0);
7721 if (N00.getOpcode() == PreferredFusedOpcode) {
7722 SDValue N002 = N00.getOperand(2);
7723 if (N002.getOpcode() == ISD::FMUL)
7724 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7725 N002.getOperand(0), N002.getOperand(1),
7730 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7731 // -> (fma y, z, (fma (fpext u), (fpext v), x))
7732 if (N1.getOpcode() == PreferredFusedOpcode) {
7733 SDValue N12 = N1.getOperand(2);
7734 if (N12.getOpcode() == ISD::FP_EXTEND) {
7735 SDValue N120 = N12.getOperand(0);
7736 if (N120.getOpcode() == ISD::FMUL)
7737 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7738 N120.getOperand(0), N120.getOperand(1),
7743 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7744 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7745 // FIXME: This turns two single-precision and one double-precision
7746 // operation into two double-precision operations, which might not be
7747 // interesting for all targets, especially GPUs.
7748 if (N1.getOpcode() == ISD::FP_EXTEND) {
7749 SDValue N10 = N1.getOperand(0);
7750 if (N10.getOpcode() == PreferredFusedOpcode) {
7751 SDValue N102 = N10.getOperand(2);
7752 if (N102.getOpcode() == ISD::FMUL)
7753 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7754 N102.getOperand(0), N102.getOperand(1),
7764 /// Try to perform FMA combining on a given FSUB node.
7765 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7766 SDValue N0 = N->getOperand(0);
7767 SDValue N1 = N->getOperand(1);
7768 EVT VT = N->getValueType(0);
7771 const TargetOptions &Options = DAG.getTarget().Options;
7773 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7775 // Floating-point multiply-add with intermediate rounding.
7776 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7778 // Floating-point multiply-add without intermediate rounding.
7780 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7781 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7783 // No valid opcode, do not combine.
7784 if (!HasFMAD && !HasFMA)
7787 // Always prefer FMAD to FMA for precision.
7788 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7789 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7790 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7792 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7793 if (N0.getOpcode() == ISD::FMUL &&
7794 (Aggressive || N0->hasOneUse())) {
7795 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7796 N0.getOperand(0), N0.getOperand(1),
7797 DAG.getNode(ISD::FNEG, SL, VT, N1));
7800 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7801 // Note: Commutes FSUB operands.
7802 if (N1.getOpcode() == ISD::FMUL &&
7803 (Aggressive || N1->hasOneUse()))
7804 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7805 DAG.getNode(ISD::FNEG, SL, VT,
7807 N1.getOperand(1), N0);
7809 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7810 if (N0.getOpcode() == ISD::FNEG &&
7811 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7812 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7813 SDValue N00 = N0.getOperand(0).getOperand(0);
7814 SDValue N01 = N0.getOperand(0).getOperand(1);
7815 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7816 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7817 DAG.getNode(ISD::FNEG, SL, VT, N1));
7820 // Look through FP_EXTEND nodes to do more combining.
7821 if (AllowFusion && LookThroughFPExt) {
7822 // fold (fsub (fpext (fmul x, y)), z)
7823 // -> (fma (fpext x), (fpext y), (fneg z))
7824 if (N0.getOpcode() == ISD::FP_EXTEND) {
7825 SDValue N00 = N0.getOperand(0);
7826 if (N00.getOpcode() == ISD::FMUL)
7827 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7828 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7830 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7832 DAG.getNode(ISD::FNEG, SL, VT, N1));
7835 // fold (fsub x, (fpext (fmul y, z)))
7836 // -> (fma (fneg (fpext y)), (fpext z), x)
7837 // Note: Commutes FSUB operands.
7838 if (N1.getOpcode() == ISD::FP_EXTEND) {
7839 SDValue N10 = N1.getOperand(0);
7840 if (N10.getOpcode() == ISD::FMUL)
7841 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7842 DAG.getNode(ISD::FNEG, SL, VT,
7843 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7844 N10.getOperand(0))),
7845 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7850 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7851 // -> (fneg (fma (fpext x), (fpext y), z))
7852 // Note: This could be removed with appropriate canonicalization of the
7853 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7854 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7855 // from implementing the canonicalization in visitFSUB.
7856 if (N0.getOpcode() == ISD::FP_EXTEND) {
7857 SDValue N00 = N0.getOperand(0);
7858 if (N00.getOpcode() == ISD::FNEG) {
7859 SDValue N000 = N00.getOperand(0);
7860 if (N000.getOpcode() == ISD::FMUL) {
7861 return DAG.getNode(ISD::FNEG, SL, VT,
7862 DAG.getNode(PreferredFusedOpcode, SL, VT,
7863 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7864 N000.getOperand(0)),
7865 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7866 N000.getOperand(1)),
7872 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7873 // -> (fneg (fma (fpext x)), (fpext y), z)
7874 // Note: This could be removed with appropriate canonicalization of the
7875 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7876 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7877 // from implementing the canonicalization in visitFSUB.
7878 if (N0.getOpcode() == ISD::FNEG) {
7879 SDValue N00 = N0.getOperand(0);
7880 if (N00.getOpcode() == ISD::FP_EXTEND) {
7881 SDValue N000 = N00.getOperand(0);
7882 if (N000.getOpcode() == ISD::FMUL) {
7883 return DAG.getNode(ISD::FNEG, SL, VT,
7884 DAG.getNode(PreferredFusedOpcode, SL, VT,
7885 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7886 N000.getOperand(0)),
7887 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7888 N000.getOperand(1)),
7896 // More folding opportunities when target permits.
7897 if ((AllowFusion || HasFMAD) && Aggressive) {
7898 // fold (fsub (fma x, y, (fmul u, v)), z)
7899 // -> (fma x, y (fma u, v, (fneg z)))
7900 if (N0.getOpcode() == PreferredFusedOpcode &&
7901 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7902 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7903 N0.getOperand(0), N0.getOperand(1),
7904 DAG.getNode(PreferredFusedOpcode, SL, VT,
7905 N0.getOperand(2).getOperand(0),
7906 N0.getOperand(2).getOperand(1),
7907 DAG.getNode(ISD::FNEG, SL, VT,
7911 // fold (fsub x, (fma y, z, (fmul u, v)))
7912 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7913 if (N1.getOpcode() == PreferredFusedOpcode &&
7914 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7915 SDValue N20 = N1.getOperand(2).getOperand(0);
7916 SDValue N21 = N1.getOperand(2).getOperand(1);
7917 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7918 DAG.getNode(ISD::FNEG, SL, VT,
7921 DAG.getNode(PreferredFusedOpcode, SL, VT,
7922 DAG.getNode(ISD::FNEG, SL, VT, N20),
7927 if (AllowFusion && LookThroughFPExt) {
7928 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7929 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7930 if (N0.getOpcode() == PreferredFusedOpcode) {
7931 SDValue N02 = N0.getOperand(2);
7932 if (N02.getOpcode() == ISD::FP_EXTEND) {
7933 SDValue N020 = N02.getOperand(0);
7934 if (N020.getOpcode() == ISD::FMUL)
7935 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7936 N0.getOperand(0), N0.getOperand(1),
7937 DAG.getNode(PreferredFusedOpcode, SL, VT,
7938 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7939 N020.getOperand(0)),
7940 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7941 N020.getOperand(1)),
7942 DAG.getNode(ISD::FNEG, SL, VT,
7947 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7948 // -> (fma (fpext x), (fpext y),
7949 // (fma (fpext u), (fpext v), (fneg z)))
7950 // FIXME: This turns two single-precision and one double-precision
7951 // operation into two double-precision operations, which might not be
7952 // interesting for all targets, especially GPUs.
7953 if (N0.getOpcode() == ISD::FP_EXTEND) {
7954 SDValue N00 = N0.getOperand(0);
7955 if (N00.getOpcode() == PreferredFusedOpcode) {
7956 SDValue N002 = N00.getOperand(2);
7957 if (N002.getOpcode() == ISD::FMUL)
7958 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7959 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7961 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7963 DAG.getNode(PreferredFusedOpcode, SL, VT,
7964 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7965 N002.getOperand(0)),
7966 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7967 N002.getOperand(1)),
7968 DAG.getNode(ISD::FNEG, SL, VT,
7973 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7974 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7975 if (N1.getOpcode() == PreferredFusedOpcode &&
7976 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7977 SDValue N120 = N1.getOperand(2).getOperand(0);
7978 if (N120.getOpcode() == ISD::FMUL) {
7979 SDValue N1200 = N120.getOperand(0);
7980 SDValue N1201 = N120.getOperand(1);
7981 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7982 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7984 DAG.getNode(PreferredFusedOpcode, SL, VT,
7985 DAG.getNode(ISD::FNEG, SL, VT,
7986 DAG.getNode(ISD::FP_EXTEND, SL,
7988 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7994 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7995 // -> (fma (fneg (fpext y)), (fpext z),
7996 // (fma (fneg (fpext u)), (fpext v), x))
7997 // FIXME: This turns two single-precision and one double-precision
7998 // operation into two double-precision operations, which might not be
7999 // interesting for all targets, especially GPUs.
8000 if (N1.getOpcode() == ISD::FP_EXTEND &&
8001 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
8002 SDValue N100 = N1.getOperand(0).getOperand(0);
8003 SDValue N101 = N1.getOperand(0).getOperand(1);
8004 SDValue N102 = N1.getOperand(0).getOperand(2);
8005 if (N102.getOpcode() == ISD::FMUL) {
8006 SDValue N1020 = N102.getOperand(0);
8007 SDValue N1021 = N102.getOperand(1);
8008 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8009 DAG.getNode(ISD::FNEG, SL, VT,
8010 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8012 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
8013 DAG.getNode(PreferredFusedOpcode, SL, VT,
8014 DAG.getNode(ISD::FNEG, SL, VT,
8015 DAG.getNode(ISD::FP_EXTEND, SL,
8017 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8028 /// Try to perform FMA combining on a given FMUL node.
8029 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
8030 SDValue N0 = N->getOperand(0);
8031 SDValue N1 = N->getOperand(1);
8032 EVT VT = N->getValueType(0);
8035 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
8037 const TargetOptions &Options = DAG.getTarget().Options;
8039 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8041 // Floating-point multiply-add with intermediate rounding.
8042 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8044 // Floating-point multiply-add without intermediate rounding.
8046 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8047 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8049 // No valid opcode, do not combine.
8050 if (!HasFMAD && !HasFMA)
8053 // Always prefer FMAD to FMA for precision.
8054 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8055 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8057 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
8058 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
8059 auto FuseFADD = [&](SDValue X, SDValue Y) {
8060 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
8061 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8062 if (XC1 && XC1->isExactlyValue(+1.0))
8063 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8064 if (XC1 && XC1->isExactlyValue(-1.0))
8065 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8066 DAG.getNode(ISD::FNEG, SL, VT, Y));
8071 if (SDValue FMA = FuseFADD(N0, N1))
8073 if (SDValue FMA = FuseFADD(N1, N0))
8076 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
8077 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
8078 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
8079 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
8080 auto FuseFSUB = [&](SDValue X, SDValue Y) {
8081 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
8082 auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
8083 if (XC0 && XC0->isExactlyValue(+1.0))
8084 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8085 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8087 if (XC0 && XC0->isExactlyValue(-1.0))
8088 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8089 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8090 DAG.getNode(ISD::FNEG, SL, VT, Y));
8092 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8093 if (XC1 && XC1->isExactlyValue(+1.0))
8094 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8095 DAG.getNode(ISD::FNEG, SL, VT, Y));
8096 if (XC1 && XC1->isExactlyValue(-1.0))
8097 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8102 if (SDValue FMA = FuseFSUB(N0, N1))
8104 if (SDValue FMA = FuseFSUB(N1, N0))
8110 SDValue DAGCombiner::visitFADD(SDNode *N) {
8111 SDValue N0 = N->getOperand(0);
8112 SDValue N1 = N->getOperand(1);
8113 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
8114 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8115 EVT VT = N->getValueType(0);
8117 const TargetOptions &Options = DAG.getTarget().Options;
8118 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8122 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8125 // fold (fadd c1, c2) -> c1 + c2
8127 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8129 // canonicalize constant to RHS
8130 if (N0CFP && !N1CFP)
8131 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8133 // fold (fadd A, (fneg B)) -> (fsub A, B)
8134 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8135 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8136 return DAG.getNode(ISD::FSUB, DL, VT, N0,
8137 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8139 // fold (fadd (fneg A), B) -> (fsub B, A)
8140 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8141 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8142 return DAG.getNode(ISD::FSUB, DL, VT, N1,
8143 GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8145 // If 'unsafe math' is enabled, fold lots of things.
8146 if (Options.UnsafeFPMath) {
8147 // No FP constant should be created after legalization as Instruction
8148 // Selection pass has a hard time dealing with FP constants.
8149 bool AllowNewConst = (Level < AfterLegalizeDAG);
8151 // fold (fadd A, 0) -> A
8152 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8156 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8157 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8158 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8159 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8160 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8164 // If allowed, fold (fadd (fneg x), x) -> 0.0
8165 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8166 return DAG.getConstantFP(0.0, DL, VT);
8168 // If allowed, fold (fadd x, (fneg x)) -> 0.0
8169 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8170 return DAG.getConstantFP(0.0, DL, VT);
8172 // We can fold chains of FADD's of the same value into multiplications.
8173 // This transform is not safe in general because we are reducing the number
8174 // of rounding steps.
8175 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8176 if (N0.getOpcode() == ISD::FMUL) {
8177 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8178 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8180 // (fadd (fmul x, c), x) -> (fmul x, c+1)
8181 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8182 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8183 DAG.getConstantFP(1.0, DL, VT), Flags);
8184 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8187 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8188 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8189 N1.getOperand(0) == N1.getOperand(1) &&
8190 N0.getOperand(0) == N1.getOperand(0)) {
8191 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8192 DAG.getConstantFP(2.0, DL, VT), Flags);
8193 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8197 if (N1.getOpcode() == ISD::FMUL) {
8198 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8199 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8201 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8202 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8203 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8204 DAG.getConstantFP(1.0, DL, VT), Flags);
8205 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8208 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8209 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8210 N0.getOperand(0) == N0.getOperand(1) &&
8211 N1.getOperand(0) == N0.getOperand(0)) {
8212 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8213 DAG.getConstantFP(2.0, DL, VT), Flags);
8214 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8218 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8219 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8220 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8221 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8222 (N0.getOperand(0) == N1)) {
8223 return DAG.getNode(ISD::FMUL, DL, VT,
8224 N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8228 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8229 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8230 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8231 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8232 N1.getOperand(0) == N0) {
8233 return DAG.getNode(ISD::FMUL, DL, VT,
8234 N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8238 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8239 if (AllowNewConst &&
8240 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8241 N0.getOperand(0) == N0.getOperand(1) &&
8242 N1.getOperand(0) == N1.getOperand(1) &&
8243 N0.getOperand(0) == N1.getOperand(0)) {
8244 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8245 DAG.getConstantFP(4.0, DL, VT), Flags);
8248 } // enable-unsafe-fp-math
8250 // FADD -> FMA combines:
8251 if (SDValue Fused = visitFADDForFMACombine(N)) {
8252 AddToWorklist(Fused.getNode());
8259 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8260 SDValue N0 = N->getOperand(0);
8261 SDValue N1 = N->getOperand(1);
8262 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8263 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8264 EVT VT = N->getValueType(0);
8266 const TargetOptions &Options = DAG.getTarget().Options;
8267 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8271 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8274 // fold (fsub c1, c2) -> c1-c2
8276 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags);
8278 // fold (fsub A, (fneg B)) -> (fadd A, B)
8279 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8280 return DAG.getNode(ISD::FADD, dl, VT, N0,
8281 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8283 // If 'unsafe math' is enabled, fold lots of things.
8284 if (Options.UnsafeFPMath) {
8286 if (N1CFP && N1CFP->isZero())
8289 // (fsub 0, B) -> -B
8290 if (N0CFP && N0CFP->isZero()) {
8291 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8292 return GetNegatedExpression(N1, DAG, LegalOperations);
8293 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8294 return DAG.getNode(ISD::FNEG, dl, VT, N1);
8297 // (fsub x, x) -> 0.0
8299 return DAG.getConstantFP(0.0f, dl, VT);
8301 // (fsub x, (fadd x, y)) -> (fneg y)
8302 // (fsub x, (fadd y, x)) -> (fneg y)
8303 if (N1.getOpcode() == ISD::FADD) {
8304 SDValue N10 = N1->getOperand(0);
8305 SDValue N11 = N1->getOperand(1);
8307 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8308 return GetNegatedExpression(N11, DAG, LegalOperations);
8310 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8311 return GetNegatedExpression(N10, DAG, LegalOperations);
8315 // FSUB -> FMA combines:
8316 if (SDValue Fused = visitFSUBForFMACombine(N)) {
8317 AddToWorklist(Fused.getNode());
8324 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8325 SDValue N0 = N->getOperand(0);
8326 SDValue N1 = N->getOperand(1);
8327 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8328 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8329 EVT VT = N->getValueType(0);
8331 const TargetOptions &Options = DAG.getTarget().Options;
8332 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8335 if (VT.isVector()) {
8336 // This just handles C1 * C2 for vectors. Other vector folds are below.
8337 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8341 // fold (fmul c1, c2) -> c1*c2
8343 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8345 // canonicalize constant to RHS
8346 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8347 !isConstantFPBuildVectorOrConstantFP(N1))
8348 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8350 // fold (fmul A, 1.0) -> A
8351 if (N1CFP && N1CFP->isExactlyValue(1.0))
8354 if (Options.UnsafeFPMath) {
8355 // fold (fmul A, 0) -> 0
8356 if (N1CFP && N1CFP->isZero())
8359 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8360 if (N0.getOpcode() == ISD::FMUL) {
8361 // Fold scalars or any vector constants (not just splats).
8362 // This fold is done in general by InstCombine, but extra fmul insts
8363 // may have been generated during lowering.
8364 SDValue N00 = N0.getOperand(0);
8365 SDValue N01 = N0.getOperand(1);
8366 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8367 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8368 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8370 // Check 1: Make sure that the first operand of the inner multiply is NOT
8371 // a constant. Otherwise, we may induce infinite looping.
8372 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8373 // Check 2: Make sure that the second operand of the inner multiply and
8374 // the second operand of the outer multiply are constants.
8375 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8376 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8377 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8378 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8383 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8384 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8385 // during an early run of DAGCombiner can prevent folding with fmuls
8386 // inserted during lowering.
8387 if (N0.getOpcode() == ISD::FADD &&
8388 (N0.getOperand(0) == N0.getOperand(1)) &&
8390 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8391 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8392 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8396 // fold (fmul X, 2.0) -> (fadd X, X)
8397 if (N1CFP && N1CFP->isExactlyValue(+2.0))
8398 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8400 // fold (fmul X, -1.0) -> (fneg X)
8401 if (N1CFP && N1CFP->isExactlyValue(-1.0))
8402 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8403 return DAG.getNode(ISD::FNEG, DL, VT, N0);
8405 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8406 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8407 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8408 // Both can be negated for free, check to see if at least one is cheaper
8410 if (LHSNeg == 2 || RHSNeg == 2)
8411 return DAG.getNode(ISD::FMUL, DL, VT,
8412 GetNegatedExpression(N0, DAG, LegalOperations),
8413 GetNegatedExpression(N1, DAG, LegalOperations),
8418 // FMUL -> FMA combines:
8419 if (SDValue Fused = visitFMULForFMACombine(N)) {
8420 AddToWorklist(Fused.getNode());
8427 SDValue DAGCombiner::visitFMA(SDNode *N) {
8428 SDValue N0 = N->getOperand(0);
8429 SDValue N1 = N->getOperand(1);
8430 SDValue N2 = N->getOperand(2);
8431 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8432 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8433 EVT VT = N->getValueType(0);
8435 const TargetOptions &Options = DAG.getTarget().Options;
8437 // Constant fold FMA.
8438 if (isa<ConstantFPSDNode>(N0) &&
8439 isa<ConstantFPSDNode>(N1) &&
8440 isa<ConstantFPSDNode>(N2)) {
8441 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8444 if (Options.UnsafeFPMath) {
8445 if (N0CFP && N0CFP->isZero())
8447 if (N1CFP && N1CFP->isZero())
8450 // TODO: The FMA node should have flags that propagate to these nodes.
8451 if (N0CFP && N0CFP->isExactlyValue(1.0))
8452 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8453 if (N1CFP && N1CFP->isExactlyValue(1.0))
8454 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8456 // Canonicalize (fma c, x, y) -> (fma x, c, y)
8457 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8458 !isConstantFPBuildVectorOrConstantFP(N1))
8459 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8461 // TODO: FMA nodes should have flags that propagate to the created nodes.
8462 // For now, create a Flags object for use with all unsafe math transforms.
8464 Flags.setUnsafeAlgebra(true);
8466 if (Options.UnsafeFPMath) {
8467 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8468 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8469 isConstantFPBuildVectorOrConstantFP(N1) &&
8470 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8471 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8472 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1),
8476 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8477 if (N0.getOpcode() == ISD::FMUL &&
8478 isConstantFPBuildVectorOrConstantFP(N1) &&
8479 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8480 return DAG.getNode(ISD::FMA, dl, VT,
8482 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1),
8488 // (fma x, 1, y) -> (fadd x, y)
8489 // (fma x, -1, y) -> (fadd (fneg x), y)
8491 if (N1CFP->isExactlyValue(1.0))
8492 // TODO: The FMA node should have flags that propagate to this node.
8493 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8495 if (N1CFP->isExactlyValue(-1.0) &&
8496 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8497 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8498 AddToWorklist(RHSNeg.getNode());
8499 // TODO: The FMA node should have flags that propagate to this node.
8500 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8504 if (Options.UnsafeFPMath) {
8505 // (fma x, c, x) -> (fmul x, (c+1))
8506 if (N1CFP && N0 == N2) {
8507 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8508 DAG.getNode(ISD::FADD, dl, VT,
8509 N1, DAG.getConstantFP(1.0, dl, VT),
8513 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8514 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8515 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8516 DAG.getNode(ISD::FADD, dl, VT,
8517 N1, DAG.getConstantFP(-1.0, dl, VT),
8525 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8527 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8528 // Notice that this is not always beneficial. One reason is different target
8529 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8530 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8531 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8532 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8533 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
8534 const SDNodeFlags *Flags = N->getFlags();
8535 if (!UnsafeMath && !Flags->hasAllowReciprocal())
8538 // Skip if current node is a reciprocal.
8539 SDValue N0 = N->getOperand(0);
8540 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8541 if (N0CFP && N0CFP->isExactlyValue(1.0))
8544 // Exit early if the target does not want this transform or if there can't
8545 // possibly be enough uses of the divisor to make the transform worthwhile.
8546 SDValue N1 = N->getOperand(1);
8547 unsigned MinUses = TLI.combineRepeatedFPDivisors();
8548 if (!MinUses || N1->use_size() < MinUses)
8551 // Find all FDIV users of the same divisor.
8552 // Use a set because duplicates may be present in the user list.
8553 SetVector<SDNode *> Users;
8554 for (auto *U : N1->uses()) {
8555 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
8556 // This division is eligible for optimization only if global unsafe math
8557 // is enabled or if this division allows reciprocal formation.
8558 if (UnsafeMath || U->getFlags()->hasAllowReciprocal())
8563 // Now that we have the actual number of divisor uses, make sure it meets
8564 // the minimum threshold specified by the target.
8565 if (Users.size() < MinUses)
8568 EVT VT = N->getValueType(0);
8570 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8571 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8573 // Dividend / Divisor -> Dividend * Reciprocal
8574 for (auto *U : Users) {
8575 SDValue Dividend = U->getOperand(0);
8576 if (Dividend != FPOne) {
8577 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8579 CombineTo(U, NewNode);
8580 } else if (U != Reciprocal.getNode()) {
8581 // In the absence of fast-math-flags, this user node is always the
8582 // same node as Reciprocal, but with FMF they may be different nodes.
8583 CombineTo(U, Reciprocal);
8586 return SDValue(N, 0); // N was replaced.
8589 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8590 SDValue N0 = N->getOperand(0);
8591 SDValue N1 = N->getOperand(1);
8592 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8593 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8594 EVT VT = N->getValueType(0);
8596 const TargetOptions &Options = DAG.getTarget().Options;
8597 SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8601 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8604 // fold (fdiv c1, c2) -> c1/c2
8606 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8608 if (Options.UnsafeFPMath) {
8609 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8611 // Compute the reciprocal 1.0 / c2.
8612 APFloat N1APF = N1CFP->getValueAPF();
8613 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8614 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8615 // Only do the transform if the reciprocal is a legal fp immediate that
8616 // isn't too nasty (eg NaN, denormal, ...).
8617 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8618 (!LegalOperations ||
8619 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8620 // backend)... we should handle this gracefully after Legalize.
8621 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8622 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8623 TLI.isFPImmLegal(Recip, VT)))
8624 return DAG.getNode(ISD::FMUL, DL, VT, N0,
8625 DAG.getConstantFP(Recip, DL, VT), Flags);
8628 // If this FDIV is part of a reciprocal square root, it may be folded
8629 // into a target-specific square root estimate instruction.
8630 if (N1.getOpcode() == ISD::FSQRT) {
8631 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) {
8632 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8634 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8635 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8636 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8638 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8639 AddToWorklist(RV.getNode());
8640 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8642 } else if (N1.getOpcode() == ISD::FP_ROUND &&
8643 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8644 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8646 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8647 AddToWorklist(RV.getNode());
8648 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8650 } else if (N1.getOpcode() == ISD::FMUL) {
8651 // Look through an FMUL. Even though this won't remove the FDIV directly,
8652 // it's still worthwhile to get rid of the FSQRT if possible.
8655 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8656 SqrtOp = N1.getOperand(0);
8657 OtherOp = N1.getOperand(1);
8658 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8659 SqrtOp = N1.getOperand(1);
8660 OtherOp = N1.getOperand(0);
8662 if (SqrtOp.getNode()) {
8663 // We found a FSQRT, so try to make this fold:
8664 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8665 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
8666 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
8667 AddToWorklist(RV.getNode());
8668 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8673 // Fold into a reciprocal estimate and multiply instead of a real divide.
8674 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
8675 AddToWorklist(RV.getNode());
8676 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8680 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8681 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8682 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8683 // Both can be negated for free, check to see if at least one is cheaper
8685 if (LHSNeg == 2 || RHSNeg == 2)
8686 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8687 GetNegatedExpression(N0, DAG, LegalOperations),
8688 GetNegatedExpression(N1, DAG, LegalOperations),
8693 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8694 return CombineRepeatedDivisors;
8699 SDValue DAGCombiner::visitFREM(SDNode *N) {
8700 SDValue N0 = N->getOperand(0);
8701 SDValue N1 = N->getOperand(1);
8702 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8703 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8704 EVT VT = N->getValueType(0);
8706 // fold (frem c1, c2) -> fmod(c1,c2)
8708 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
8709 &cast<BinaryWithFlagsSDNode>(N)->Flags);
8714 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8715 if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8718 // TODO: FSQRT nodes should have flags that propagate to the created nodes.
8719 // For now, create a Flags object for use with all unsafe math transforms.
8721 Flags.setUnsafeAlgebra(true);
8723 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8724 SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags);
8728 EVT VT = RV.getValueType();
8730 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags);
8731 AddToWorklist(RV.getNode());
8733 // Unfortunately, RV is now NaN if the input was exactly 0.
8734 // Select out this case and force the answer to 0.
8735 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8736 EVT CCVT = getSetCCResultType(VT);
8737 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8738 AddToWorklist(ZeroCmp.getNode());
8739 AddToWorklist(RV.getNode());
8741 return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8745 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8746 SDValue N0 = N->getOperand(0);
8747 SDValue N1 = N->getOperand(1);
8748 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8749 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8750 EVT VT = N->getValueType(0);
8752 if (N0CFP && N1CFP) // Constant fold
8753 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8756 const APFloat& V = N1CFP->getValueAPF();
8757 // copysign(x, c1) -> fabs(x) iff ispos(c1)
8758 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8759 if (!V.isNegative()) {
8760 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8761 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8763 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8764 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8765 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8769 // copysign(fabs(x), y) -> copysign(x, y)
8770 // copysign(fneg(x), y) -> copysign(x, y)
8771 // copysign(copysign(x,z), y) -> copysign(x, y)
8772 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8773 N0.getOpcode() == ISD::FCOPYSIGN)
8774 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8775 N0.getOperand(0), N1);
8777 // copysign(x, abs(y)) -> abs(x)
8778 if (N1.getOpcode() == ISD::FABS)
8779 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8781 // copysign(x, copysign(y,z)) -> copysign(x, z)
8782 if (N1.getOpcode() == ISD::FCOPYSIGN)
8783 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8784 N0, N1.getOperand(1));
8786 // copysign(x, fp_extend(y)) -> copysign(x, y)
8787 // copysign(x, fp_round(y)) -> copysign(x, y)
8788 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8789 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8790 N0, N1.getOperand(0));
8795 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8796 SDValue N0 = N->getOperand(0);
8797 EVT VT = N->getValueType(0);
8798 EVT OpVT = N0.getValueType();
8800 // fold (sint_to_fp c1) -> c1fp
8801 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8802 // ...but only if the target supports immediate floating-point values
8803 (!LegalOperations ||
8804 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8805 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8807 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8808 // but UINT_TO_FP is legal on this target, try to convert.
8809 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8810 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8811 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8812 if (DAG.SignBitIsZero(N0))
8813 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8816 // The next optimizations are desirable only if SELECT_CC can be lowered.
8817 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8818 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8819 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8821 (!LegalOperations ||
8822 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8825 { N0.getOperand(0), N0.getOperand(1),
8826 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8828 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8831 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8832 // (select_cc x, y, 1.0, 0.0,, cc)
8833 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8834 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8835 (!LegalOperations ||
8836 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8839 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8840 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8841 N0.getOperand(0).getOperand(2) };
8842 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8849 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8850 SDValue N0 = N->getOperand(0);
8851 EVT VT = N->getValueType(0);
8852 EVT OpVT = N0.getValueType();
8854 // fold (uint_to_fp c1) -> c1fp
8855 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8856 // ...but only if the target supports immediate floating-point values
8857 (!LegalOperations ||
8858 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8859 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8861 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8862 // but SINT_TO_FP is legal on this target, try to convert.
8863 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8864 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8865 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8866 if (DAG.SignBitIsZero(N0))
8867 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8870 // The next optimizations are desirable only if SELECT_CC can be lowered.
8871 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8872 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8874 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8875 (!LegalOperations ||
8876 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8879 { N0.getOperand(0), N0.getOperand(1),
8880 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8882 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8889 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8890 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8891 SDValue N0 = N->getOperand(0);
8892 EVT VT = N->getValueType(0);
8894 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8897 SDValue Src = N0.getOperand(0);
8898 EVT SrcVT = Src.getValueType();
8899 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8900 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8902 // We can safely assume the conversion won't overflow the output range,
8903 // because (for example) (uint8_t)18293.f is undefined behavior.
8905 // Since we can assume the conversion won't overflow, our decision as to
8906 // whether the input will fit in the float should depend on the minimum
8907 // of the input range and output range.
8909 // This means this is also safe for a signed input and unsigned output, since
8910 // a negative input would lead to undefined behavior.
8911 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8912 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8913 unsigned ActualSize = std::min(InputSize, OutputSize);
8914 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8916 // We can only fold away the float conversion if the input range can be
8917 // represented exactly in the float range.
8918 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8919 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8920 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8922 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8924 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8925 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8928 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8933 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8934 SDValue N0 = N->getOperand(0);
8935 EVT VT = N->getValueType(0);
8937 // fold (fp_to_sint c1fp) -> c1
8938 if (isConstantFPBuildVectorOrConstantFP(N0))
8939 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8941 return FoldIntToFPToInt(N, DAG);
8944 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8945 SDValue N0 = N->getOperand(0);
8946 EVT VT = N->getValueType(0);
8948 // fold (fp_to_uint c1fp) -> c1
8949 if (isConstantFPBuildVectorOrConstantFP(N0))
8950 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8952 return FoldIntToFPToInt(N, DAG);
8955 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8956 SDValue N0 = N->getOperand(0);
8957 SDValue N1 = N->getOperand(1);
8958 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8959 EVT VT = N->getValueType(0);
8961 // fold (fp_round c1fp) -> c1fp
8963 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8965 // fold (fp_round (fp_extend x)) -> x
8966 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8967 return N0.getOperand(0);
8969 // fold (fp_round (fp_round x)) -> (fp_round x)
8970 if (N0.getOpcode() == ISD::FP_ROUND) {
8971 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8972 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8973 // If the first fp_round isn't a value preserving truncation, it might
8974 // introduce a tie in the second fp_round, that wouldn't occur in the
8975 // single-step fp_round we want to fold to.
8976 // In other words, double rounding isn't the same as rounding.
8977 // Also, this is a value preserving truncation iff both fp_round's are.
8978 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8980 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8981 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8985 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8986 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8987 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8988 N0.getOperand(0), N1);
8989 AddToWorklist(Tmp.getNode());
8990 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8991 Tmp, N0.getOperand(1));
8997 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8998 SDValue N0 = N->getOperand(0);
8999 EVT VT = N->getValueType(0);
9000 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
9001 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9003 // fold (fp_round_inreg c1fp) -> c1fp
9004 if (N0CFP && isTypeLegal(EVT)) {
9006 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
9007 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
9013 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
9014 SDValue N0 = N->getOperand(0);
9015 EVT VT = N->getValueType(0);
9017 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
9018 if (N->hasOneUse() &&
9019 N->use_begin()->getOpcode() == ISD::FP_ROUND)
9022 // fold (fp_extend c1fp) -> c1fp
9023 if (isConstantFPBuildVectorOrConstantFP(N0))
9024 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
9026 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
9027 if (N0.getOpcode() == ISD::FP16_TO_FP &&
9028 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
9029 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
9031 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
9033 if (N0.getOpcode() == ISD::FP_ROUND
9034 && N0.getNode()->getConstantOperandVal(1) == 1) {
9035 SDValue In = N0.getOperand(0);
9036 if (In.getValueType() == VT) return In;
9037 if (VT.bitsLT(In.getValueType()))
9038 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
9039 In, N0.getOperand(1));
9040 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
9043 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
9044 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9045 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
9046 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9047 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
9049 LN0->getBasePtr(), N0.getValueType(),
9050 LN0->getMemOperand());
9051 CombineTo(N, ExtLoad);
9052 CombineTo(N0.getNode(),
9053 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
9054 N0.getValueType(), ExtLoad,
9055 DAG.getIntPtrConstant(1, SDLoc(N0))),
9056 ExtLoad.getValue(1));
9057 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9063 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
9064 SDValue N0 = N->getOperand(0);
9065 EVT VT = N->getValueType(0);
9067 // fold (fceil c1) -> fceil(c1)
9068 if (isConstantFPBuildVectorOrConstantFP(N0))
9069 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
9074 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
9075 SDValue N0 = N->getOperand(0);
9076 EVT VT = N->getValueType(0);
9078 // fold (ftrunc c1) -> ftrunc(c1)
9079 if (isConstantFPBuildVectorOrConstantFP(N0))
9080 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
9085 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
9086 SDValue N0 = N->getOperand(0);
9087 EVT VT = N->getValueType(0);
9089 // fold (ffloor c1) -> ffloor(c1)
9090 if (isConstantFPBuildVectorOrConstantFP(N0))
9091 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
9096 // FIXME: FNEG and FABS have a lot in common; refactor.
9097 SDValue DAGCombiner::visitFNEG(SDNode *N) {
9098 SDValue N0 = N->getOperand(0);
9099 EVT VT = N->getValueType(0);
9101 // Constant fold FNEG.
9102 if (isConstantFPBuildVectorOrConstantFP(N0))
9103 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
9105 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
9106 &DAG.getTarget().Options))
9107 return GetNegatedExpression(N0, DAG, LegalOperations);
9109 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
9110 // constant pool values.
9111 if (!TLI.isFNegFree(VT) &&
9112 N0.getOpcode() == ISD::BITCAST &&
9113 N0.getNode()->hasOneUse()) {
9114 SDValue Int = N0.getOperand(0);
9115 EVT IntVT = Int.getValueType();
9116 if (IntVT.isInteger() && !IntVT.isVector()) {
9118 if (N0.getValueType().isVector()) {
9119 // For a vector, get a mask such as 0x80... per scalar element
9121 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9122 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9124 // For a scalar, just generate 0x80...
9125 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
9128 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9129 DAG.getConstant(SignMask, DL0, IntVT));
9130 AddToWorklist(Int.getNode());
9131 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
9135 // (fneg (fmul c, x)) -> (fmul -c, x)
9136 if (N0.getOpcode() == ISD::FMUL &&
9137 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9138 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9140 APFloat CVal = CFP1->getValueAPF();
9142 if (Level >= AfterLegalizeDAG &&
9143 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
9144 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
9145 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9146 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9148 &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9155 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
9156 SDValue N0 = N->getOperand(0);
9157 SDValue N1 = N->getOperand(1);
9158 EVT VT = N->getValueType(0);
9159 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9160 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9162 if (N0CFP && N1CFP) {
9163 const APFloat &C0 = N0CFP->getValueAPF();
9164 const APFloat &C1 = N1CFP->getValueAPF();
9165 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9168 // Canonicalize to constant on RHS.
9169 if (isConstantFPBuildVectorOrConstantFP(N0) &&
9170 !isConstantFPBuildVectorOrConstantFP(N1))
9171 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9176 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9177 SDValue N0 = N->getOperand(0);
9178 SDValue N1 = N->getOperand(1);
9179 EVT VT = N->getValueType(0);
9180 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9181 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9183 if (N0CFP && N1CFP) {
9184 const APFloat &C0 = N0CFP->getValueAPF();
9185 const APFloat &C1 = N1CFP->getValueAPF();
9186 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9189 // Canonicalize to constant on RHS.
9190 if (isConstantFPBuildVectorOrConstantFP(N0) &&
9191 !isConstantFPBuildVectorOrConstantFP(N1))
9192 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9197 SDValue DAGCombiner::visitFABS(SDNode *N) {
9198 SDValue N0 = N->getOperand(0);
9199 EVT VT = N->getValueType(0);
9201 // fold (fabs c1) -> fabs(c1)
9202 if (isConstantFPBuildVectorOrConstantFP(N0))
9203 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9205 // fold (fabs (fabs x)) -> (fabs x)
9206 if (N0.getOpcode() == ISD::FABS)
9207 return N->getOperand(0);
9209 // fold (fabs (fneg x)) -> (fabs x)
9210 // fold (fabs (fcopysign x, y)) -> (fabs x)
9211 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9212 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9214 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9215 // constant pool values.
9216 if (!TLI.isFAbsFree(VT) &&
9217 N0.getOpcode() == ISD::BITCAST &&
9218 N0.getNode()->hasOneUse()) {
9219 SDValue Int = N0.getOperand(0);
9220 EVT IntVT = Int.getValueType();
9221 if (IntVT.isInteger() && !IntVT.isVector()) {
9223 if (N0.getValueType().isVector()) {
9224 // For a vector, get a mask such as 0x7f... per scalar element
9226 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9227 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9229 // For a scalar, just generate 0x7f...
9230 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9233 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9234 DAG.getConstant(SignMask, DL, IntVT));
9235 AddToWorklist(Int.getNode());
9236 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
9243 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9244 SDValue Chain = N->getOperand(0);
9245 SDValue N1 = N->getOperand(1);
9246 SDValue N2 = N->getOperand(2);
9248 // If N is a constant we could fold this into a fallthrough or unconditional
9249 // branch. However that doesn't happen very often in normal code, because
9250 // Instcombine/SimplifyCFG should have handled the available opportunities.
9251 // If we did this folding here, it would be necessary to update the
9252 // MachineBasicBlock CFG, which is awkward.
9254 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9256 if (N1.getOpcode() == ISD::SETCC &&
9257 TLI.isOperationLegalOrCustom(ISD::BR_CC,
9258 N1.getOperand(0).getValueType())) {
9259 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9260 Chain, N1.getOperand(2),
9261 N1.getOperand(0), N1.getOperand(1), N2);
9264 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9265 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9266 (N1.getOperand(0).hasOneUse() &&
9267 N1.getOperand(0).getOpcode() == ISD::SRL))) {
9268 SDNode *Trunc = nullptr;
9269 if (N1.getOpcode() == ISD::TRUNCATE) {
9270 // Look pass the truncate.
9271 Trunc = N1.getNode();
9272 N1 = N1.getOperand(0);
9275 // Match this pattern so that we can generate simpler code:
9278 // %b = and i32 %a, 2
9279 // %c = srl i32 %b, 1
9280 // brcond i32 %c ...
9285 // %b = and i32 %a, 2
9286 // %c = setcc eq %b, 0
9289 // This applies only when the AND constant value has one bit set and the
9290 // SRL constant is equal to the log2 of the AND constant. The back-end is
9291 // smart enough to convert the result into a TEST/JMP sequence.
9292 SDValue Op0 = N1.getOperand(0);
9293 SDValue Op1 = N1.getOperand(1);
9295 if (Op0.getOpcode() == ISD::AND &&
9296 Op1.getOpcode() == ISD::Constant) {
9297 SDValue AndOp1 = Op0.getOperand(1);
9299 if (AndOp1.getOpcode() == ISD::Constant) {
9300 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9302 if (AndConst.isPowerOf2() &&
9303 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9307 getSetCCResultType(Op0.getValueType()),
9308 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9311 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9312 MVT::Other, Chain, SetCC, N2);
9313 // Don't add the new BRCond into the worklist or else SimplifySelectCC
9314 // will convert it back to (X & C1) >> C2.
9315 CombineTo(N, NewBRCond, false);
9316 // Truncate is dead.
9318 deleteAndRecombine(Trunc);
9319 // Replace the uses of SRL with SETCC
9320 WorklistRemover DeadNodes(*this);
9321 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9322 deleteAndRecombine(N1.getNode());
9323 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9329 // Restore N1 if the above transformation doesn't match.
9330 N1 = N->getOperand(1);
9333 // Transform br(xor(x, y)) -> br(x != y)
9334 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9335 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9336 SDNode *TheXor = N1.getNode();
9337 SDValue Op0 = TheXor->getOperand(0);
9338 SDValue Op1 = TheXor->getOperand(1);
9339 if (Op0.getOpcode() == Op1.getOpcode()) {
9340 // Avoid missing important xor optimizations.
9341 if (SDValue Tmp = visitXOR(TheXor)) {
9342 if (Tmp.getNode() != TheXor) {
9343 DEBUG(dbgs() << "\nReplacing.8 ";
9345 dbgs() << "\nWith: ";
9346 Tmp.getNode()->dump(&DAG);
9348 WorklistRemover DeadNodes(*this);
9349 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9350 deleteAndRecombine(TheXor);
9351 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9352 MVT::Other, Chain, Tmp, N2);
9355 // visitXOR has changed XOR's operands or replaced the XOR completely,
9357 return SDValue(N, 0);
9361 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9363 if (isOneConstant(Op0) && Op0.hasOneUse() &&
9364 Op0.getOpcode() == ISD::XOR) {
9365 TheXor = Op0.getNode();
9369 EVT SetCCVT = N1.getValueType();
9371 SetCCVT = getSetCCResultType(SetCCVT);
9372 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9375 Equal ? ISD::SETEQ : ISD::SETNE);
9376 // Replace the uses of XOR with SETCC
9377 WorklistRemover DeadNodes(*this);
9378 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9379 deleteAndRecombine(N1.getNode());
9380 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9381 MVT::Other, Chain, SetCC, N2);
9388 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9390 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9391 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9392 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9394 // If N is a constant we could fold this into a fallthrough or unconditional
9395 // branch. However that doesn't happen very often in normal code, because
9396 // Instcombine/SimplifyCFG should have handled the available opportunities.
9397 // If we did this folding here, it would be necessary to update the
9398 // MachineBasicBlock CFG, which is awkward.
9400 // Use SimplifySetCC to simplify SETCC's.
9401 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9402 CondLHS, CondRHS, CC->get(), SDLoc(N),
9404 if (Simp.getNode()) AddToWorklist(Simp.getNode());
9406 // fold to a simpler setcc
9407 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9408 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9409 N->getOperand(0), Simp.getOperand(2),
9410 Simp.getOperand(0), Simp.getOperand(1),
9416 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9417 /// and that N may be folded in the load / store addressing mode.
9418 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9420 const TargetLowering &TLI) {
9424 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
9425 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9427 VT = LD->getMemoryVT();
9428 AS = LD->getAddressSpace();
9429 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
9430 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9432 VT = ST->getMemoryVT();
9433 AS = ST->getAddressSpace();
9437 TargetLowering::AddrMode AM;
9438 if (N->getOpcode() == ISD::ADD) {
9439 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9442 AM.BaseOffs = Offset->getSExtValue();
9446 } else if (N->getOpcode() == ISD::SUB) {
9447 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9450 AM.BaseOffs = -Offset->getSExtValue();
9457 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9458 VT.getTypeForEVT(*DAG.getContext()), AS);
9461 /// Try turning a load/store into a pre-indexed load/store when the base
9462 /// pointer is an add or subtract and it has other uses besides the load/store.
9463 /// After the transformation, the new indexed load/store has effectively folded
9464 /// the add/subtract in and all of its other uses are redirected to the
9466 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9467 if (Level < AfterLegalizeDAG)
9473 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9474 if (LD->isIndexed())
9476 VT = LD->getMemoryVT();
9477 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9478 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9480 Ptr = LD->getBasePtr();
9481 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9482 if (ST->isIndexed())
9484 VT = ST->getMemoryVT();
9485 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9486 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9488 Ptr = ST->getBasePtr();
9494 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9495 // out. There is no reason to make this a preinc/predec.
9496 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9497 Ptr.getNode()->hasOneUse())
9500 // Ask the target to do addressing mode selection.
9503 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9504 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9507 // Backends without true r+i pre-indexed forms may need to pass a
9508 // constant base with a variable offset so that constant coercion
9509 // will work with the patterns in canonical form.
9510 bool Swapped = false;
9511 if (isa<ConstantSDNode>(BasePtr)) {
9512 std::swap(BasePtr, Offset);
9516 // Don't create a indexed load / store with zero offset.
9517 if (isNullConstant(Offset))
9520 // Try turning it into a pre-indexed load / store except when:
9521 // 1) The new base ptr is a frame index.
9522 // 2) If N is a store and the new base ptr is either the same as or is a
9523 // predecessor of the value being stored.
9524 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9525 // that would create a cycle.
9526 // 4) All uses are load / store ops that use it as old base ptr.
9528 // Check #1. Preinc'ing a frame index would require copying the stack pointer
9529 // (plus the implicit offset) to a register to preinc anyway.
9530 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9535 SDValue Val = cast<StoreSDNode>(N)->getValue();
9536 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9540 // If the offset is a constant, there may be other adds of constants that
9541 // can be folded with this one. We should do this to avoid having to keep
9542 // a copy of the original base pointer.
9543 SmallVector<SDNode *, 16> OtherUses;
9544 if (isa<ConstantSDNode>(Offset))
9545 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9546 UE = BasePtr.getNode()->use_end();
9548 SDUse &Use = UI.getUse();
9549 // Skip the use that is Ptr and uses of other results from BasePtr's
9550 // node (important for nodes that return multiple results).
9551 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9554 if (Use.getUser()->isPredecessorOf(N))
9557 if (Use.getUser()->getOpcode() != ISD::ADD &&
9558 Use.getUser()->getOpcode() != ISD::SUB) {
9563 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9564 if (!isa<ConstantSDNode>(Op1)) {
9569 // FIXME: In some cases, we can be smarter about this.
9570 if (Op1.getValueType() != Offset.getValueType()) {
9575 OtherUses.push_back(Use.getUser());
9579 std::swap(BasePtr, Offset);
9581 // Now check for #3 and #4.
9582 bool RealUse = false;
9584 // Caches for hasPredecessorHelper
9585 SmallPtrSet<const SDNode *, 32> Visited;
9586 SmallVector<const SDNode *, 16> Worklist;
9588 for (SDNode *Use : Ptr.getNode()->uses()) {
9591 if (N->hasPredecessorHelper(Use, Visited, Worklist))
9594 // If Ptr may be folded in addressing mode of other use, then it's
9595 // not profitable to do this transformation.
9596 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9605 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9606 BasePtr, Offset, AM);
9608 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9609 BasePtr, Offset, AM);
9612 DEBUG(dbgs() << "\nReplacing.4 ";
9614 dbgs() << "\nWith: ";
9615 Result.getNode()->dump(&DAG);
9617 WorklistRemover DeadNodes(*this);
9619 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9620 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9622 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9625 // Finally, since the node is now dead, remove it from the graph.
9626 deleteAndRecombine(N);
9629 std::swap(BasePtr, Offset);
9631 // Replace other uses of BasePtr that can be updated to use Ptr
9632 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9633 unsigned OffsetIdx = 1;
9634 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9636 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9637 BasePtr.getNode() && "Expected BasePtr operand");
9639 // We need to replace ptr0 in the following expression:
9640 // x0 * offset0 + y0 * ptr0 = t0
9642 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9644 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9645 // indexed load/store and the expresion that needs to be re-written.
9647 // Therefore, we have:
9648 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9650 ConstantSDNode *CN =
9651 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9653 APInt Offset0 = CN->getAPIntValue();
9654 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9656 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9657 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9658 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9659 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9661 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9663 APInt CNV = Offset0;
9664 if (X0 < 0) CNV = -CNV;
9665 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9666 else CNV = CNV - Offset1;
9668 SDLoc DL(OtherUses[i]);
9670 // We can now generate the new expression.
9671 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9672 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9674 SDValue NewUse = DAG.getNode(Opcode,
9676 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9677 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9678 deleteAndRecombine(OtherUses[i]);
9681 // Replace the uses of Ptr with uses of the updated base value.
9682 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9683 deleteAndRecombine(Ptr.getNode());
9688 /// Try to combine a load/store with a add/sub of the base pointer node into a
9689 /// post-indexed load/store. The transformation folded the add/subtract into the
9690 /// new indexed load/store effectively and all of its uses are redirected to the
9692 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9693 if (Level < AfterLegalizeDAG)
9699 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9700 if (LD->isIndexed())
9702 VT = LD->getMemoryVT();
9703 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9704 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9706 Ptr = LD->getBasePtr();
9707 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9708 if (ST->isIndexed())
9710 VT = ST->getMemoryVT();
9711 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9712 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9714 Ptr = ST->getBasePtr();
9720 if (Ptr.getNode()->hasOneUse())
9723 for (SDNode *Op : Ptr.getNode()->uses()) {
9725 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9730 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9731 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9732 // Don't create a indexed load / store with zero offset.
9733 if (isNullConstant(Offset))
9736 // Try turning it into a post-indexed load / store except when
9737 // 1) All uses are load / store ops that use it as base ptr (and
9738 // it may be folded as addressing mmode).
9739 // 2) Op must be independent of N, i.e. Op is neither a predecessor
9740 // nor a successor of N. Otherwise, if Op is folded that would
9743 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9747 bool TryNext = false;
9748 for (SDNode *Use : BasePtr.getNode()->uses()) {
9749 if (Use == Ptr.getNode())
9752 // If all the uses are load / store addresses, then don't do the
9754 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9755 bool RealUse = false;
9756 for (SDNode *UseUse : Use->uses()) {
9757 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9772 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9773 SDValue Result = isLoad
9774 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9775 BasePtr, Offset, AM)
9776 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9777 BasePtr, Offset, AM);
9780 DEBUG(dbgs() << "\nReplacing.5 ";
9782 dbgs() << "\nWith: ";
9783 Result.getNode()->dump(&DAG);
9785 WorklistRemover DeadNodes(*this);
9787 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9788 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9790 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9793 // Finally, since the node is now dead, remove it from the graph.
9794 deleteAndRecombine(N);
9796 // Replace the uses of Use with uses of the updated base value.
9797 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9798 Result.getValue(isLoad ? 1 : 0));
9799 deleteAndRecombine(Op);
9808 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9809 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9810 ISD::MemIndexedMode AM = LD->getAddressingMode();
9811 assert(AM != ISD::UNINDEXED);
9812 SDValue BP = LD->getOperand(1);
9813 SDValue Inc = LD->getOperand(2);
9815 // Some backends use TargetConstants for load offsets, but don't expect
9816 // TargetConstants in general ADD nodes. We can convert these constants into
9817 // regular Constants (if the constant is not opaque).
9818 assert((Inc.getOpcode() != ISD::TargetConstant ||
9819 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9820 "Cannot split out indexing using opaque target constants");
9821 if (Inc.getOpcode() == ISD::TargetConstant) {
9822 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9823 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9824 ConstInc->getValueType(0));
9828 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9829 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9832 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9833 LoadSDNode *LD = cast<LoadSDNode>(N);
9834 SDValue Chain = LD->getChain();
9835 SDValue Ptr = LD->getBasePtr();
9837 // If load is not volatile and there are no uses of the loaded value (and
9838 // the updated indexed value in case of indexed loads), change uses of the
9839 // chain value into uses of the chain input (i.e. delete the dead load).
9840 if (!LD->isVolatile()) {
9841 if (N->getValueType(1) == MVT::Other) {
9843 if (!N->hasAnyUseOfValue(0)) {
9844 // It's not safe to use the two value CombineTo variant here. e.g.
9845 // v1, chain2 = load chain1, loc
9846 // v2, chain3 = load chain2, loc
9848 // Now we replace use of chain2 with chain1. This makes the second load
9849 // isomorphic to the one we are deleting, and thus makes this load live.
9850 DEBUG(dbgs() << "\nReplacing.6 ";
9852 dbgs() << "\nWith chain: ";
9853 Chain.getNode()->dump(&DAG);
9855 WorklistRemover DeadNodes(*this);
9856 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9859 deleteAndRecombine(N);
9861 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9865 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9867 // If this load has an opaque TargetConstant offset, then we cannot split
9868 // the indexing into an add/sub directly (that TargetConstant may not be
9869 // valid for a different type of node, and we cannot convert an opaque
9870 // target constant into a regular constant).
9871 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9872 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9874 if (!N->hasAnyUseOfValue(0) &&
9875 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9876 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9878 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9879 Index = SplitIndexingFromLoad(LD);
9880 // Try to fold the base pointer arithmetic into subsequent loads and
9882 AddUsersToWorklist(N);
9884 Index = DAG.getUNDEF(N->getValueType(1));
9885 DEBUG(dbgs() << "\nReplacing.7 ";
9887 dbgs() << "\nWith: ";
9888 Undef.getNode()->dump(&DAG);
9889 dbgs() << " and 2 other values\n");
9890 WorklistRemover DeadNodes(*this);
9891 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9892 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9893 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9894 deleteAndRecombine(N);
9895 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9900 // If this load is directly stored, replace the load value with the stored
9902 // TODO: Handle store large -> read small portion.
9903 // TODO: Handle TRUNCSTORE/LOADEXT
9904 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9905 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9906 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9907 if (PrevST->getBasePtr() == Ptr &&
9908 PrevST->getValue().getValueType() == N->getValueType(0))
9909 return CombineTo(N, Chain.getOperand(1), Chain);
9913 // Try to infer better alignment information than the load already has.
9914 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9915 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9916 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9918 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9919 LD->getValueType(0),
9920 Chain, Ptr, LD->getPointerInfo(),
9922 LD->isVolatile(), LD->isNonTemporal(),
9923 LD->isInvariant(), Align, LD->getAAInfo());
9924 if (NewLoad.getNode() != N)
9925 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9930 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9931 : DAG.getSubtarget().useAA();
9933 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9934 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9937 if (UseAA && LD->isUnindexed()) {
9938 // Walk up chain skipping non-aliasing memory nodes.
9939 SDValue BetterChain = FindBetterChain(N, Chain);
9941 // If there is a better chain.
9942 if (Chain != BetterChain) {
9945 // Replace the chain to void dependency.
9946 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9947 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9948 BetterChain, Ptr, LD->getMemOperand());
9950 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9951 LD->getValueType(0),
9952 BetterChain, Ptr, LD->getMemoryVT(),
9953 LD->getMemOperand());
9956 // Create token factor to keep old chain connected.
9957 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9958 MVT::Other, Chain, ReplLoad.getValue(1));
9960 // Make sure the new and old chains are cleaned up.
9961 AddToWorklist(Token.getNode());
9963 // Replace uses with load result and token factor. Don't add users
9965 return CombineTo(N, ReplLoad.getValue(0), Token, false);
9969 // Try transforming N to an indexed load.
9970 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9971 return SDValue(N, 0);
9973 // Try to slice up N to more direct loads if the slices are mapped to
9974 // different register banks or pairing can take place.
9976 return SDValue(N, 0);
9982 /// \brief Helper structure used to slice a load in smaller loads.
9983 /// Basically a slice is obtained from the following sequence:
9984 /// Origin = load Ty1, Base
9985 /// Shift = srl Ty1 Origin, CstTy Amount
9986 /// Inst = trunc Shift to Ty2
9988 /// Then, it will be rewriten into:
9989 /// Slice = load SliceTy, Base + SliceOffset
9990 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9992 /// SliceTy is deduced from the number of bits that are actually used to
9994 struct LoadedSlice {
9995 /// \brief Helper structure used to compute the cost of a slice.
9997 /// Are we optimizing for code size.
10001 unsigned Truncates;
10002 unsigned CrossRegisterBanksCopies;
10006 Cost(bool ForCodeSize = false)
10007 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
10008 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
10010 /// \brief Get the cost of one isolated slice.
10011 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
10012 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
10013 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
10014 EVT TruncType = LS.Inst->getValueType(0);
10015 EVT LoadedType = LS.getLoadedType();
10016 if (TruncType != LoadedType &&
10017 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
10021 /// \brief Account for slicing gain in the current cost.
10022 /// Slicing provide a few gains like removing a shift or a
10023 /// truncate. This method allows to grow the cost of the original
10024 /// load with the gain from this slice.
10025 void addSliceGain(const LoadedSlice &LS) {
10026 // Each slice saves a truncate.
10027 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
10028 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
10029 LS.Inst->getValueType(0)))
10031 // If there is a shift amount, this slice gets rid of it.
10034 // If this slice can merge a cross register bank copy, account for it.
10035 if (LS.canMergeExpensiveCrossRegisterBankCopy())
10036 ++CrossRegisterBanksCopies;
10039 Cost &operator+=(const Cost &RHS) {
10040 Loads += RHS.Loads;
10041 Truncates += RHS.Truncates;
10042 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
10043 ZExts += RHS.ZExts;
10044 Shift += RHS.Shift;
10048 bool operator==(const Cost &RHS) const {
10049 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
10050 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
10051 ZExts == RHS.ZExts && Shift == RHS.Shift;
10054 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
10056 bool operator<(const Cost &RHS) const {
10057 // Assume cross register banks copies are as expensive as loads.
10058 // FIXME: Do we want some more target hooks?
10059 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
10060 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
10061 // Unless we are optimizing for code size, consider the
10062 // expensive operation first.
10063 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
10064 return ExpensiveOpsLHS < ExpensiveOpsRHS;
10065 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
10066 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
10069 bool operator>(const Cost &RHS) const { return RHS < *this; }
10071 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
10073 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
10075 // The last instruction that represent the slice. This should be a
10076 // truncate instruction.
10078 // The original load instruction.
10079 LoadSDNode *Origin;
10080 // The right shift amount in bits from the original load.
10082 // The DAG from which Origin came from.
10083 // This is used to get some contextual information about legal types, etc.
10086 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
10087 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
10088 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
10090 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
10091 /// \return Result is \p BitWidth and has used bits set to 1 and
10092 /// not used bits set to 0.
10093 APInt getUsedBits() const {
10094 // Reproduce the trunc(lshr) sequence:
10095 // - Start from the truncated value.
10096 // - Zero extend to the desired bit width.
10098 assert(Origin && "No original load to compare against.");
10099 unsigned BitWidth = Origin->getValueSizeInBits(0);
10100 assert(Inst && "This slice is not bound to an instruction");
10101 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
10102 "Extracted slice is bigger than the whole type!");
10103 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
10104 UsedBits.setAllBits();
10105 UsedBits = UsedBits.zext(BitWidth);
10106 UsedBits <<= Shift;
10110 /// \brief Get the size of the slice to be loaded in bytes.
10111 unsigned getLoadedSize() const {
10112 unsigned SliceSize = getUsedBits().countPopulation();
10113 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
10114 return SliceSize / 8;
10117 /// \brief Get the type that will be loaded for this slice.
10118 /// Note: This may not be the final type for the slice.
10119 EVT getLoadedType() const {
10120 assert(DAG && "Missing context");
10121 LLVMContext &Ctxt = *DAG->getContext();
10122 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
10125 /// \brief Get the alignment of the load used for this slice.
10126 unsigned getAlignment() const {
10127 unsigned Alignment = Origin->getAlignment();
10128 unsigned Offset = getOffsetFromBase();
10130 Alignment = MinAlign(Alignment, Alignment + Offset);
10134 /// \brief Check if this slice can be rewritten with legal operations.
10135 bool isLegal() const {
10136 // An invalid slice is not legal.
10137 if (!Origin || !Inst || !DAG)
10140 // Offsets are for indexed load only, we do not handle that.
10141 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
10144 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10146 // Check that the type is legal.
10147 EVT SliceType = getLoadedType();
10148 if (!TLI.isTypeLegal(SliceType))
10151 // Check that the load is legal for this type.
10152 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10155 // Check that the offset can be computed.
10156 // 1. Check its type.
10157 EVT PtrType = Origin->getBasePtr().getValueType();
10158 if (PtrType == MVT::Untyped || PtrType.isExtended())
10161 // 2. Check that it fits in the immediate.
10162 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10165 // 3. Check that the computation is legal.
10166 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10169 // Check that the zext is legal if it needs one.
10170 EVT TruncateType = Inst->getValueType(0);
10171 if (TruncateType != SliceType &&
10172 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10178 /// \brief Get the offset in bytes of this slice in the original chunk of
10180 /// \pre DAG != nullptr.
10181 uint64_t getOffsetFromBase() const {
10182 assert(DAG && "Missing context.");
10183 bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10184 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10185 uint64_t Offset = Shift / 8;
10186 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10187 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10188 "The size of the original loaded type is not a multiple of a"
10190 // If Offset is bigger than TySizeInBytes, it means we are loading all
10191 // zeros. This should have been optimized before in the process.
10192 assert(TySizeInBytes > Offset &&
10193 "Invalid shift amount for given loaded size");
10195 Offset = TySizeInBytes - Offset - getLoadedSize();
10199 /// \brief Generate the sequence of instructions to load the slice
10200 /// represented by this object and redirect the uses of this slice to
10201 /// this new sequence of instructions.
10202 /// \pre this->Inst && this->Origin are valid Instructions and this
10203 /// object passed the legal check: LoadedSlice::isLegal returned true.
10204 /// \return The last instruction of the sequence used to load the slice.
10205 SDValue loadSlice() const {
10206 assert(Inst && Origin && "Unable to replace a non-existing slice.");
10207 const SDValue &OldBaseAddr = Origin->getBasePtr();
10208 SDValue BaseAddr = OldBaseAddr;
10209 // Get the offset in that chunk of bytes w.r.t. the endianess.
10210 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10211 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10213 // BaseAddr = BaseAddr + Offset.
10214 EVT ArithType = BaseAddr.getValueType();
10216 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10217 DAG->getConstant(Offset, DL, ArithType));
10220 // Create the type of the loaded slice according to its size.
10221 EVT SliceType = getLoadedType();
10223 // Create the load for the slice.
10224 SDValue LastInst = DAG->getLoad(
10225 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10226 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
10227 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
10228 // If the final type is not the same as the loaded type, this means that
10229 // we have to pad with zero. Create a zero extend for that.
10230 EVT FinalType = Inst->getValueType(0);
10231 if (SliceType != FinalType)
10233 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10237 /// \brief Check if this slice can be merged with an expensive cross register
10238 /// bank copy. E.g.,
10240 /// f = bitcast i32 i to float
10241 bool canMergeExpensiveCrossRegisterBankCopy() const {
10242 if (!Inst || !Inst->hasOneUse())
10244 SDNode *Use = *Inst->use_begin();
10245 if (Use->getOpcode() != ISD::BITCAST)
10247 assert(DAG && "Missing context");
10248 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10249 EVT ResVT = Use->getValueType(0);
10250 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10251 const TargetRegisterClass *ArgRC =
10252 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10253 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10256 // At this point, we know that we perform a cross-register-bank copy.
10257 // Check if it is expensive.
10258 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10259 // Assume bitcasts are cheap, unless both register classes do not
10260 // explicitly share a common sub class.
10261 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10264 // Check if it will be merged with the load.
10265 // 1. Check the alignment constraint.
10266 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10267 ResVT.getTypeForEVT(*DAG->getContext()));
10269 if (RequiredAlignment > getAlignment())
10272 // 2. Check that the load is a legal operation for that type.
10273 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10276 // 3. Check that we do not have a zext in the way.
10277 if (Inst->getValueType(0) != getLoadedType())
10285 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10286 /// \p UsedBits looks like 0..0 1..1 0..0.
10287 static bool areUsedBitsDense(const APInt &UsedBits) {
10288 // If all the bits are one, this is dense!
10289 if (UsedBits.isAllOnesValue())
10292 // Get rid of the unused bits on the right.
10293 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10294 // Get rid of the unused bits on the left.
10295 if (NarrowedUsedBits.countLeadingZeros())
10296 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10297 // Check that the chunk of bits is completely used.
10298 return NarrowedUsedBits.isAllOnesValue();
10301 /// \brief Check whether or not \p First and \p Second are next to each other
10302 /// in memory. This means that there is no hole between the bits loaded
10303 /// by \p First and the bits loaded by \p Second.
10304 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10305 const LoadedSlice &Second) {
10306 assert(First.Origin == Second.Origin && First.Origin &&
10307 "Unable to match different memory origins.");
10308 APInt UsedBits = First.getUsedBits();
10309 assert((UsedBits & Second.getUsedBits()) == 0 &&
10310 "Slices are not supposed to overlap.");
10311 UsedBits |= Second.getUsedBits();
10312 return areUsedBitsDense(UsedBits);
10315 /// \brief Adjust the \p GlobalLSCost according to the target
10316 /// paring capabilities and the layout of the slices.
10317 /// \pre \p GlobalLSCost should account for at least as many loads as
10318 /// there is in the slices in \p LoadedSlices.
10319 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10320 LoadedSlice::Cost &GlobalLSCost) {
10321 unsigned NumberOfSlices = LoadedSlices.size();
10322 // If there is less than 2 elements, no pairing is possible.
10323 if (NumberOfSlices < 2)
10326 // Sort the slices so that elements that are likely to be next to each
10327 // other in memory are next to each other in the list.
10328 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10329 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10330 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10331 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10333 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10334 // First (resp. Second) is the first (resp. Second) potentially candidate
10335 // to be placed in a paired load.
10336 const LoadedSlice *First = nullptr;
10337 const LoadedSlice *Second = nullptr;
10338 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10339 // Set the beginning of the pair.
10342 Second = &LoadedSlices[CurrSlice];
10344 // If First is NULL, it means we start a new pair.
10345 // Get to the next slice.
10349 EVT LoadedType = First->getLoadedType();
10351 // If the types of the slices are different, we cannot pair them.
10352 if (LoadedType != Second->getLoadedType())
10355 // Check if the target supplies paired loads for this type.
10356 unsigned RequiredAlignment = 0;
10357 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10358 // move to the next pair, this type is hopeless.
10362 // Check if we meet the alignment requirement.
10363 if (RequiredAlignment > First->getAlignment())
10366 // Check that both loads are next to each other in memory.
10367 if (!areSlicesNextToEachOther(*First, *Second))
10370 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10371 --GlobalLSCost.Loads;
10372 // Move to the next pair.
10377 /// \brief Check the profitability of all involved LoadedSlice.
10378 /// Currently, it is considered profitable if there is exactly two
10379 /// involved slices (1) which are (2) next to each other in memory, and
10380 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10382 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10383 /// the elements themselves.
10385 /// FIXME: When the cost model will be mature enough, we can relax
10386 /// constraints (1) and (2).
10387 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10388 const APInt &UsedBits, bool ForCodeSize) {
10389 unsigned NumberOfSlices = LoadedSlices.size();
10390 if (StressLoadSlicing)
10391 return NumberOfSlices > 1;
10394 if (NumberOfSlices != 2)
10398 if (!areUsedBitsDense(UsedBits))
10402 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10403 // The original code has one big load.
10404 OrigCost.Loads = 1;
10405 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10406 const LoadedSlice &LS = LoadedSlices[CurrSlice];
10407 // Accumulate the cost of all the slices.
10408 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10409 GlobalSlicingCost += SliceCost;
10411 // Account as cost in the original configuration the gain obtained
10412 // with the current slices.
10413 OrigCost.addSliceGain(LS);
10416 // If the target supports paired load, adjust the cost accordingly.
10417 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10418 return OrigCost > GlobalSlicingCost;
10421 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10422 /// operations, split it in the various pieces being extracted.
10424 /// This sort of thing is introduced by SROA.
10425 /// This slicing takes care not to insert overlapping loads.
10426 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10427 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10428 if (Level < AfterLegalizeDAG)
10431 LoadSDNode *LD = cast<LoadSDNode>(N);
10432 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10433 !LD->getValueType(0).isInteger())
10436 // Keep track of already used bits to detect overlapping values.
10437 // In that case, we will just abort the transformation.
10438 APInt UsedBits(LD->getValueSizeInBits(0), 0);
10440 SmallVector<LoadedSlice, 4> LoadedSlices;
10442 // Check if this load is used as several smaller chunks of bits.
10443 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10444 // of computation for each trunc.
10445 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10446 UI != UIEnd; ++UI) {
10447 // Skip the uses of the chain.
10448 if (UI.getUse().getResNo() != 0)
10451 SDNode *User = *UI;
10452 unsigned Shift = 0;
10454 // Check if this is a trunc(lshr).
10455 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10456 isa<ConstantSDNode>(User->getOperand(1))) {
10457 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10458 User = *User->use_begin();
10461 // At this point, User is a Truncate, iff we encountered, trunc or
10463 if (User->getOpcode() != ISD::TRUNCATE)
10466 // The width of the type must be a power of 2 and greater than 8-bits.
10467 // Otherwise the load cannot be represented in LLVM IR.
10468 // Moreover, if we shifted with a non-8-bits multiple, the slice
10469 // will be across several bytes. We do not support that.
10470 unsigned Width = User->getValueSizeInBits(0);
10471 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10474 // Build the slice for this chain of computations.
10475 LoadedSlice LS(User, LD, Shift, &DAG);
10476 APInt CurrentUsedBits = LS.getUsedBits();
10478 // Check if this slice overlaps with another.
10479 if ((CurrentUsedBits & UsedBits) != 0)
10481 // Update the bits used globally.
10482 UsedBits |= CurrentUsedBits;
10484 // Check if the new slice would be legal.
10488 // Record the slice.
10489 LoadedSlices.push_back(LS);
10492 // Abort slicing if it does not seem to be profitable.
10493 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10498 // Rewrite each chain to use an independent load.
10499 // By construction, each chain can be represented by a unique load.
10501 // Prepare the argument for the new token factor for all the slices.
10502 SmallVector<SDValue, 8> ArgChains;
10503 for (SmallVectorImpl<LoadedSlice>::const_iterator
10504 LSIt = LoadedSlices.begin(),
10505 LSItEnd = LoadedSlices.end();
10506 LSIt != LSItEnd; ++LSIt) {
10507 SDValue SliceInst = LSIt->loadSlice();
10508 CombineTo(LSIt->Inst, SliceInst, true);
10509 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10510 SliceInst = SliceInst.getOperand(0);
10511 assert(SliceInst->getOpcode() == ISD::LOAD &&
10512 "It takes more than a zext to get to the loaded slice!!");
10513 ArgChains.push_back(SliceInst.getValue(1));
10516 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10518 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10522 /// Check to see if V is (and load (ptr), imm), where the load is having
10523 /// specific bytes cleared out. If so, return the byte size being masked out
10524 /// and the shift amount.
10525 static std::pair<unsigned, unsigned>
10526 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10527 std::pair<unsigned, unsigned> Result(0, 0);
10529 // Check for the structure we're looking for.
10530 if (V->getOpcode() != ISD::AND ||
10531 !isa<ConstantSDNode>(V->getOperand(1)) ||
10532 !ISD::isNormalLoad(V->getOperand(0).getNode()))
10535 // Check the chain and pointer.
10536 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10537 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
10539 // The store should be chained directly to the load or be an operand of a
10541 if (LD == Chain.getNode())
10543 else if (Chain->getOpcode() != ISD::TokenFactor)
10544 return Result; // Fail.
10547 for (const SDValue &ChainOp : Chain->op_values())
10548 if (ChainOp.getNode() == LD) {
10552 if (!isOk) return Result;
10555 // This only handles simple types.
10556 if (V.getValueType() != MVT::i16 &&
10557 V.getValueType() != MVT::i32 &&
10558 V.getValueType() != MVT::i64)
10561 // Check the constant mask. Invert it so that the bits being masked out are
10562 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
10563 // follow the sign bit for uniformity.
10564 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10565 unsigned NotMaskLZ = countLeadingZeros(NotMask);
10566 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
10567 unsigned NotMaskTZ = countTrailingZeros(NotMask);
10568 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
10569 if (NotMaskLZ == 64) return Result; // All zero mask.
10571 // See if we have a continuous run of bits. If so, we have 0*1+0*
10572 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10575 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10576 if (V.getValueType() != MVT::i64 && NotMaskLZ)
10577 NotMaskLZ -= 64-V.getValueSizeInBits();
10579 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10580 switch (MaskedBytes) {
10584 default: return Result; // All one mask, or 5-byte mask.
10587 // Verify that the first bit starts at a multiple of mask so that the access
10588 // is aligned the same as the access width.
10589 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10591 Result.first = MaskedBytes;
10592 Result.second = NotMaskTZ/8;
10597 /// Check to see if IVal is something that provides a value as specified by
10598 /// MaskInfo. If so, replace the specified store with a narrower store of
10599 /// truncated IVal.
10601 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10602 SDValue IVal, StoreSDNode *St,
10604 unsigned NumBytes = MaskInfo.first;
10605 unsigned ByteShift = MaskInfo.second;
10606 SelectionDAG &DAG = DC->getDAG();
10608 // Check to see if IVal is all zeros in the part being masked in by the 'or'
10609 // that uses this. If not, this is not a replacement.
10610 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10611 ByteShift*8, (ByteShift+NumBytes)*8);
10612 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10614 // Check that it is legal on the target to do this. It is legal if the new
10615 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10617 MVT VT = MVT::getIntegerVT(NumBytes*8);
10618 if (!DC->isTypeLegal(VT))
10621 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
10622 // shifted by ByteShift and truncated down to NumBytes.
10625 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10626 DAG.getConstant(ByteShift*8, DL,
10627 DC->getShiftAmountTy(IVal.getValueType())));
10630 // Figure out the offset for the store and the alignment of the access.
10632 unsigned NewAlign = St->getAlignment();
10634 if (DAG.getDataLayout().isLittleEndian())
10635 StOffset = ByteShift;
10637 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10639 SDValue Ptr = St->getBasePtr();
10642 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10643 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10644 NewAlign = MinAlign(NewAlign, StOffset);
10647 // Truncate down to the new size.
10648 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10651 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10652 St->getPointerInfo().getWithOffset(StOffset),
10653 false, false, NewAlign).getNode();
10657 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10658 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10659 /// narrowing the load and store if it would end up being a win for performance
10661 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10662 StoreSDNode *ST = cast<StoreSDNode>(N);
10663 if (ST->isVolatile())
10666 SDValue Chain = ST->getChain();
10667 SDValue Value = ST->getValue();
10668 SDValue Ptr = ST->getBasePtr();
10669 EVT VT = Value.getValueType();
10671 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10674 unsigned Opc = Value.getOpcode();
10676 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10677 // is a byte mask indicating a consecutive number of bytes, check to see if
10678 // Y is known to provide just those bytes. If so, we try to replace the
10679 // load + replace + store sequence with a single (narrower) store, which makes
10681 if (Opc == ISD::OR) {
10682 std::pair<unsigned, unsigned> MaskedLoad;
10683 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10684 if (MaskedLoad.first)
10685 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10686 Value.getOperand(1), ST,this))
10687 return SDValue(NewST, 0);
10689 // Or is commutative, so try swapping X and Y.
10690 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10691 if (MaskedLoad.first)
10692 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10693 Value.getOperand(0), ST,this))
10694 return SDValue(NewST, 0);
10697 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10698 Value.getOperand(1).getOpcode() != ISD::Constant)
10701 SDValue N0 = Value.getOperand(0);
10702 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10703 Chain == SDValue(N0.getNode(), 1)) {
10704 LoadSDNode *LD = cast<LoadSDNode>(N0);
10705 if (LD->getBasePtr() != Ptr ||
10706 LD->getPointerInfo().getAddrSpace() !=
10707 ST->getPointerInfo().getAddrSpace())
10710 // Find the type to narrow it the load / op / store to.
10711 SDValue N1 = Value.getOperand(1);
10712 unsigned BitWidth = N1.getValueSizeInBits();
10713 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10714 if (Opc == ISD::AND)
10715 Imm ^= APInt::getAllOnesValue(BitWidth);
10716 if (Imm == 0 || Imm.isAllOnesValue())
10718 unsigned ShAmt = Imm.countTrailingZeros();
10719 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10720 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10721 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10722 // The narrowing should be profitable, the load/store operation should be
10723 // legal (or custom) and the store size should be equal to the NewVT width.
10724 while (NewBW < BitWidth &&
10725 (NewVT.getStoreSizeInBits() != NewBW ||
10726 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10727 !TLI.isNarrowingProfitable(VT, NewVT))) {
10728 NewBW = NextPowerOf2(NewBW);
10729 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10731 if (NewBW >= BitWidth)
10734 // If the lsb changed does not start at the type bitwidth boundary,
10735 // start at the previous one.
10737 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10738 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10739 std::min(BitWidth, ShAmt + NewBW));
10740 if ((Imm & Mask) == Imm) {
10741 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10742 if (Opc == ISD::AND)
10743 NewImm ^= APInt::getAllOnesValue(NewBW);
10744 uint64_t PtrOff = ShAmt / 8;
10745 // For big endian targets, we need to adjust the offset to the pointer to
10746 // load the correct bytes.
10747 if (DAG.getDataLayout().isBigEndian())
10748 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10750 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10751 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10752 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10755 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10756 Ptr.getValueType(), Ptr,
10757 DAG.getConstant(PtrOff, SDLoc(LD),
10758 Ptr.getValueType()));
10759 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10760 LD->getChain(), NewPtr,
10761 LD->getPointerInfo().getWithOffset(PtrOff),
10762 LD->isVolatile(), LD->isNonTemporal(),
10763 LD->isInvariant(), NewAlign,
10765 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10766 DAG.getConstant(NewImm, SDLoc(Value),
10768 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10770 ST->getPointerInfo().getWithOffset(PtrOff),
10771 false, false, NewAlign);
10773 AddToWorklist(NewPtr.getNode());
10774 AddToWorklist(NewLD.getNode());
10775 AddToWorklist(NewVal.getNode());
10776 WorklistRemover DeadNodes(*this);
10777 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10786 /// For a given floating point load / store pair, if the load value isn't used
10787 /// by any other operations, then consider transforming the pair to integer
10788 /// load / store operations if the target deems the transformation profitable.
10789 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10790 StoreSDNode *ST = cast<StoreSDNode>(N);
10791 SDValue Chain = ST->getChain();
10792 SDValue Value = ST->getValue();
10793 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10794 Value.hasOneUse() &&
10795 Chain == SDValue(Value.getNode(), 1)) {
10796 LoadSDNode *LD = cast<LoadSDNode>(Value);
10797 EVT VT = LD->getMemoryVT();
10798 if (!VT.isFloatingPoint() ||
10799 VT != ST->getMemoryVT() ||
10800 LD->isNonTemporal() ||
10801 ST->isNonTemporal() ||
10802 LD->getPointerInfo().getAddrSpace() != 0 ||
10803 ST->getPointerInfo().getAddrSpace() != 0)
10806 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10807 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10808 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10809 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10810 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10813 unsigned LDAlign = LD->getAlignment();
10814 unsigned STAlign = ST->getAlignment();
10815 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10816 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10817 if (LDAlign < ABIAlign || STAlign < ABIAlign)
10820 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10821 LD->getChain(), LD->getBasePtr(),
10822 LD->getPointerInfo(),
10823 false, false, false, LDAlign);
10825 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10826 NewLD, ST->getBasePtr(),
10827 ST->getPointerInfo(),
10828 false, false, STAlign);
10830 AddToWorklist(NewLD.getNode());
10831 AddToWorklist(NewST.getNode());
10832 WorklistRemover DeadNodes(*this);
10833 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10842 /// Helper struct to parse and store a memory address as base + index + offset.
10843 /// We ignore sign extensions when it is safe to do so.
10844 /// The following two expressions are not equivalent. To differentiate we need
10845 /// to store whether there was a sign extension involved in the index
10847 /// (load (i64 add (i64 copyfromreg %c)
10848 /// (i64 signextend (add (i8 load %index)
10852 /// (load (i64 add (i64 copyfromreg %c)
10853 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
10855 struct BaseIndexOffset {
10859 bool IsIndexSignExt;
10861 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10863 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10864 bool IsIndexSignExt) :
10865 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10867 bool equalBaseIndex(const BaseIndexOffset &Other) {
10868 return Other.Base == Base && Other.Index == Index &&
10869 Other.IsIndexSignExt == IsIndexSignExt;
10872 /// Parses tree in Ptr for base, index, offset addresses.
10873 static BaseIndexOffset match(SDValue Ptr) {
10874 bool IsIndexSignExt = false;
10876 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10877 // instruction, then it could be just the BASE or everything else we don't
10878 // know how to handle. Just use Ptr as BASE and give up.
10879 if (Ptr->getOpcode() != ISD::ADD)
10880 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10882 // We know that we have at least an ADD instruction. Try to pattern match
10883 // the simple case of BASE + OFFSET.
10884 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10885 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10886 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10890 // Inside a loop the current BASE pointer is calculated using an ADD and a
10891 // MUL instruction. In this case Ptr is the actual BASE pointer.
10892 // (i64 add (i64 %array_ptr)
10893 // (i64 mul (i64 %induction_var)
10894 // (i64 %element_size)))
10895 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10896 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10898 // Look at Base + Index + Offset cases.
10899 SDValue Base = Ptr->getOperand(0);
10900 SDValue IndexOffset = Ptr->getOperand(1);
10902 // Skip signextends.
10903 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10904 IndexOffset = IndexOffset->getOperand(0);
10905 IsIndexSignExt = true;
10908 // Either the case of Base + Index (no offset) or something else.
10909 if (IndexOffset->getOpcode() != ISD::ADD)
10910 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10912 // Now we have the case of Base + Index + offset.
10913 SDValue Index = IndexOffset->getOperand(0);
10914 SDValue Offset = IndexOffset->getOperand(1);
10916 if (!isa<ConstantSDNode>(Offset))
10917 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10919 // Ignore signextends.
10920 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10921 Index = Index->getOperand(0);
10922 IsIndexSignExt = true;
10923 } else IsIndexSignExt = false;
10925 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10926 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10931 // This is a helper function for visitMUL to check the profitability
10932 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
10933 // MulNode is the original multiply, AddNode is (add x, c1),
10934 // and ConstNode is c2.
10936 // If the (add x, c1) has multiple uses, we could increase
10937 // the number of adds if we make this transformation.
10938 // It would only be worth doing this if we can remove a
10939 // multiply in the process. Check for that here.
10943 // We're checking for cases where we have common "c3 * A" expressions.
10944 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
10946 SDValue &ConstNode) {
10949 // If the add only has one use, this would be OK to do.
10950 if (AddNode.getNode()->hasOneUse())
10953 // Walk all the users of the constant with which we're multiplying.
10954 for (SDNode *Use : ConstNode->uses()) {
10956 if (Use == MulNode) // This use is the one we're on right now. Skip it.
10959 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
10961 SDNode *MulVar = AddNode.getOperand(0).getNode();
10963 // OtherOp is what we're multiplying against the constant.
10964 if (Use->getOperand(0) == ConstNode)
10965 OtherOp = Use->getOperand(1).getNode();
10967 OtherOp = Use->getOperand(0).getNode();
10969 // Check to see if multiply is with the same operand of our "add".
10971 // ConstNode = CONST
10972 // Use = ConstNode * A <-- visiting Use. OtherOp is A.
10974 // AddNode = (A + c1) <-- MulVar is A.
10975 // = AddNode * ConstNode <-- current visiting instruction.
10977 // If we make this transformation, we will have a common
10978 // multiply (ConstNode * A) that we can save.
10979 if (OtherOp == MulVar)
10982 // Now check to see if a future expansion will give us a common
10985 // ConstNode = CONST
10986 // AddNode = (A + c1)
10987 // ... = AddNode * ConstNode <-- current visiting instruction.
10989 // OtherOp = (A + c2)
10990 // Use = OtherOp * ConstNode <-- visiting Use.
10992 // If we make this transformation, we will have a common
10993 // multiply (CONST * A) after we also do the same transformation
10994 // to the "t2" instruction.
10995 if (OtherOp->getOpcode() == ISD::ADD &&
10996 isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
10997 OtherOp->getOperand(0).getNode() == MulVar)
11002 // Didn't find a case where this would be profitable.
11006 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
11008 ArrayRef<MemOpLink> Stores,
11009 SmallVectorImpl<SDValue> &Chains,
11011 SmallVector<SDValue, 8> BuildVector;
11013 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
11014 StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
11015 Chains.push_back(St->getChain());
11016 BuildVector.push_back(St->getValue());
11019 return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
11022 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
11023 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
11024 unsigned NumStores, bool IsConstantSrc, bool UseVector) {
11025 // Make sure we have something to merge.
11029 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11030 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11031 unsigned LatestNodeUsed = 0;
11033 for (unsigned i=0; i < NumStores; ++i) {
11034 // Find a chain for the new wide-store operand. Notice that some
11035 // of the store nodes that we found may not be selected for inclusion
11036 // in the wide store. The chain we use needs to be the chain of the
11037 // latest store node which is *used* and replaced by the wide store.
11038 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11039 LatestNodeUsed = i;
11042 SmallVector<SDValue, 8> Chains;
11044 // The latest Node in the DAG.
11045 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11046 SDLoc DL(StoreNodes[0].MemNode);
11050 bool IsVec = MemVT.isVector();
11051 unsigned Elts = NumStores;
11053 // When merging vector stores, get the total number of elements.
11054 Elts *= MemVT.getVectorNumElements();
11056 // Get the type for the merged vector store.
11057 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11058 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
11060 if (IsConstantSrc) {
11061 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
11063 SmallVector<SDValue, 8> Ops;
11064 for (unsigned i = 0; i < NumStores; ++i) {
11065 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11066 SDValue Val = St->getValue();
11067 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
11068 if (Val.getValueType() != MemVT)
11070 Ops.push_back(Val);
11071 Chains.push_back(St->getChain());
11074 // Build the extracted vector elements back into a vector.
11075 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
11078 // We should always use a vector store when merging extracted vector
11079 // elements, so this path implies a store of constants.
11080 assert(IsConstantSrc && "Merged vector elements should use vector store");
11082 unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
11083 APInt StoreInt(SizeInBits, 0);
11085 // Construct a single integer constant which is made of the smaller
11086 // constant inputs.
11087 bool IsLE = DAG.getDataLayout().isLittleEndian();
11088 for (unsigned i = 0; i < NumStores; ++i) {
11089 unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
11090 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
11091 Chains.push_back(St->getChain());
11093 SDValue Val = St->getValue();
11094 StoreInt <<= ElementSizeBytes * 8;
11095 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
11096 StoreInt |= C->getAPIntValue().zext(SizeInBits);
11097 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
11098 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
11100 llvm_unreachable("Invalid constant element type");
11104 // Create the new Load and Store operations.
11105 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11106 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
11109 assert(!Chains.empty());
11111 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11112 SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
11113 FirstInChain->getBasePtr(),
11114 FirstInChain->getPointerInfo(),
11116 FirstInChain->getAlignment());
11118 // Replace the last store with the new store
11119 CombineTo(LatestOp, NewStore);
11120 // Erase all other stores.
11121 for (unsigned i = 0; i < NumStores; ++i) {
11122 if (StoreNodes[i].MemNode == LatestOp)
11124 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11125 // ReplaceAllUsesWith will replace all uses that existed when it was
11126 // called, but graph optimizations may cause new ones to appear. For
11127 // example, the case in pr14333 looks like
11129 // St's chain -> St -> another store -> X
11131 // And the only difference from St to the other store is the chain.
11132 // When we change it's chain to be St's chain they become identical,
11133 // get CSEed and the net result is that X is now a use of St.
11134 // Since we know that St is redundant, just iterate.
11135 while (!St->use_empty())
11136 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
11137 deleteAndRecombine(St);
11143 void DAGCombiner::getStoreMergeAndAliasCandidates(
11144 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
11145 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
11146 // This holds the base pointer, index, and the offset in bytes from the base
11148 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
11150 // We must have a base and an offset.
11151 if (!BasePtr.Base.getNode())
11154 // Do not handle stores to undef base pointers.
11155 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
11158 // Walk up the chain and look for nodes with offsets from the same
11159 // base pointer. Stop when reaching an instruction with a different kind
11160 // or instruction which has a different base pointer.
11161 EVT MemVT = St->getMemoryVT();
11163 StoreSDNode *Index = St;
11166 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11167 : DAG.getSubtarget().useAA();
11170 // Look at other users of the same chain. Stores on the same chain do not
11171 // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
11172 // to be on the same chain, so don't bother looking at adjacent chains.
11174 SDValue Chain = St->getChain();
11175 for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
11176 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
11177 if (I.getOperandNo() != 0)
11180 if (OtherST->isVolatile() || OtherST->isIndexed())
11183 if (OtherST->getMemoryVT() != MemVT)
11186 BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr());
11188 if (Ptr.equalBaseIndex(BasePtr))
11189 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
11197 // If the chain has more than one use, then we can't reorder the mem ops.
11198 if (Index != St && !SDValue(Index, 0)->hasOneUse())
11201 // Find the base pointer and offset for this memory node.
11202 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
11204 // Check that the base pointer is the same as the original one.
11205 if (!Ptr.equalBaseIndex(BasePtr))
11208 // The memory operands must not be volatile.
11209 if (Index->isVolatile() || Index->isIndexed())
11213 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
11214 if (St->isTruncatingStore())
11217 // The stored memory type must be the same.
11218 if (Index->getMemoryVT() != MemVT)
11221 // We do not allow under-aligned stores in order to prevent
11222 // overriding stores. NOTE: this is a bad hack. Alignment SHOULD
11223 // be irrelevant here; what MATTERS is that we not move memory
11224 // operations that potentially overlap past each-other.
11225 if (Index->getAlignment() < MemVT.getStoreSize())
11228 // We found a potential memory operand to merge.
11229 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11231 // Find the next memory operand in the chain. If the next operand in the
11232 // chain is a store then move up and continue the scan with the next
11233 // memory operand. If the next operand is a load save it and use alias
11234 // information to check if it interferes with anything.
11235 SDNode *NextInChain = Index->getChain().getNode();
11237 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11238 // We found a store node. Use it for the next iteration.
11241 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11242 if (Ldn->isVolatile()) {
11247 // Save the load node for later. Continue the scan.
11248 AliasLoadNodes.push_back(Ldn);
11249 NextInChain = Ldn->getChain().getNode();
11259 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
11260 if (OptLevel == CodeGenOpt::None)
11263 EVT MemVT = St->getMemoryVT();
11264 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11265 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11266 Attribute::NoImplicitFloat);
11268 // This function cannot currently deal with non-byte-sized memory sizes.
11269 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11272 if (!MemVT.isSimple())
11275 // Perform an early exit check. Do not bother looking at stored values that
11276 // are not constants, loads, or extracted vector elements.
11277 SDValue StoredVal = St->getValue();
11278 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11279 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11280 isa<ConstantFPSDNode>(StoredVal);
11281 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11282 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11284 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11287 // Don't merge vectors into wider vectors if the source data comes from loads.
11288 // TODO: This restriction can be lifted by using logic similar to the
11289 // ExtractVecSrc case.
11290 if (MemVT.isVector() && IsLoadSrc)
11293 // Only look at ends of store sequences.
11294 SDValue Chain = SDValue(St, 0);
11295 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11298 // Save the LoadSDNodes that we find in the chain.
11299 // We need to make sure that these nodes do not interfere with
11300 // any of the store nodes.
11301 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11303 // Save the StoreSDNodes that we find in the chain.
11304 SmallVector<MemOpLink, 8> StoreNodes;
11306 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11308 // Check if there is anything to merge.
11309 if (StoreNodes.size() < 2)
11312 // Sort the memory operands according to their distance from the
11313 // base pointer. As a secondary criteria: make sure stores coming
11314 // later in the code come first in the list. This is important for
11315 // the non-UseAA case, because we're merging stores into the FINAL
11316 // store along a chain which potentially contains aliasing stores.
11317 // Thus, if there are multiple stores to the same address, the last
11318 // one can be considered for merging but not the others.
11319 std::sort(StoreNodes.begin(), StoreNodes.end(),
11320 [](MemOpLink LHS, MemOpLink RHS) {
11321 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11322 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11323 LHS.SequenceNum < RHS.SequenceNum);
11326 // Scan the memory operations on the chain and find the first non-consecutive
11327 // store memory address.
11328 unsigned LastConsecutiveStore = 0;
11329 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11330 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11332 // Check that the addresses are consecutive starting from the second
11333 // element in the list of stores.
11335 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11336 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11340 bool Alias = false;
11341 // Check if this store interferes with any of the loads that we found.
11342 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
11343 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
11347 // We found a load that alias with this store. Stop the sequence.
11351 // Mark this node as useful.
11352 LastConsecutiveStore = i;
11355 // The node with the lowest store address.
11356 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11357 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11358 unsigned FirstStoreAlign = FirstInChain->getAlignment();
11359 LLVMContext &Context = *DAG.getContext();
11360 const DataLayout &DL = DAG.getDataLayout();
11362 // Store the constants into memory as one consecutive store.
11363 if (IsConstantSrc) {
11364 unsigned LastLegalType = 0;
11365 unsigned LastLegalVectorType = 0;
11366 bool NonZero = false;
11367 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11368 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11369 SDValue StoredVal = St->getValue();
11371 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11372 NonZero |= !C->isNullValue();
11373 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11374 NonZero |= !C->getConstantFPValue()->isNullValue();
11380 // Find a legal type for the constant store.
11381 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11382 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11384 if (TLI.isTypeLegal(StoreTy) &&
11385 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11386 FirstStoreAlign, &IsFast) && IsFast) {
11387 LastLegalType = i+1;
11388 // Or check whether a truncstore is legal.
11389 } else if (TLI.getTypeAction(Context, StoreTy) ==
11390 TargetLowering::TypePromoteInteger) {
11391 EVT LegalizedStoredValueTy =
11392 TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11393 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11394 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11395 FirstStoreAS, FirstStoreAlign, &IsFast) &&
11397 LastLegalType = i + 1;
11401 // We only use vectors if the constant is known to be zero or the target
11402 // allows it and the function is not marked with the noimplicitfloat
11404 if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11407 // Find a legal type for the vector store.
11408 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11409 if (TLI.isTypeLegal(Ty) &&
11410 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11411 FirstStoreAlign, &IsFast) && IsFast)
11412 LastLegalVectorType = i + 1;
11416 // Check if we found a legal integer type to store.
11417 if (LastLegalType == 0 && LastLegalVectorType == 0)
11420 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11421 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11423 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11427 // When extracting multiple vector elements, try to store them
11428 // in one vector store rather than a sequence of scalar stores.
11429 if (IsExtractVecSrc) {
11430 unsigned NumStoresToMerge = 0;
11431 bool IsVec = MemVT.isVector();
11432 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11433 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11434 unsigned StoreValOpcode = St->getValue().getOpcode();
11435 // This restriction could be loosened.
11436 // Bail out if any stored values are not elements extracted from a vector.
11437 // It should be possible to handle mixed sources, but load sources need
11438 // more careful handling (see the block of code below that handles
11439 // consecutive loads).
11440 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11441 StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11444 // Find a legal type for the vector store.
11445 unsigned Elts = i + 1;
11447 // When merging vector stores, get the total number of elements.
11448 Elts *= MemVT.getVectorNumElements();
11450 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11452 if (TLI.isTypeLegal(Ty) &&
11453 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11454 FirstStoreAlign, &IsFast) && IsFast)
11455 NumStoresToMerge = i + 1;
11458 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11462 // Below we handle the case of multiple consecutive stores that
11463 // come from multiple consecutive loads. We merge them into a single
11464 // wide load and a single wide store.
11466 // Look for load nodes which are used by the stored values.
11467 SmallVector<MemOpLink, 8> LoadNodes;
11469 // Find acceptable loads. Loads need to have the same chain (token factor),
11470 // must not be zext, volatile, indexed, and they must be consecutive.
11471 BaseIndexOffset LdBasePtr;
11472 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11473 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11474 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11477 // Loads must only have one use.
11478 if (!Ld->hasNUsesOfValue(1, 0))
11481 // The memory operands must not be volatile.
11482 if (Ld->isVolatile() || Ld->isIndexed())
11485 // We do not accept ext loads.
11486 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11489 // The stored memory type must be the same.
11490 if (Ld->getMemoryVT() != MemVT)
11493 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11494 // If this is not the first ptr that we check.
11495 if (LdBasePtr.Base.getNode()) {
11496 // The base ptr must be the same.
11497 if (!LdPtr.equalBaseIndex(LdBasePtr))
11500 // Check that all other base pointers are the same as this one.
11504 // We found a potential memory operand to merge.
11505 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11508 if (LoadNodes.size() < 2)
11511 // If we have load/store pair instructions and we only have two values,
11513 unsigned RequiredAlignment;
11514 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11515 St->getAlignment() >= RequiredAlignment)
11518 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11519 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11520 unsigned FirstLoadAlign = FirstLoad->getAlignment();
11522 // Scan the memory operations on the chain and find the first non-consecutive
11523 // load memory address. These variables hold the index in the store node
11525 unsigned LastConsecutiveLoad = 0;
11526 // This variable refers to the size and not index in the array.
11527 unsigned LastLegalVectorType = 0;
11528 unsigned LastLegalIntegerType = 0;
11529 StartAddress = LoadNodes[0].OffsetFromBase;
11530 SDValue FirstChain = FirstLoad->getChain();
11531 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11532 // All loads much share the same chain.
11533 if (LoadNodes[i].MemNode->getChain() != FirstChain)
11536 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11537 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11539 LastConsecutiveLoad = i;
11540 // Find a legal type for the vector store.
11541 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11542 bool IsFastSt, IsFastLd;
11543 if (TLI.isTypeLegal(StoreTy) &&
11544 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11545 FirstStoreAlign, &IsFastSt) && IsFastSt &&
11546 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11547 FirstLoadAlign, &IsFastLd) && IsFastLd) {
11548 LastLegalVectorType = i + 1;
11551 // Find a legal type for the integer store.
11552 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11553 StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11554 if (TLI.isTypeLegal(StoreTy) &&
11555 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11556 FirstStoreAlign, &IsFastSt) && IsFastSt &&
11557 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11558 FirstLoadAlign, &IsFastLd) && IsFastLd)
11559 LastLegalIntegerType = i + 1;
11560 // Or check whether a truncstore and extload is legal.
11561 else if (TLI.getTypeAction(Context, StoreTy) ==
11562 TargetLowering::TypePromoteInteger) {
11563 EVT LegalizedStoredValueTy =
11564 TLI.getTypeToTransformTo(Context, StoreTy);
11565 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11566 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11567 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11568 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11569 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11570 FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11572 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11573 FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11575 LastLegalIntegerType = i+1;
11579 // Only use vector types if the vector type is larger than the integer type.
11580 // If they are the same, use integers.
11581 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11582 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11584 // We add +1 here because the LastXXX variables refer to location while
11585 // the NumElem refers to array/index size.
11586 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11587 NumElem = std::min(LastLegalType, NumElem);
11592 // Collect the chains from all merged stores.
11593 SmallVector<SDValue, 8> MergeStoreChains;
11594 MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
11596 // The latest Node in the DAG.
11597 unsigned LatestNodeUsed = 0;
11598 for (unsigned i=1; i<NumElem; ++i) {
11599 // Find a chain for the new wide-store operand. Notice that some
11600 // of the store nodes that we found may not be selected for inclusion
11601 // in the wide store. The chain we use needs to be the chain of the
11602 // latest store node which is *used* and replaced by the wide store.
11603 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11604 LatestNodeUsed = i;
11606 MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
11609 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11611 // Find if it is better to use vectors or integers to load and store
11615 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11617 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11618 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11621 SDLoc LoadDL(LoadNodes[0].MemNode);
11622 SDLoc StoreDL(StoreNodes[0].MemNode);
11624 // The merged loads are required to have the same chain, so using the first's
11625 // chain is acceptable.
11626 SDValue NewLoad = DAG.getLoad(
11627 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11628 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11630 SDValue NewStoreChain =
11631 DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
11633 SDValue NewStore = DAG.getStore(
11634 NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
11635 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11637 // Replace one of the loads with the new load.
11638 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11639 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11640 SDValue(NewLoad.getNode(), 1));
11642 // Remove the rest of the load chains.
11643 for (unsigned i = 1; i < NumElem ; ++i) {
11644 // Replace all chain users of the old load nodes with the chain of the new
11646 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11647 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11650 // Replace the last store with the new store.
11651 CombineTo(LatestOp, NewStore);
11652 // Erase all other stores.
11653 for (unsigned i = 0; i < NumElem ; ++i) {
11654 // Remove all Store nodes.
11655 if (StoreNodes[i].MemNode == LatestOp)
11657 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11658 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11659 deleteAndRecombine(St);
11665 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11669 // Replace the chain to avoid dependency.
11670 if (ST->isTruncatingStore()) {
11671 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11672 ST->getBasePtr(), ST->getMemoryVT(),
11673 ST->getMemOperand());
11675 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11676 ST->getMemOperand());
11679 // Create token to keep both nodes around.
11680 SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11681 MVT::Other, ST->getChain(), ReplStore);
11683 // Make sure the new and old chains are cleaned up.
11684 AddToWorklist(Token.getNode());
11686 // Don't add users to work list.
11687 return CombineTo(ST, Token, false);
11690 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
11691 SDValue Value = ST->getValue();
11692 if (Value.getOpcode() == ISD::TargetConstantFP)
11697 SDValue Chain = ST->getChain();
11698 SDValue Ptr = ST->getBasePtr();
11700 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
11702 // NOTE: If the original store is volatile, this transform must not increase
11703 // the number of stores. For example, on x86-32 an f64 can be stored in one
11704 // processor operation but an i64 (which is not legal) requires two. So the
11705 // transform should not be done in this case.
11708 switch (CFP->getSimpleValueType(0).SimpleTy) {
11710 llvm_unreachable("Unknown FP type");
11711 case MVT::f16: // We don't do this for these yet.
11717 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11718 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11720 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11721 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11723 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
11728 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11729 !ST->isVolatile()) ||
11730 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11732 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11733 getZExtValue(), SDLoc(CFP), MVT::i64);
11734 return DAG.getStore(Chain, DL, Tmp,
11735 Ptr, ST->getMemOperand());
11738 if (!ST->isVolatile() &&
11739 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11740 // Many FP stores are not made apparent until after legalize, e.g. for
11741 // argument passing. Since this is so common, custom legalize the
11742 // 64-bit integer store into two 32-bit stores.
11743 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11744 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11745 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11746 if (DAG.getDataLayout().isBigEndian())
11749 unsigned Alignment = ST->getAlignment();
11750 bool isVolatile = ST->isVolatile();
11751 bool isNonTemporal = ST->isNonTemporal();
11752 AAMDNodes AAInfo = ST->getAAInfo();
11754 SDValue St0 = DAG.getStore(Chain, DL, Lo,
11755 Ptr, ST->getPointerInfo(),
11756 isVolatile, isNonTemporal,
11757 ST->getAlignment(), AAInfo);
11758 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11759 DAG.getConstant(4, DL, Ptr.getValueType()));
11760 Alignment = MinAlign(Alignment, 4U);
11761 SDValue St1 = DAG.getStore(Chain, DL, Hi,
11762 Ptr, ST->getPointerInfo().getWithOffset(4),
11763 isVolatile, isNonTemporal,
11764 Alignment, AAInfo);
11765 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11773 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11774 StoreSDNode *ST = cast<StoreSDNode>(N);
11775 SDValue Chain = ST->getChain();
11776 SDValue Value = ST->getValue();
11777 SDValue Ptr = ST->getBasePtr();
11779 // If this is a store of a bit convert, store the input value if the
11780 // resultant store does not need a higher alignment than the original.
11781 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11782 ST->isUnindexed()) {
11783 unsigned OrigAlign = ST->getAlignment();
11784 EVT SVT = Value.getOperand(0).getValueType();
11785 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11786 SVT.getTypeForEVT(*DAG.getContext()));
11787 if (Align <= OrigAlign &&
11788 ((!LegalOperations && !ST->isVolatile()) ||
11789 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11790 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11791 Ptr, ST->getPointerInfo(), ST->isVolatile(),
11792 ST->isNonTemporal(), OrigAlign,
11796 // Turn 'store undef, Ptr' -> nothing.
11797 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11800 // Try to infer better alignment information than the store already has.
11801 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11802 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11803 if (Align > ST->getAlignment()) {
11805 DAG.getTruncStore(Chain, SDLoc(N), Value,
11806 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11807 ST->isVolatile(), ST->isNonTemporal(), Align,
11809 if (NewStore.getNode() != N)
11810 return CombineTo(ST, NewStore, true);
11815 // Try transforming a pair floating point load / store ops to integer
11816 // load / store ops.
11817 if (SDValue NewST = TransformFPLoadStorePair(N))
11820 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11821 : DAG.getSubtarget().useAA();
11823 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11824 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11827 if (UseAA && ST->isUnindexed()) {
11828 // FIXME: We should do this even without AA enabled. AA will just allow
11829 // FindBetterChain to work in more situations. The problem with this is that
11830 // any combine that expects memory operations to be on consecutive chains
11831 // first needs to be updated to look for users of the same chain.
11833 // Walk up chain skipping non-aliasing memory nodes, on this store and any
11834 // adjacent stores.
11835 if (findBetterNeighborChains(ST)) {
11836 // replaceStoreChain uses CombineTo, which handled all of the worklist
11837 // manipulation. Return the original node to not do anything else.
11838 return SDValue(ST, 0);
11842 // Try transforming N to an indexed store.
11843 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11844 return SDValue(N, 0);
11846 // FIXME: is there such a thing as a truncating indexed store?
11847 if (ST->isTruncatingStore() && ST->isUnindexed() &&
11848 Value.getValueType().isInteger()) {
11849 // See if we can simplify the input to this truncstore with knowledge that
11850 // only the low bits are being used. For example:
11851 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
11853 GetDemandedBits(Value,
11854 APInt::getLowBitsSet(
11855 Value.getValueType().getScalarType().getSizeInBits(),
11856 ST->getMemoryVT().getScalarType().getSizeInBits()));
11857 AddToWorklist(Value.getNode());
11858 if (Shorter.getNode())
11859 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11860 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11862 // Otherwise, see if we can simplify the operation with
11863 // SimplifyDemandedBits, which only works if the value has a single use.
11864 if (SimplifyDemandedBits(Value,
11865 APInt::getLowBitsSet(
11866 Value.getValueType().getScalarType().getSizeInBits(),
11867 ST->getMemoryVT().getScalarType().getSizeInBits())))
11868 return SDValue(N, 0);
11871 // If this is a load followed by a store to the same location, then the store
11873 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11874 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11875 ST->isUnindexed() && !ST->isVolatile() &&
11876 // There can't be any side effects between the load and store, such as
11877 // a call or store.
11878 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11879 // The store is dead, remove it.
11884 // If this is a store followed by a store with the same value to the same
11885 // location, then the store is dead/noop.
11886 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11887 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11888 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11889 ST1->isUnindexed() && !ST1->isVolatile()) {
11890 // The store is dead, remove it.
11895 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11896 // truncating store. We can do this even if this is already a truncstore.
11897 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11898 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11899 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11900 ST->getMemoryVT())) {
11901 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11902 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11905 // Only perform this optimization before the types are legal, because we
11906 // don't want to perform this optimization on every DAGCombine invocation.
11908 bool EverChanged = false;
11911 // There can be multiple store sequences on the same chain.
11912 // Keep trying to merge store sequences until we are unable to do so
11913 // or until we merge the last store on the chain.
11914 bool Changed = MergeConsecutiveStores(ST);
11915 EverChanged |= Changed;
11916 if (!Changed) break;
11917 } while (ST->getOpcode() != ISD::DELETED_NODE);
11920 return SDValue(N, 0);
11923 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11925 // Make sure to do this only after attempting to merge stores in order to
11926 // avoid changing the types of some subset of stores due to visit order,
11927 // preventing their merging.
11928 if (isa<ConstantFPSDNode>(Value)) {
11929 if (SDValue NewSt = replaceStoreOfFPConstant(ST))
11933 return ReduceLoadOpStoreWidth(N);
11936 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11937 SDValue InVec = N->getOperand(0);
11938 SDValue InVal = N->getOperand(1);
11939 SDValue EltNo = N->getOperand(2);
11942 // If the inserted element is an UNDEF, just use the input vector.
11943 if (InVal.getOpcode() == ISD::UNDEF)
11946 EVT VT = InVec.getValueType();
11948 // If we can't generate a legal BUILD_VECTOR, exit
11949 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11952 // Check that we know which element is being inserted
11953 if (!isa<ConstantSDNode>(EltNo))
11955 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11957 // Canonicalize insert_vector_elt dag nodes.
11959 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11960 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11962 // Do this only if the child insert_vector node has one use; also
11963 // do this only if indices are both constants and Idx1 < Idx0.
11964 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11965 && isa<ConstantSDNode>(InVec.getOperand(2))) {
11966 unsigned OtherElt =
11967 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11968 if (Elt < OtherElt) {
11970 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11971 InVec.getOperand(0), InVal, EltNo);
11972 AddToWorklist(NewOp.getNode());
11973 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11974 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11978 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11979 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
11980 // vector elements.
11981 SmallVector<SDValue, 8> Ops;
11982 // Do not combine these two vectors if the output vector will not replace
11983 // the input vector.
11984 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11985 Ops.append(InVec.getNode()->op_begin(),
11986 InVec.getNode()->op_end());
11987 } else if (InVec.getOpcode() == ISD::UNDEF) {
11988 unsigned NElts = VT.getVectorNumElements();
11989 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11994 // Insert the element
11995 if (Elt < Ops.size()) {
11996 // All the operands of BUILD_VECTOR must have the same type;
11997 // we enforce that here.
11998 EVT OpVT = Ops[0].getValueType();
11999 if (InVal.getValueType() != OpVT)
12000 InVal = OpVT.bitsGT(InVal.getValueType()) ?
12001 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
12002 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
12006 // Return the new vector
12007 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
12010 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
12011 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
12012 EVT ResultVT = EVE->getValueType(0);
12013 EVT VecEltVT = InVecVT.getVectorElementType();
12014 unsigned Align = OriginalLoad->getAlignment();
12015 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
12016 VecEltVT.getTypeForEVT(*DAG.getContext()));
12018 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
12023 SDValue NewPtr = OriginalLoad->getBasePtr();
12025 EVT PtrType = NewPtr.getValueType();
12026 MachinePointerInfo MPI;
12028 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
12029 int Elt = ConstEltNo->getZExtValue();
12030 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
12031 Offset = DAG.getConstant(PtrOff, DL, PtrType);
12032 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
12034 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
12035 Offset = DAG.getNode(
12036 ISD::MUL, DL, PtrType, Offset,
12037 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
12038 MPI = OriginalLoad->getPointerInfo();
12040 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
12042 // The replacement we need to do here is a little tricky: we need to
12043 // replace an extractelement of a load with a load.
12044 // Use ReplaceAllUsesOfValuesWith to do the replacement.
12045 // Note that this replacement assumes that the extractvalue is the only
12046 // use of the load; that's okay because we don't want to perform this
12047 // transformation in other cases anyway.
12050 if (ResultVT.bitsGT(VecEltVT)) {
12051 // If the result type of vextract is wider than the load, then issue an
12052 // extending load instead.
12053 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
12057 Load = DAG.getExtLoad(
12058 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
12059 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
12060 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
12061 Chain = Load.getValue(1);
12063 Load = DAG.getLoad(
12064 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
12065 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
12066 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
12067 Chain = Load.getValue(1);
12068 if (ResultVT.bitsLT(VecEltVT))
12069 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
12071 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
12073 WorklistRemover DeadNodes(*this);
12074 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
12075 SDValue To[] = { Load, Chain };
12076 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
12077 // Since we're explicitly calling ReplaceAllUses, add the new node to the
12078 // worklist explicitly as well.
12079 AddToWorklist(Load.getNode());
12080 AddUsersToWorklist(Load.getNode()); // Add users too
12081 // Make sure to revisit this node to clean it up; it will usually be dead.
12082 AddToWorklist(EVE);
12084 return SDValue(EVE, 0);
12087 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
12088 // (vextract (scalar_to_vector val, 0) -> val
12089 SDValue InVec = N->getOperand(0);
12090 EVT VT = InVec.getValueType();
12091 EVT NVT = N->getValueType(0);
12093 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
12094 // Check if the result type doesn't match the inserted element type. A
12095 // SCALAR_TO_VECTOR may truncate the inserted element and the
12096 // EXTRACT_VECTOR_ELT may widen the extracted vector.
12097 SDValue InOp = InVec.getOperand(0);
12098 if (InOp.getValueType() != NVT) {
12099 assert(InOp.getValueType().isInteger() && NVT.isInteger());
12100 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
12105 SDValue EltNo = N->getOperand(1);
12106 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
12108 // extract_vector_elt (build_vector x, y), 1 -> y
12110 InVec.getOpcode() == ISD::BUILD_VECTOR &&
12111 TLI.isTypeLegal(VT) &&
12112 (InVec.hasOneUse() ||
12113 TLI.aggressivelyPreferBuildVectorSources(VT))) {
12114 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
12115 EVT InEltVT = Elt.getValueType();
12117 // Sometimes build_vector's scalar input types do not match result type.
12118 if (NVT == InEltVT)
12121 // TODO: It may be useful to truncate if free if the build_vector implicitly
12125 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
12126 // We only perform this optimization before the op legalization phase because
12127 // we may introduce new vector instructions which are not backed by TD
12128 // patterns. For example on AVX, extracting elements from a wide vector
12129 // without using extract_subvector. However, if we can find an underlying
12130 // scalar value, then we can always use that.
12131 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
12132 int NumElem = VT.getVectorNumElements();
12133 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
12134 // Find the new index to extract from.
12135 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
12137 // Extracting an undef index is undef.
12139 return DAG.getUNDEF(NVT);
12141 // Select the right vector half to extract from.
12143 if (OrigElt < NumElem) {
12144 SVInVec = InVec->getOperand(0);
12146 SVInVec = InVec->getOperand(1);
12147 OrigElt -= NumElem;
12150 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
12151 SDValue InOp = SVInVec.getOperand(OrigElt);
12152 if (InOp.getValueType() != NVT) {
12153 assert(InOp.getValueType().isInteger() && NVT.isInteger());
12154 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
12160 // FIXME: We should handle recursing on other vector shuffles and
12161 // scalar_to_vector here as well.
12163 if (!LegalOperations) {
12164 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12165 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
12166 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
12170 bool BCNumEltsChanged = false;
12171 EVT ExtVT = VT.getVectorElementType();
12174 // If the result of load has to be truncated, then it's not necessarily
12176 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
12179 if (InVec.getOpcode() == ISD::BITCAST) {
12180 // Don't duplicate a load with other uses.
12181 if (!InVec.hasOneUse())
12184 EVT BCVT = InVec.getOperand(0).getValueType();
12185 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
12187 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
12188 BCNumEltsChanged = true;
12189 InVec = InVec.getOperand(0);
12190 ExtVT = BCVT.getVectorElementType();
12193 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
12194 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
12195 ISD::isNormalLoad(InVec.getNode()) &&
12196 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
12197 SDValue Index = N->getOperand(1);
12198 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
12199 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
12203 // Perform only after legalization to ensure build_vector / vector_shuffle
12204 // optimizations have already been done.
12205 if (!LegalOperations) return SDValue();
12207 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
12208 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
12209 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
12212 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12214 LoadSDNode *LN0 = nullptr;
12215 const ShuffleVectorSDNode *SVN = nullptr;
12216 if (ISD::isNormalLoad(InVec.getNode())) {
12217 LN0 = cast<LoadSDNode>(InVec);
12218 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
12219 InVec.getOperand(0).getValueType() == ExtVT &&
12220 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
12221 // Don't duplicate a load with other uses.
12222 if (!InVec.hasOneUse())
12225 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
12226 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
12227 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
12229 // (load $addr+1*size)
12231 // Don't duplicate a load with other uses.
12232 if (!InVec.hasOneUse())
12235 // If the bit convert changed the number of elements, it is unsafe
12236 // to examine the mask.
12237 if (BCNumEltsChanged)
12240 // Select the input vector, guarding against out of range extract vector.
12241 unsigned NumElems = VT.getVectorNumElements();
12242 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
12243 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
12245 if (InVec.getOpcode() == ISD::BITCAST) {
12246 // Don't duplicate a load with other uses.
12247 if (!InVec.hasOneUse())
12250 InVec = InVec.getOperand(0);
12252 if (ISD::isNormalLoad(InVec.getNode())) {
12253 LN0 = cast<LoadSDNode>(InVec);
12254 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12255 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12259 // Make sure we found a non-volatile load and the extractelement is
12261 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12264 // If Idx was -1 above, Elt is going to be -1, so just return undef.
12266 return DAG.getUNDEF(LVT);
12268 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12274 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12275 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12276 // We perform this optimization post type-legalization because
12277 // the type-legalizer often scalarizes integer-promoted vectors.
12278 // Performing this optimization before may create bit-casts which
12279 // will be type-legalized to complex code sequences.
12280 // We perform this optimization only before the operation legalizer because we
12281 // may introduce illegal operations.
12282 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12285 unsigned NumInScalars = N->getNumOperands();
12287 EVT VT = N->getValueType(0);
12289 // Check to see if this is a BUILD_VECTOR of a bunch of values
12290 // which come from any_extend or zero_extend nodes. If so, we can create
12291 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12292 // optimizations. We do not handle sign-extend because we can't fill the sign
12294 EVT SourceType = MVT::Other;
12295 bool AllAnyExt = true;
12297 for (unsigned i = 0; i != NumInScalars; ++i) {
12298 SDValue In = N->getOperand(i);
12299 // Ignore undef inputs.
12300 if (In.getOpcode() == ISD::UNDEF) continue;
12302 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
12303 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12305 // Abort if the element is not an extension.
12306 if (!ZeroExt && !AnyExt) {
12307 SourceType = MVT::Other;
12311 // The input is a ZeroExt or AnyExt. Check the original type.
12312 EVT InTy = In.getOperand(0).getValueType();
12314 // Check that all of the widened source types are the same.
12315 if (SourceType == MVT::Other)
12318 else if (InTy != SourceType) {
12319 // Multiple income types. Abort.
12320 SourceType = MVT::Other;
12324 // Check if all of the extends are ANY_EXTENDs.
12325 AllAnyExt &= AnyExt;
12328 // In order to have valid types, all of the inputs must be extended from the
12329 // same source type and all of the inputs must be any or zero extend.
12330 // Scalar sizes must be a power of two.
12331 EVT OutScalarTy = VT.getScalarType();
12332 bool ValidTypes = SourceType != MVT::Other &&
12333 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12334 isPowerOf2_32(SourceType.getSizeInBits());
12336 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12337 // turn into a single shuffle instruction.
12341 bool isLE = DAG.getDataLayout().isLittleEndian();
12342 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12343 assert(ElemRatio > 1 && "Invalid element size ratio");
12344 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12345 DAG.getConstant(0, SDLoc(N), SourceType);
12347 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12348 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12350 // Populate the new build_vector
12351 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12352 SDValue Cast = N->getOperand(i);
12353 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12354 Cast.getOpcode() == ISD::ZERO_EXTEND ||
12355 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
12357 if (Cast.getOpcode() == ISD::UNDEF)
12358 In = DAG.getUNDEF(SourceType);
12360 In = Cast->getOperand(0);
12361 unsigned Index = isLE ? (i * ElemRatio) :
12362 (i * ElemRatio + (ElemRatio - 1));
12364 assert(Index < Ops.size() && "Invalid index");
12368 // The type of the new BUILD_VECTOR node.
12369 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12370 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12371 "Invalid vector size");
12372 // Check if the new vector type is legal.
12373 if (!isTypeLegal(VecVT)) return SDValue();
12375 // Make the new BUILD_VECTOR.
12376 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
12378 // The new BUILD_VECTOR node has the potential to be further optimized.
12379 AddToWorklist(BV.getNode());
12380 // Bitcast to the desired type.
12381 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12384 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12385 EVT VT = N->getValueType(0);
12387 unsigned NumInScalars = N->getNumOperands();
12390 EVT SrcVT = MVT::Other;
12391 unsigned Opcode = ISD::DELETED_NODE;
12392 unsigned NumDefs = 0;
12394 for (unsigned i = 0; i != NumInScalars; ++i) {
12395 SDValue In = N->getOperand(i);
12396 unsigned Opc = In.getOpcode();
12398 if (Opc == ISD::UNDEF)
12401 // If all scalar values are floats and converted from integers.
12402 if (Opcode == ISD::DELETED_NODE &&
12403 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12410 EVT InVT = In.getOperand(0).getValueType();
12412 // If all scalar values are typed differently, bail out. It's chosen to
12413 // simplify BUILD_VECTOR of integer types.
12414 if (SrcVT == MVT::Other)
12421 // If the vector has just one element defined, it's not worth to fold it into
12422 // a vectorized one.
12426 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12427 && "Should only handle conversion from integer to float.");
12428 assert(SrcVT != MVT::Other && "Cannot determine source type!");
12430 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12432 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12435 // Just because the floating-point vector type is legal does not necessarily
12436 // mean that the corresponding integer vector type is.
12437 if (!isTypeLegal(NVT))
12440 SmallVector<SDValue, 8> Opnds;
12441 for (unsigned i = 0; i != NumInScalars; ++i) {
12442 SDValue In = N->getOperand(i);
12444 if (In.getOpcode() == ISD::UNDEF)
12445 Opnds.push_back(DAG.getUNDEF(SrcVT));
12447 Opnds.push_back(In.getOperand(0));
12449 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
12450 AddToWorklist(BV.getNode());
12452 return DAG.getNode(Opcode, dl, VT, BV);
12455 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12456 unsigned NumInScalars = N->getNumOperands();
12458 EVT VT = N->getValueType(0);
12460 // A vector built entirely of undefs is undef.
12461 if (ISD::allOperandsUndef(N))
12462 return DAG.getUNDEF(VT);
12464 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12467 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12470 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12471 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12472 // at most two distinct vectors, turn this into a shuffle node.
12474 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12475 if (!isTypeLegal(VT))
12478 // May only combine to shuffle after legalize if shuffle is legal.
12479 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12482 SDValue VecIn1, VecIn2;
12483 bool UsesZeroVector = false;
12484 for (unsigned i = 0; i != NumInScalars; ++i) {
12485 SDValue Op = N->getOperand(i);
12486 // Ignore undef inputs.
12487 if (Op.getOpcode() == ISD::UNDEF) continue;
12489 // See if we can combine this build_vector into a blend with a zero vector.
12490 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12491 UsesZeroVector = true;
12495 // If this input is something other than a EXTRACT_VECTOR_ELT with a
12496 // constant index, bail out.
12497 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12498 !isa<ConstantSDNode>(Op.getOperand(1))) {
12499 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12503 // We allow up to two distinct input vectors.
12504 SDValue ExtractedFromVec = Op.getOperand(0);
12505 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12508 if (!VecIn1.getNode()) {
12509 VecIn1 = ExtractedFromVec;
12510 } else if (!VecIn2.getNode() && !UsesZeroVector) {
12511 VecIn2 = ExtractedFromVec;
12513 // Too many inputs.
12514 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12519 // If everything is good, we can make a shuffle operation.
12520 if (VecIn1.getNode()) {
12521 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12522 SmallVector<int, 8> Mask;
12523 for (unsigned i = 0; i != NumInScalars; ++i) {
12524 unsigned Opcode = N->getOperand(i).getOpcode();
12525 if (Opcode == ISD::UNDEF) {
12526 Mask.push_back(-1);
12530 // Operands can also be zero.
12531 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12532 assert(UsesZeroVector &&
12533 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12534 "Unexpected node found!");
12535 Mask.push_back(NumInScalars+i);
12539 // If extracting from the first vector, just use the index directly.
12540 SDValue Extract = N->getOperand(i);
12541 SDValue ExtVal = Extract.getOperand(1);
12542 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12543 if (Extract.getOperand(0) == VecIn1) {
12544 Mask.push_back(ExtIndex);
12548 // Otherwise, use InIdx + InputVecSize
12549 Mask.push_back(InNumElements + ExtIndex);
12552 // Avoid introducing illegal shuffles with zero.
12553 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12556 // We can't generate a shuffle node with mismatched input and output types.
12557 // Attempt to transform a single input vector to the correct type.
12558 if ((VT != VecIn1.getValueType())) {
12559 // If the input vector type has a different base type to the output
12560 // vector type, bail out.
12561 EVT VTElemType = VT.getVectorElementType();
12562 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12563 (VecIn2.getNode() &&
12564 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12567 // If the input vector is too small, widen it.
12568 // We only support widening of vectors which are half the size of the
12569 // output registers. For example XMM->YMM widening on X86 with AVX.
12570 EVT VecInT = VecIn1.getValueType();
12571 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12572 // If we only have one small input, widen it by adding undef values.
12573 if (!VecIn2.getNode())
12574 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12575 DAG.getUNDEF(VecIn1.getValueType()));
12576 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12577 // If we have two small inputs of the same type, try to concat them.
12578 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12579 VecIn2 = SDValue(nullptr, 0);
12582 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12583 // If the input vector is too large, try to split it.
12584 // We don't support having two input vectors that are too large.
12585 // If the zero vector was used, we can not split the vector,
12586 // since we'd need 3 inputs.
12587 if (UsesZeroVector || VecIn2.getNode())
12590 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12593 // Try to replace VecIn1 with two extract_subvectors
12594 // No need to update the masks, they should still be correct.
12595 VecIn2 = DAG.getNode(
12596 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12597 DAG.getConstant(VT.getVectorNumElements(), dl,
12598 TLI.getVectorIdxTy(DAG.getDataLayout())));
12599 VecIn1 = DAG.getNode(
12600 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12601 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12606 if (UsesZeroVector)
12607 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12608 DAG.getConstantFP(0.0, dl, VT);
12610 // If VecIn2 is unused then change it to undef.
12611 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12613 // Check that we were able to transform all incoming values to the same
12615 if (VecIn2.getValueType() != VecIn1.getValueType() ||
12616 VecIn1.getValueType() != VT)
12619 // Return the new VECTOR_SHUFFLE node.
12623 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12629 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12630 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12631 EVT OpVT = N->getOperand(0).getValueType();
12633 // If the operands are legal vectors, leave them alone.
12634 if (TLI.isTypeLegal(OpVT))
12638 EVT VT = N->getValueType(0);
12639 SmallVector<SDValue, 8> Ops;
12641 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12642 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12644 // Keep track of what we encounter.
12645 bool AnyInteger = false;
12646 bool AnyFP = false;
12647 for (const SDValue &Op : N->ops()) {
12648 if (ISD::BITCAST == Op.getOpcode() &&
12649 !Op.getOperand(0).getValueType().isVector())
12650 Ops.push_back(Op.getOperand(0));
12651 else if (ISD::UNDEF == Op.getOpcode())
12652 Ops.push_back(ScalarUndef);
12656 // Note whether we encounter an integer or floating point scalar.
12657 // If it's neither, bail out, it could be something weird like x86mmx.
12658 EVT LastOpVT = Ops.back().getValueType();
12659 if (LastOpVT.isFloatingPoint())
12661 else if (LastOpVT.isInteger())
12667 // If any of the operands is a floating point scalar bitcast to a vector,
12668 // use floating point types throughout, and bitcast everything.
12669 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12671 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12672 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12674 for (SDValue &Op : Ops) {
12675 if (Op.getValueType() == SVT)
12677 if (Op.getOpcode() == ISD::UNDEF)
12680 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12685 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12686 VT.getSizeInBits() / SVT.getSizeInBits());
12687 return DAG.getNode(ISD::BITCAST, DL, VT,
12688 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12691 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12692 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12693 // most two distinct vectors the same size as the result, attempt to turn this
12694 // into a legal shuffle.
12695 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12696 EVT VT = N->getValueType(0);
12697 EVT OpVT = N->getOperand(0).getValueType();
12698 int NumElts = VT.getVectorNumElements();
12699 int NumOpElts = OpVT.getVectorNumElements();
12701 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12702 SmallVector<int, 8> Mask;
12704 for (SDValue Op : N->ops()) {
12705 // Peek through any bitcast.
12706 while (Op.getOpcode() == ISD::BITCAST)
12707 Op = Op.getOperand(0);
12709 // UNDEF nodes convert to UNDEF shuffle mask values.
12710 if (Op.getOpcode() == ISD::UNDEF) {
12711 Mask.append((unsigned)NumOpElts, -1);
12715 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12718 // What vector are we extracting the subvector from and at what index?
12719 SDValue ExtVec = Op.getOperand(0);
12721 // We want the EVT of the original extraction to correctly scale the
12722 // extraction index.
12723 EVT ExtVT = ExtVec.getValueType();
12725 // Peek through any bitcast.
12726 while (ExtVec.getOpcode() == ISD::BITCAST)
12727 ExtVec = ExtVec.getOperand(0);
12729 // UNDEF nodes convert to UNDEF shuffle mask values.
12730 if (ExtVec.getOpcode() == ISD::UNDEF) {
12731 Mask.append((unsigned)NumOpElts, -1);
12735 if (!isa<ConstantSDNode>(Op.getOperand(1)))
12737 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12739 // Ensure that we are extracting a subvector from a vector the same
12740 // size as the result.
12741 if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12744 // Scale the subvector index to account for any bitcast.
12745 int NumExtElts = ExtVT.getVectorNumElements();
12746 if (0 == (NumExtElts % NumElts))
12747 ExtIdx /= (NumExtElts / NumElts);
12748 else if (0 == (NumElts % NumExtElts))
12749 ExtIdx *= (NumElts / NumExtElts);
12753 // At most we can reference 2 inputs in the final shuffle.
12754 if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) {
12756 for (int i = 0; i != NumOpElts; ++i)
12757 Mask.push_back(i + ExtIdx);
12758 } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) {
12760 for (int i = 0; i != NumOpElts; ++i)
12761 Mask.push_back(i + ExtIdx + NumElts);
12767 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
12770 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
12771 DAG.getBitcast(VT, SV1), Mask);
12774 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12775 // If we only have one input vector, we don't need to do any concatenation.
12776 if (N->getNumOperands() == 1)
12777 return N->getOperand(0);
12779 // Check if all of the operands are undefs.
12780 EVT VT = N->getValueType(0);
12781 if (ISD::allOperandsUndef(N))
12782 return DAG.getUNDEF(VT);
12784 // Optimize concat_vectors where all but the first of the vectors are undef.
12785 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12786 return Op.getOpcode() == ISD::UNDEF;
12788 SDValue In = N->getOperand(0);
12789 assert(In.getValueType().isVector() && "Must concat vectors");
12791 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12792 if (In->getOpcode() == ISD::BITCAST &&
12793 !In->getOperand(0)->getValueType(0).isVector()) {
12794 SDValue Scalar = In->getOperand(0);
12796 // If the bitcast type isn't legal, it might be a trunc of a legal type;
12797 // look through the trunc so we can still do the transform:
12798 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12799 if (Scalar->getOpcode() == ISD::TRUNCATE &&
12800 !TLI.isTypeLegal(Scalar.getValueType()) &&
12801 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12802 Scalar = Scalar->getOperand(0);
12804 EVT SclTy = Scalar->getValueType(0);
12806 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12809 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12810 VT.getSizeInBits() / SclTy.getSizeInBits());
12811 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12814 SDLoc dl = SDLoc(N);
12815 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12816 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12820 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12821 // We have already tested above for an UNDEF only concatenation.
12822 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12823 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12824 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12825 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12827 bool AllBuildVectorsOrUndefs =
12828 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12829 if (AllBuildVectorsOrUndefs) {
12830 SmallVector<SDValue, 8> Opnds;
12831 EVT SVT = VT.getScalarType();
12834 if (!SVT.isFloatingPoint()) {
12835 // If BUILD_VECTOR are from built from integer, they may have different
12836 // operand types. Get the smallest type and truncate all operands to it.
12837 bool FoundMinVT = false;
12838 for (const SDValue &Op : N->ops())
12839 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12840 EVT OpSVT = Op.getOperand(0)->getValueType(0);
12841 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12844 assert(FoundMinVT && "Concat vector type mismatch");
12847 for (const SDValue &Op : N->ops()) {
12848 EVT OpVT = Op.getValueType();
12849 unsigned NumElts = OpVT.getVectorNumElements();
12851 if (ISD::UNDEF == Op.getOpcode())
12852 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12854 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12855 if (SVT.isFloatingPoint()) {
12856 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12857 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12859 for (unsigned i = 0; i != NumElts; ++i)
12861 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12866 assert(VT.getVectorNumElements() == Opnds.size() &&
12867 "Concat vector type mismatch");
12868 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12871 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12872 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12875 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
12876 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
12877 if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
12880 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12881 // nodes often generate nop CONCAT_VECTOR nodes.
12882 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12883 // place the incoming vectors at the exact same location.
12884 SDValue SingleSource = SDValue();
12885 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12887 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12888 SDValue Op = N->getOperand(i);
12890 if (Op.getOpcode() == ISD::UNDEF)
12893 // Check if this is the identity extract:
12894 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12897 // Find the single incoming vector for the extract_subvector.
12898 if (SingleSource.getNode()) {
12899 if (Op.getOperand(0) != SingleSource)
12902 SingleSource = Op.getOperand(0);
12904 // Check the source type is the same as the type of the result.
12905 // If not, this concat may extend the vector, so we can not
12906 // optimize it away.
12907 if (SingleSource.getValueType() != N->getValueType(0))
12911 unsigned IdentityIndex = i * PartNumElem;
12912 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12913 // The extract index must be constant.
12917 // Check that we are reading from the identity index.
12918 if (CS->getZExtValue() != IdentityIndex)
12922 if (SingleSource.getNode())
12923 return SingleSource;
12928 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12929 EVT NVT = N->getValueType(0);
12930 SDValue V = N->getOperand(0);
12932 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12934 // (extract_subvec (concat V1, V2, ...), i)
12937 // Only operand 0 is checked as 'concat' assumes all inputs of the same
12939 if (V->getOperand(0).getValueType() != NVT)
12941 unsigned Idx = N->getConstantOperandVal(1);
12942 unsigned NumElems = NVT.getVectorNumElements();
12943 assert((Idx % NumElems) == 0 &&
12944 "IDX in concat is not a multiple of the result vector length.");
12945 return V->getOperand(Idx / NumElems);
12949 if (V->getOpcode() == ISD::BITCAST)
12950 V = V.getOperand(0);
12952 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12954 // Handle only simple case where vector being inserted and vector
12955 // being extracted are of same type, and are half size of larger vectors.
12956 EVT BigVT = V->getOperand(0).getValueType();
12957 EVT SmallVT = V->getOperand(1).getValueType();
12958 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12961 // Only handle cases where both indexes are constants with the same type.
12962 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12963 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12965 if (InsIdx && ExtIdx &&
12966 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12967 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12969 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12971 // indices are equal or bit offsets are equal => V1
12972 // otherwise => (extract_subvec V1, ExtIdx)
12973 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12974 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12975 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12976 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12977 DAG.getNode(ISD::BITCAST, dl,
12978 N->getOperand(0).getValueType(),
12979 V->getOperand(0)), N->getOperand(1));
12986 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12987 SDValue V, SelectionDAG &DAG) {
12989 EVT VT = V.getValueType();
12991 switch (V.getOpcode()) {
12995 case ISD::CONCAT_VECTORS: {
12996 EVT OpVT = V->getOperand(0).getValueType();
12997 int OpSize = OpVT.getVectorNumElements();
12998 SmallBitVector OpUsedElements(OpSize, false);
12999 bool FoundSimplification = false;
13000 SmallVector<SDValue, 4> NewOps;
13001 NewOps.reserve(V->getNumOperands());
13002 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
13003 SDValue Op = V->getOperand(i);
13004 bool OpUsed = false;
13005 for (int j = 0; j < OpSize; ++j)
13006 if (UsedElements[i * OpSize + j]) {
13007 OpUsedElements[j] = true;
13011 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
13012 : DAG.getUNDEF(OpVT));
13013 FoundSimplification |= Op == NewOps.back();
13014 OpUsedElements.reset();
13016 if (FoundSimplification)
13017 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
13021 case ISD::INSERT_SUBVECTOR: {
13022 SDValue BaseV = V->getOperand(0);
13023 SDValue SubV = V->getOperand(1);
13024 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
13028 int SubSize = SubV.getValueType().getVectorNumElements();
13029 int Idx = IdxN->getZExtValue();
13030 bool SubVectorUsed = false;
13031 SmallBitVector SubUsedElements(SubSize, false);
13032 for (int i = 0; i < SubSize; ++i)
13033 if (UsedElements[i + Idx]) {
13034 SubVectorUsed = true;
13035 SubUsedElements[i] = true;
13036 UsedElements[i + Idx] = false;
13039 // Now recurse on both the base and sub vectors.
13040 SDValue SimplifiedSubV =
13042 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
13043 : DAG.getUNDEF(SubV.getValueType());
13044 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
13045 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
13046 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
13047 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
13053 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
13054 SDValue N1, SelectionDAG &DAG) {
13055 EVT VT = SVN->getValueType(0);
13056 int NumElts = VT.getVectorNumElements();
13057 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
13058 for (int M : SVN->getMask())
13059 if (M >= 0 && M < NumElts)
13060 N0UsedElements[M] = true;
13061 else if (M >= NumElts)
13062 N1UsedElements[M - NumElts] = true;
13064 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
13065 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
13066 if (S0 == N0 && S1 == N1)
13069 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
13072 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
13073 // or turn a shuffle of a single concat into simpler shuffle then concat.
13074 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
13075 EVT VT = N->getValueType(0);
13076 unsigned NumElts = VT.getVectorNumElements();
13078 SDValue N0 = N->getOperand(0);
13079 SDValue N1 = N->getOperand(1);
13080 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13082 SmallVector<SDValue, 4> Ops;
13083 EVT ConcatVT = N0.getOperand(0).getValueType();
13084 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
13085 unsigned NumConcats = NumElts / NumElemsPerConcat;
13087 // Special case: shuffle(concat(A,B)) can be more efficiently represented
13088 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
13089 // half vector elements.
13090 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
13091 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
13092 SVN->getMask().end(), [](int i) { return i == -1; })) {
13093 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
13094 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
13095 N1 = DAG.getUNDEF(ConcatVT);
13096 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
13099 // Look at every vector that's inserted. We're looking for exact
13100 // subvector-sized copies from a concatenated vector
13101 for (unsigned I = 0; I != NumConcats; ++I) {
13102 // Make sure we're dealing with a copy.
13103 unsigned Begin = I * NumElemsPerConcat;
13104 bool AllUndef = true, NoUndef = true;
13105 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
13106 if (SVN->getMaskElt(J) >= 0)
13113 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
13116 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
13117 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
13120 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
13121 if (FirstElt < N0.getNumOperands())
13122 Ops.push_back(N0.getOperand(FirstElt));
13124 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
13126 } else if (AllUndef) {
13127 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
13128 } else { // Mixed with general masks and undefs, can't do optimization.
13133 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
13136 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
13137 EVT VT = N->getValueType(0);
13138 unsigned NumElts = VT.getVectorNumElements();
13140 SDValue N0 = N->getOperand(0);
13141 SDValue N1 = N->getOperand(1);
13143 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
13145 // Canonicalize shuffle undef, undef -> undef
13146 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
13147 return DAG.getUNDEF(VT);
13149 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13151 // Canonicalize shuffle v, v -> v, undef
13153 SmallVector<int, 8> NewMask;
13154 for (unsigned i = 0; i != NumElts; ++i) {
13155 int Idx = SVN->getMaskElt(i);
13156 if (Idx >= (int)NumElts) Idx -= NumElts;
13157 NewMask.push_back(Idx);
13159 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
13163 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
13164 if (N0.getOpcode() == ISD::UNDEF) {
13165 SmallVector<int, 8> NewMask;
13166 for (unsigned i = 0; i != NumElts; ++i) {
13167 int Idx = SVN->getMaskElt(i);
13169 if (Idx >= (int)NumElts)
13172 Idx = -1; // remove reference to lhs
13174 NewMask.push_back(Idx);
13176 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
13180 // Remove references to rhs if it is undef
13181 if (N1.getOpcode() == ISD::UNDEF) {
13182 bool Changed = false;
13183 SmallVector<int, 8> NewMask;
13184 for (unsigned i = 0; i != NumElts; ++i) {
13185 int Idx = SVN->getMaskElt(i);
13186 if (Idx >= (int)NumElts) {
13190 NewMask.push_back(Idx);
13193 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
13196 // If it is a splat, check if the argument vector is another splat or a
13198 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
13199 SDNode *V = N0.getNode();
13201 // If this is a bit convert that changes the element type of the vector but
13202 // not the number of vector elements, look through it. Be careful not to
13203 // look though conversions that change things like v4f32 to v2f64.
13204 if (V->getOpcode() == ISD::BITCAST) {
13205 SDValue ConvInput = V->getOperand(0);
13206 if (ConvInput.getValueType().isVector() &&
13207 ConvInput.getValueType().getVectorNumElements() == NumElts)
13208 V = ConvInput.getNode();
13211 if (V->getOpcode() == ISD::BUILD_VECTOR) {
13212 assert(V->getNumOperands() == NumElts &&
13213 "BUILD_VECTOR has wrong number of operands");
13215 bool AllSame = true;
13216 for (unsigned i = 0; i != NumElts; ++i) {
13217 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
13218 Base = V->getOperand(i);
13222 // Splat of <u, u, u, u>, return <u, u, u, u>
13223 if (!Base.getNode())
13225 for (unsigned i = 0; i != NumElts; ++i) {
13226 if (V->getOperand(i) != Base) {
13231 // Splat of <x, x, x, x>, return <x, x, x, x>
13235 // Canonicalize any other splat as a build_vector.
13236 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
13237 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
13238 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
13239 V->getValueType(0), Ops);
13241 // We may have jumped through bitcasts, so the type of the
13242 // BUILD_VECTOR may not match the type of the shuffle.
13243 if (V->getValueType(0) != VT)
13244 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
13249 // There are various patterns used to build up a vector from smaller vectors,
13250 // subvectors, or elements. Scan chains of these and replace unused insertions
13251 // or components with undef.
13252 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13255 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13256 Level < AfterLegalizeVectorOps &&
13257 (N1.getOpcode() == ISD::UNDEF ||
13258 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13259 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13260 SDValue V = partitionShuffleOfConcats(N, DAG);
13266 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13267 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13268 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
13269 SmallVector<SDValue, 8> Ops;
13270 for (int M : SVN->getMask()) {
13271 SDValue Op = DAG.getUNDEF(VT.getScalarType());
13273 int Idx = M % NumElts;
13274 SDValue &S = (M < (int)NumElts ? N0 : N1);
13275 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
13276 Op = S.getOperand(Idx);
13277 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
13279 Op = S.getOperand(0);
13281 // Operand can't be combined - bail out.
13287 if (Ops.size() == VT.getVectorNumElements()) {
13288 // BUILD_VECTOR requires all inputs to be of the same type, find the
13289 // maximum type and extend them all.
13290 EVT SVT = VT.getScalarType();
13291 if (SVT.isInteger())
13292 for (SDValue &Op : Ops)
13293 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13294 if (SVT != VT.getScalarType())
13295 for (SDValue &Op : Ops)
13296 Op = TLI.isZExtFree(Op.getValueType(), SVT)
13297 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
13298 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
13299 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
13303 // If this shuffle only has a single input that is a bitcasted shuffle,
13304 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13305 // back to their original types.
13306 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13307 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
13308 TLI.isTypeLegal(VT)) {
13310 // Peek through the bitcast only if there is one user.
13312 while (BC0.getOpcode() == ISD::BITCAST) {
13313 if (!BC0.hasOneUse())
13315 BC0 = BC0.getOperand(0);
13318 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13320 return SmallVector<int, 8>(Mask.begin(), Mask.end());
13322 SmallVector<int, 8> NewMask;
13324 for (int s = 0; s != Scale; ++s)
13325 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13329 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13330 EVT SVT = VT.getScalarType();
13331 EVT InnerVT = BC0->getValueType(0);
13332 EVT InnerSVT = InnerVT.getScalarType();
13334 // Determine which shuffle works with the smaller scalar type.
13335 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13336 EVT ScaleSVT = ScaleVT.getScalarType();
13338 if (TLI.isTypeLegal(ScaleVT) &&
13339 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13340 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13342 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13343 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13345 // Scale the shuffle masks to the smaller scalar type.
13346 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13347 SmallVector<int, 8> InnerMask =
13348 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13349 SmallVector<int, 8> OuterMask =
13350 ScaleShuffleMask(SVN->getMask(), OuterScale);
13352 // Merge the shuffle masks.
13353 SmallVector<int, 8> NewMask;
13354 for (int M : OuterMask)
13355 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13357 // Test for shuffle mask legality over both commutations.
13358 SDValue SV0 = BC0->getOperand(0);
13359 SDValue SV1 = BC0->getOperand(1);
13360 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13362 std::swap(SV0, SV1);
13363 ShuffleVectorSDNode::commuteMask(NewMask);
13364 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13368 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
13369 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
13370 return DAG.getNode(
13371 ISD::BITCAST, SDLoc(N), VT,
13372 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13378 // Canonicalize shuffles according to rules:
13379 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13380 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13381 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13382 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13383 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
13384 TLI.isTypeLegal(VT)) {
13385 // The incoming shuffle must be of the same type as the result of the
13386 // current shuffle.
13387 assert(N1->getOperand(0).getValueType() == VT &&
13388 "Shuffle types don't match");
13390 SDValue SV0 = N1->getOperand(0);
13391 SDValue SV1 = N1->getOperand(1);
13392 bool HasSameOp0 = N0 == SV0;
13393 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
13394 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13395 // Commute the operands of this shuffle so that next rule
13397 return DAG.getCommutedVectorShuffle(*SVN);
13400 // Try to fold according to rules:
13401 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13402 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13403 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13404 // Don't try to fold shuffles with illegal type.
13405 // Only fold if this shuffle is the only user of the other shuffle.
13406 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13407 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13408 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13410 // The incoming shuffle must be of the same type as the result of the
13411 // current shuffle.
13412 assert(OtherSV->getOperand(0).getValueType() == VT &&
13413 "Shuffle types don't match");
13416 SmallVector<int, 4> Mask;
13417 // Compute the combined shuffle mask for a shuffle with SV0 as the first
13418 // operand, and SV1 as the second operand.
13419 for (unsigned i = 0; i != NumElts; ++i) {
13420 int Idx = SVN->getMaskElt(i);
13422 // Propagate Undef.
13423 Mask.push_back(Idx);
13427 SDValue CurrentVec;
13428 if (Idx < (int)NumElts) {
13429 // This shuffle index refers to the inner shuffle N0. Lookup the inner
13430 // shuffle mask to identify which vector is actually referenced.
13431 Idx = OtherSV->getMaskElt(Idx);
13433 // Propagate Undef.
13434 Mask.push_back(Idx);
13438 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13439 : OtherSV->getOperand(1);
13441 // This shuffle index references an element within N1.
13445 // Simple case where 'CurrentVec' is UNDEF.
13446 if (CurrentVec.getOpcode() == ISD::UNDEF) {
13447 Mask.push_back(-1);
13451 // Canonicalize the shuffle index. We don't know yet if CurrentVec
13452 // will be the first or second operand of the combined shuffle.
13453 Idx = Idx % NumElts;
13454 if (!SV0.getNode() || SV0 == CurrentVec) {
13455 // Ok. CurrentVec is the left hand side.
13456 // Update the mask accordingly.
13458 Mask.push_back(Idx);
13462 // Bail out if we cannot convert the shuffle pair into a single shuffle.
13463 if (SV1.getNode() && SV1 != CurrentVec)
13466 // Ok. CurrentVec is the right hand side.
13467 // Update the mask accordingly.
13469 Mask.push_back(Idx + NumElts);
13472 // Check if all indices in Mask are Undef. In case, propagate Undef.
13473 bool isUndefMask = true;
13474 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13475 isUndefMask &= Mask[i] < 0;
13478 return DAG.getUNDEF(VT);
13480 if (!SV0.getNode())
13481 SV0 = DAG.getUNDEF(VT);
13482 if (!SV1.getNode())
13483 SV1 = DAG.getUNDEF(VT);
13485 // Avoid introducing shuffles with illegal mask.
13486 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13487 ShuffleVectorSDNode::commuteMask(Mask);
13489 if (!TLI.isShuffleMaskLegal(Mask, VT))
13492 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13493 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13494 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13495 std::swap(SV0, SV1);
13498 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13499 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13500 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13501 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13507 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13508 SDValue InVal = N->getOperand(0);
13509 EVT VT = N->getValueType(0);
13511 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13512 // with a VECTOR_SHUFFLE.
13513 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13514 SDValue InVec = InVal->getOperand(0);
13515 SDValue EltNo = InVal->getOperand(1);
13517 // FIXME: We could support implicit truncation if the shuffle can be
13518 // scaled to a smaller vector scalar type.
13519 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13520 if (C0 && VT == InVec.getValueType() &&
13521 VT.getScalarType() == InVal.getValueType()) {
13522 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13523 int Elt = C0->getZExtValue();
13526 if (TLI.isShuffleMaskLegal(NewMask, VT))
13527 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13535 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13536 SDValue N0 = N->getOperand(0);
13537 SDValue N2 = N->getOperand(2);
13539 // If the input vector is a concatenation, and the insert replaces
13540 // one of the halves, we can optimize into a single concat_vectors.
13541 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13542 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13543 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13544 EVT VT = N->getValueType(0);
13546 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13547 // (concat_vectors Z, Y)
13549 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13550 N->getOperand(1), N0.getOperand(1));
13552 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13553 // (concat_vectors X, Z)
13554 if (InsIdx == VT.getVectorNumElements()/2)
13555 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13556 N0.getOperand(0), N->getOperand(1));
13562 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13563 SDValue N0 = N->getOperand(0);
13565 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13566 if (N0->getOpcode() == ISD::FP16_TO_FP)
13567 return N0->getOperand(0);
13572 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13573 SDValue N0 = N->getOperand(0);
13575 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13576 if (N0->getOpcode() == ISD::AND) {
13577 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13578 if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13579 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13587 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13588 /// with the destination vector and a zero vector.
13589 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13590 /// vector_shuffle V, Zero, <0, 4, 2, 4>
13591 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13592 EVT VT = N->getValueType(0);
13593 SDValue LHS = N->getOperand(0);
13594 SDValue RHS = N->getOperand(1);
13597 // Make sure we're not running after operation legalization where it
13598 // may have custom lowered the vector shuffles.
13599 if (LegalOperations)
13602 if (N->getOpcode() != ISD::AND)
13605 if (RHS.getOpcode() == ISD::BITCAST)
13606 RHS = RHS.getOperand(0);
13608 if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13611 EVT RVT = RHS.getValueType();
13612 unsigned NumElts = RHS.getNumOperands();
13614 // Attempt to create a valid clear mask, splitting the mask into
13615 // sub elements and checking to see if each is
13616 // all zeros or all ones - suitable for shuffle masking.
13617 auto BuildClearMask = [&](int Split) {
13618 int NumSubElts = NumElts * Split;
13619 int NumSubBits = RVT.getScalarSizeInBits() / Split;
13621 SmallVector<int, 8> Indices;
13622 for (int i = 0; i != NumSubElts; ++i) {
13623 int EltIdx = i / Split;
13624 int SubIdx = i % Split;
13625 SDValue Elt = RHS.getOperand(EltIdx);
13626 if (Elt.getOpcode() == ISD::UNDEF) {
13627 Indices.push_back(-1);
13632 if (isa<ConstantSDNode>(Elt))
13633 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13634 else if (isa<ConstantFPSDNode>(Elt))
13635 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13639 // Extract the sub element from the constant bit mask.
13640 if (DAG.getDataLayout().isBigEndian()) {
13641 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13643 Bits = Bits.lshr(SubIdx * NumSubBits);
13647 Bits = Bits.trunc(NumSubBits);
13649 if (Bits.isAllOnesValue())
13650 Indices.push_back(i);
13651 else if (Bits == 0)
13652 Indices.push_back(i + NumSubElts);
13657 // Let's see if the target supports this vector_shuffle.
13658 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13659 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13660 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13663 SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13664 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13665 DAG.getBitcast(ClearVT, LHS),
13666 Zero, &Indices[0]));
13669 // Determine maximum split level (byte level masking).
13671 if (RVT.getScalarSizeInBits() % 8 == 0)
13672 MaxSplit = RVT.getScalarSizeInBits() / 8;
13674 for (int Split = 1; Split <= MaxSplit; ++Split)
13675 if (RVT.getScalarSizeInBits() % Split == 0)
13676 if (SDValue S = BuildClearMask(Split))
13682 /// Visit a binary vector operation, like ADD.
13683 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13684 assert(N->getValueType(0).isVector() &&
13685 "SimplifyVBinOp only works on vectors!");
13687 SDValue LHS = N->getOperand(0);
13688 SDValue RHS = N->getOperand(1);
13689 SDValue Ops[] = {LHS, RHS};
13691 // See if we can constant fold the vector operation.
13692 if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
13693 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
13696 // Try to convert a constant mask AND into a shuffle clear mask.
13697 if (SDValue Shuffle = XformToShuffleWithZero(N))
13700 // Type legalization might introduce new shuffles in the DAG.
13701 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13702 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
13703 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13704 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13705 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13706 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13707 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13708 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13710 if (SVN0->getMask().equals(SVN1->getMask())) {
13711 EVT VT = N->getValueType(0);
13712 SDValue UndefVector = LHS.getOperand(1);
13713 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13714 LHS.getOperand(0), RHS.getOperand(0),
13716 AddUsersToWorklist(N);
13717 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13718 &SVN0->getMask()[0]);
13725 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13726 SDValue N1, SDValue N2){
13727 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13729 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13730 cast<CondCodeSDNode>(N0.getOperand(2))->get());
13732 // If we got a simplified select_cc node back from SimplifySelectCC, then
13733 // break it down into a new SETCC node, and a new SELECT node, and then return
13734 // the SELECT node, since we were called with a SELECT node.
13735 if (SCC.getNode()) {
13736 // Check to see if we got a select_cc back (to turn into setcc/select).
13737 // Otherwise, just return whatever node we got back, like fabs.
13738 if (SCC.getOpcode() == ISD::SELECT_CC) {
13739 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13741 SCC.getOperand(0), SCC.getOperand(1),
13742 SCC.getOperand(4));
13743 AddToWorklist(SETCC.getNode());
13744 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13745 SCC.getOperand(2), SCC.getOperand(3));
13753 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13754 /// being selected between, see if we can simplify the select. Callers of this
13755 /// should assume that TheSelect is deleted if this returns true. As such, they
13756 /// should return the appropriate thing (e.g. the node) back to the top-level of
13757 /// the DAG combiner loop to avoid it being looked at.
13758 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13761 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13762 // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13763 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13764 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13765 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13766 SDValue Sqrt = RHS;
13769 const ConstantFPSDNode *NegZero = nullptr;
13771 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13772 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13773 CmpLHS = TheSelect->getOperand(0);
13774 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13776 // SELECT or VSELECT
13777 SDValue Cmp = TheSelect->getOperand(0);
13778 if (Cmp.getOpcode() == ISD::SETCC) {
13779 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13780 CmpLHS = Cmp.getOperand(0);
13781 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13784 if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13785 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13786 CC == ISD::SETULT || CC == ISD::SETLT)) {
13787 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13788 CombineTo(TheSelect, Sqrt);
13793 // Cannot simplify select with vector condition
13794 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13796 // If this is a select from two identical things, try to pull the operation
13797 // through the select.
13798 if (LHS.getOpcode() != RHS.getOpcode() ||
13799 !LHS.hasOneUse() || !RHS.hasOneUse())
13802 // If this is a load and the token chain is identical, replace the select
13803 // of two loads with a load through a select of the address to load from.
13804 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13805 // constants have been dropped into the constant pool.
13806 if (LHS.getOpcode() == ISD::LOAD) {
13807 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13808 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13810 // Token chains must be identical.
13811 if (LHS.getOperand(0) != RHS.getOperand(0) ||
13812 // Do not let this transformation reduce the number of volatile loads.
13813 LLD->isVolatile() || RLD->isVolatile() ||
13814 // FIXME: If either is a pre/post inc/dec load,
13815 // we'd need to split out the address adjustment.
13816 LLD->isIndexed() || RLD->isIndexed() ||
13817 // If this is an EXTLOAD, the VT's must match.
13818 LLD->getMemoryVT() != RLD->getMemoryVT() ||
13819 // If this is an EXTLOAD, the kind of extension must match.
13820 (LLD->getExtensionType() != RLD->getExtensionType() &&
13821 // The only exception is if one of the extensions is anyext.
13822 LLD->getExtensionType() != ISD::EXTLOAD &&
13823 RLD->getExtensionType() != ISD::EXTLOAD) ||
13824 // FIXME: this discards src value information. This is
13825 // over-conservative. It would be beneficial to be able to remember
13826 // both potential memory locations. Since we are discarding
13827 // src value info, don't do the transformation if the memory
13828 // locations are not in the default address space.
13829 LLD->getPointerInfo().getAddrSpace() != 0 ||
13830 RLD->getPointerInfo().getAddrSpace() != 0 ||
13831 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13832 LLD->getBasePtr().getValueType()))
13835 // Check that the select condition doesn't reach either load. If so,
13836 // folding this will induce a cycle into the DAG. If not, this is safe to
13837 // xform, so create a select of the addresses.
13839 if (TheSelect->getOpcode() == ISD::SELECT) {
13840 SDNode *CondNode = TheSelect->getOperand(0).getNode();
13841 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13842 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13844 // The loads must not depend on one another.
13845 if (LLD->isPredecessorOf(RLD) ||
13846 RLD->isPredecessorOf(LLD))
13848 Addr = DAG.getSelect(SDLoc(TheSelect),
13849 LLD->getBasePtr().getValueType(),
13850 TheSelect->getOperand(0), LLD->getBasePtr(),
13851 RLD->getBasePtr());
13852 } else { // Otherwise SELECT_CC
13853 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13854 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13856 if ((LLD->hasAnyUseOfValue(1) &&
13857 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13858 (RLD->hasAnyUseOfValue(1) &&
13859 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13862 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13863 LLD->getBasePtr().getValueType(),
13864 TheSelect->getOperand(0),
13865 TheSelect->getOperand(1),
13866 LLD->getBasePtr(), RLD->getBasePtr(),
13867 TheSelect->getOperand(4));
13871 // It is safe to replace the two loads if they have different alignments,
13872 // but the new load must be the minimum (most restrictive) alignment of the
13874 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13875 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13876 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13877 Load = DAG.getLoad(TheSelect->getValueType(0),
13879 // FIXME: Discards pointer and AA info.
13880 LLD->getChain(), Addr, MachinePointerInfo(),
13881 LLD->isVolatile(), LLD->isNonTemporal(),
13882 isInvariant, Alignment);
13884 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13885 RLD->getExtensionType() : LLD->getExtensionType(),
13887 TheSelect->getValueType(0),
13888 // FIXME: Discards pointer and AA info.
13889 LLD->getChain(), Addr, MachinePointerInfo(),
13890 LLD->getMemoryVT(), LLD->isVolatile(),
13891 LLD->isNonTemporal(), isInvariant, Alignment);
13894 // Users of the select now use the result of the load.
13895 CombineTo(TheSelect, Load);
13897 // Users of the old loads now use the new load's chain. We know the
13898 // old-load value is dead now.
13899 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13900 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13907 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13908 /// where 'cond' is the comparison specified by CC.
13909 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13910 SDValue N2, SDValue N3,
13911 ISD::CondCode CC, bool NotExtCompare) {
13912 // (x ? y : y) -> y.
13913 if (N2 == N3) return N2;
13915 EVT VT = N2.getValueType();
13916 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13917 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13919 // Determine if the condition we're dealing with is constant
13920 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13921 N0, N1, CC, DL, false);
13922 if (SCC.getNode()) AddToWorklist(SCC.getNode());
13924 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13925 // fold select_cc true, x, y -> x
13926 // fold select_cc false, x, y -> y
13927 return !SCCC->isNullValue() ? N2 : N3;
13930 // Check to see if we can simplify the select into an fabs node
13931 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13932 // Allow either -0.0 or 0.0
13933 if (CFP->isZero()) {
13934 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13935 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13936 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13937 N2 == N3.getOperand(0))
13938 return DAG.getNode(ISD::FABS, DL, VT, N0);
13940 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13941 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13942 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13943 N2.getOperand(0) == N3)
13944 return DAG.getNode(ISD::FABS, DL, VT, N3);
13948 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13949 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13950 // in it. This is a win when the constant is not otherwise available because
13951 // it replaces two constant pool loads with one. We only do this if the FP
13952 // type is known to be legal, because if it isn't, then we are before legalize
13953 // types an we want the other legalization to happen first (e.g. to avoid
13954 // messing with soft float) and if the ConstantFP is not legal, because if
13955 // it is legal, we may not need to store the FP constant in a constant pool.
13956 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13957 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13958 if (TLI.isTypeLegal(N2.getValueType()) &&
13959 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13960 TargetLowering::Legal &&
13961 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13962 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13963 // If both constants have multiple uses, then we won't need to do an
13964 // extra load, they are likely around in registers for other users.
13965 (TV->hasOneUse() || FV->hasOneUse())) {
13966 Constant *Elts[] = {
13967 const_cast<ConstantFP*>(FV->getConstantFPValue()),
13968 const_cast<ConstantFP*>(TV->getConstantFPValue())
13970 Type *FPTy = Elts[0]->getType();
13971 const DataLayout &TD = DAG.getDataLayout();
13973 // Create a ConstantArray of the two constants.
13974 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13976 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
13977 TD.getPrefTypeAlignment(FPTy));
13978 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13980 // Get the offsets to the 0 and 1 element of the array so that we can
13981 // select between them.
13982 SDValue Zero = DAG.getIntPtrConstant(0, DL);
13983 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13984 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13986 SDValue Cond = DAG.getSetCC(DL,
13987 getSetCCResultType(N0.getValueType()),
13989 AddToWorklist(Cond.getNode());
13990 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13992 AddToWorklist(CstOffset.getNode());
13993 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13995 AddToWorklist(CPIdx.getNode());
13996 return DAG.getLoad(
13997 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13998 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13999 false, false, false, Alignment);
14003 // Check to see if we can perform the "gzip trick", transforming
14004 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
14005 if (isNullConstant(N3) && CC == ISD::SETLT &&
14006 (isNullConstant(N1) || // (a < 0) ? b : 0
14007 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0
14008 EVT XType = N0.getValueType();
14009 EVT AType = N2.getValueType();
14010 if (XType.bitsGE(AType)) {
14011 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
14012 // single-bit constant.
14013 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
14014 unsigned ShCtV = N2C->getAPIntValue().logBase2();
14015 ShCtV = XType.getSizeInBits() - ShCtV - 1;
14016 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
14017 getShiftAmountTy(N0.getValueType()));
14018 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
14020 AddToWorklist(Shift.getNode());
14022 if (XType.bitsGT(AType)) {
14023 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14024 AddToWorklist(Shift.getNode());
14027 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14030 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
14032 DAG.getConstant(XType.getSizeInBits() - 1,
14034 getShiftAmountTy(N0.getValueType())));
14035 AddToWorklist(Shift.getNode());
14037 if (XType.bitsGT(AType)) {
14038 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14039 AddToWorklist(Shift.getNode());
14042 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14046 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
14047 // where y is has a single bit set.
14048 // A plaintext description would be, we can turn the SELECT_CC into an AND
14049 // when the condition can be materialized as an all-ones register. Any
14050 // single bit-test can be materialized as an all-ones register with
14051 // shift-left and shift-right-arith.
14052 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
14053 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
14054 SDValue AndLHS = N0->getOperand(0);
14055 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
14056 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
14057 // Shift the tested bit over the sign bit.
14058 APInt AndMask = ConstAndRHS->getAPIntValue();
14060 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
14061 getShiftAmountTy(AndLHS.getValueType()));
14062 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
14064 // Now arithmetic right shift it all the way over, so the result is either
14065 // all-ones, or zero.
14067 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
14068 getShiftAmountTy(Shl.getValueType()));
14069 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
14071 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
14075 // fold select C, 16, 0 -> shl C, 4
14076 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
14077 TLI.getBooleanContents(N0.getValueType()) ==
14078 TargetLowering::ZeroOrOneBooleanContent) {
14080 // If the caller doesn't want us to simplify this into a zext of a compare,
14082 if (NotExtCompare && N2C->isOne())
14085 // Get a SetCC of the condition
14086 // NOTE: Don't create a SETCC if it's not legal on this target.
14087 if (!LegalOperations ||
14088 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
14090 // cast from setcc result type to select result type
14092 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
14094 if (N2.getValueType().bitsLT(SCC.getValueType()))
14095 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
14096 N2.getValueType());
14098 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14099 N2.getValueType(), SCC);
14101 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
14102 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14103 N2.getValueType(), SCC);
14106 AddToWorklist(SCC.getNode());
14107 AddToWorklist(Temp.getNode());
14112 // shl setcc result by log2 n2c
14113 return DAG.getNode(
14114 ISD::SHL, DL, N2.getValueType(), Temp,
14115 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
14116 getShiftAmountTy(Temp.getValueType())));
14120 // Check to see if this is an integer abs.
14121 // select_cc setg[te] X, 0, X, -X ->
14122 // select_cc setgt X, -1, X, -X ->
14123 // select_cc setl[te] X, 0, -X, X ->
14124 // select_cc setlt X, 1, -X, X ->
14125 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
14127 ConstantSDNode *SubC = nullptr;
14128 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
14129 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
14130 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
14131 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
14132 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
14133 (N1C->isOne() && CC == ISD::SETLT)) &&
14134 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
14135 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
14137 EVT XType = N0.getValueType();
14138 if (SubC && SubC->isNullValue() && XType.isInteger()) {
14140 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
14142 DAG.getConstant(XType.getSizeInBits() - 1, DL,
14143 getShiftAmountTy(N0.getValueType())));
14144 SDValue Add = DAG.getNode(ISD::ADD, DL,
14146 AddToWorklist(Shift.getNode());
14147 AddToWorklist(Add.getNode());
14148 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
14155 /// This is a stub for TargetLowering::SimplifySetCC.
14156 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
14157 SDValue N1, ISD::CondCode Cond,
14158 SDLoc DL, bool foldBooleans) {
14159 TargetLowering::DAGCombinerInfo
14160 DagCombineInfo(DAG, Level, false, this);
14161 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
14164 /// Given an ISD::SDIV node expressing a divide by constant, return
14165 /// a DAG expression to select that will generate the same value by multiplying
14166 /// by a magic number.
14167 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14168 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
14169 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14173 // Avoid division by zero.
14174 if (C->isNullValue())
14177 std::vector<SDNode*> Built;
14179 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14181 for (SDNode *N : Built)
14186 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
14187 /// DAG expression that will generate the same value by right shifting.
14188 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
14189 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14193 // Avoid division by zero.
14194 if (C->isNullValue())
14197 std::vector<SDNode *> Built;
14198 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
14200 for (SDNode *N : Built)
14205 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
14206 /// expression that will generate the same value by multiplying by a magic
14208 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14209 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
14210 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14214 // Avoid division by zero.
14215 if (C->isNullValue())
14218 std::vector<SDNode*> Built;
14220 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14222 for (SDNode *N : Built)
14227 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
14228 if (Level >= AfterLegalizeDAG)
14231 // Expose the DAG combiner to the target combiner implementations.
14232 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14234 unsigned Iterations = 0;
14235 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
14237 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14238 // For the reciprocal, we need to find the zero of the function:
14239 // F(X) = A X - 1 [which has a zero at X = 1/A]
14241 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
14242 // does not require additional intermediate precision]
14243 EVT VT = Op.getValueType();
14245 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
14247 AddToWorklist(Est.getNode());
14249 // Newton iterations: Est = Est + Est (1 - Arg * Est)
14250 for (unsigned i = 0; i < Iterations; ++i) {
14251 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14252 AddToWorklist(NewEst.getNode());
14254 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14255 AddToWorklist(NewEst.getNode());
14257 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14258 AddToWorklist(NewEst.getNode());
14260 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14261 AddToWorklist(Est.getNode());
14270 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14271 /// For the reciprocal sqrt, we need to find the zero of the function:
14272 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14274 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14275 /// As a result, we precompute A/2 prior to the iteration loop.
14276 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
14277 unsigned Iterations,
14278 SDNodeFlags *Flags) {
14279 EVT VT = Arg.getValueType();
14281 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14283 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14284 // this entire sequence requires only one FP constant.
14285 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14286 AddToWorklist(HalfArg.getNode());
14288 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14289 AddToWorklist(HalfArg.getNode());
14291 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14292 for (unsigned i = 0; i < Iterations; ++i) {
14293 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14294 AddToWorklist(NewEst.getNode());
14296 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14297 AddToWorklist(NewEst.getNode());
14299 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14300 AddToWorklist(NewEst.getNode());
14302 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14303 AddToWorklist(Est.getNode());
14308 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14309 /// For the reciprocal sqrt, we need to find the zero of the function:
14310 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14312 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14313 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
14314 unsigned Iterations,
14315 SDNodeFlags *Flags) {
14316 EVT VT = Arg.getValueType();
14318 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
14319 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
14321 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
14322 for (unsigned i = 0; i < Iterations; ++i) {
14323 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
14324 AddToWorklist(HalfEst.getNode());
14326 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14327 AddToWorklist(Est.getNode());
14329 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14330 AddToWorklist(Est.getNode());
14332 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags);
14333 AddToWorklist(Est.getNode());
14335 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags);
14336 AddToWorklist(Est.getNode());
14341 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14342 if (Level >= AfterLegalizeDAG)
14345 // Expose the DAG combiner to the target combiner implementations.
14346 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14347 unsigned Iterations = 0;
14348 bool UseOneConstNR = false;
14349 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
14350 AddToWorklist(Est.getNode());
14352 Est = UseOneConstNR ?
14353 BuildRsqrtNROneConst(Op, Est, Iterations, Flags) :
14354 BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags);
14362 /// Return true if base is a frame index, which is known not to alias with
14363 /// anything but itself. Provides base object and offset as results.
14364 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14365 const GlobalValue *&GV, const void *&CV) {
14366 // Assume it is a primitive operation.
14367 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14369 // If it's an adding a simple constant then integrate the offset.
14370 if (Base.getOpcode() == ISD::ADD) {
14371 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14372 Base = Base.getOperand(0);
14373 Offset += C->getZExtValue();
14377 // Return the underlying GlobalValue, and update the Offset. Return false
14378 // for GlobalAddressSDNode since the same GlobalAddress may be represented
14379 // by multiple nodes with different offsets.
14380 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14381 GV = G->getGlobal();
14382 Offset += G->getOffset();
14386 // Return the underlying Constant value, and update the Offset. Return false
14387 // for ConstantSDNodes since the same constant pool entry may be represented
14388 // by multiple nodes with different offsets.
14389 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14390 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14391 : (const void *)C->getConstVal();
14392 Offset += C->getOffset();
14395 // If it's any of the following then it can't alias with anything but itself.
14396 return isa<FrameIndexSDNode>(Base);
14399 /// Return true if there is any possibility that the two addresses overlap.
14400 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14401 // If they are the same then they must be aliases.
14402 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14404 // If they are both volatile then they cannot be reordered.
14405 if (Op0->isVolatile() && Op1->isVolatile()) return true;
14407 // If one operation reads from invariant memory, and the other may store, they
14408 // cannot alias. These should really be checking the equivalent of mayWrite,
14409 // but it only matters for memory nodes other than load /store.
14410 if (Op0->isInvariant() && Op1->writeMem())
14413 if (Op1->isInvariant() && Op0->writeMem())
14416 // Gather base node and offset information.
14417 SDValue Base1, Base2;
14418 int64_t Offset1, Offset2;
14419 const GlobalValue *GV1, *GV2;
14420 const void *CV1, *CV2;
14421 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14422 Base1, Offset1, GV1, CV1);
14423 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14424 Base2, Offset2, GV2, CV2);
14426 // If they have a same base address then check to see if they overlap.
14427 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14428 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14429 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14431 // It is possible for different frame indices to alias each other, mostly
14432 // when tail call optimization reuses return address slots for arguments.
14433 // To catch this case, look up the actual index of frame indices to compute
14434 // the real alias relationship.
14435 if (isFrameIndex1 && isFrameIndex2) {
14436 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14437 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14438 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14439 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14440 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14443 // Otherwise, if we know what the bases are, and they aren't identical, then
14444 // we know they cannot alias.
14445 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14448 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14449 // compared to the size and offset of the access, we may be able to prove they
14450 // do not alias. This check is conservative for now to catch cases created by
14451 // splitting vector types.
14452 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14453 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14454 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14455 Op1->getMemoryVT().getSizeInBits() >> 3) &&
14456 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14457 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14458 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14460 // There is no overlap between these relatively aligned accesses of similar
14461 // size, return no alias.
14462 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14463 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14467 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14469 : DAG.getSubtarget().useAA();
14471 if (CombinerAAOnlyFunc.getNumOccurrences() &&
14472 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14476 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14477 // Use alias analysis information.
14478 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14479 Op1->getSrcValueOffset());
14480 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14481 Op0->getSrcValueOffset() - MinOffset;
14482 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14483 Op1->getSrcValueOffset() - MinOffset;
14484 AliasResult AAResult =
14485 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14486 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14487 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14488 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14489 if (AAResult == NoAlias)
14493 // Otherwise we have to assume they alias.
14497 /// Walk up chain skipping non-aliasing memory nodes,
14498 /// looking for aliasing nodes and adding them to the Aliases vector.
14499 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14500 SmallVectorImpl<SDValue> &Aliases) {
14501 SmallVector<SDValue, 8> Chains; // List of chains to visit.
14502 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
14504 // Get alias information for node.
14505 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14508 Chains.push_back(OriginalChain);
14509 unsigned Depth = 0;
14511 // Look at each chain and determine if it is an alias. If so, add it to the
14512 // aliases list. If not, then continue up the chain looking for the next
14514 while (!Chains.empty()) {
14515 SDValue Chain = Chains.pop_back_val();
14517 // For TokenFactor nodes, look at each operand and only continue up the
14518 // chain until we reach the depth limit.
14520 // FIXME: The depth check could be made to return the last non-aliasing
14521 // chain we found before we hit a tokenfactor rather than the original
14523 if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
14525 Aliases.push_back(OriginalChain);
14529 // Don't bother if we've been before.
14530 if (!Visited.insert(Chain.getNode()).second)
14533 switch (Chain.getOpcode()) {
14534 case ISD::EntryToken:
14535 // Entry token is ideal chain operand, but handled in FindBetterChain.
14540 // Get alias information for Chain.
14541 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14542 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14544 // If chain is alias then stop here.
14545 if (!(IsLoad && IsOpLoad) &&
14546 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14547 Aliases.push_back(Chain);
14549 // Look further up the chain.
14550 Chains.push_back(Chain.getOperand(0));
14556 case ISD::TokenFactor:
14557 // We have to check each of the operands of the token factor for "small"
14558 // token factors, so we queue them up. Adding the operands to the queue
14559 // (stack) in reverse order maintains the original order and increases the
14560 // likelihood that getNode will find a matching token factor (CSE.)
14561 if (Chain.getNumOperands() > 16) {
14562 Aliases.push_back(Chain);
14565 for (unsigned n = Chain.getNumOperands(); n;)
14566 Chains.push_back(Chain.getOperand(--n));
14571 // For all other instructions we will just have to take what we can get.
14572 Aliases.push_back(Chain);
14577 // We need to be careful here to also search for aliases through the
14578 // value operand of a store, etc. Consider the following situation:
14580 // L1 = load Token1, %52
14581 // S1 = store Token1, L1, %51
14582 // L2 = load Token1, %52+8
14583 // S2 = store Token1, L2, %51+8
14584 // Token2 = Token(S1, S2)
14585 // L3 = load Token2, %53
14586 // S3 = store Token2, L3, %52
14587 // L4 = load Token2, %53+8
14588 // S4 = store Token2, L4, %52+8
14589 // If we search for aliases of S3 (which loads address %52), and we look
14590 // only through the chain, then we'll miss the trivial dependence on L1
14591 // (which also loads from %52). We then might change all loads and
14592 // stores to use Token1 as their chain operand, which could result in
14593 // copying %53 into %52 before copying %52 into %51 (which should
14596 // The problem is, however, that searching for such data dependencies
14597 // can become expensive, and the cost is not directly related to the
14598 // chain depth. Instead, we'll rule out such configurations here by
14599 // insisting that we've visited all chain users (except for users
14600 // of the original chain, which is not necessary). When doing this,
14601 // we need to look through nodes we don't care about (otherwise, things
14602 // like register copies will interfere with trivial cases).
14604 SmallVector<const SDNode *, 16> Worklist;
14605 for (const SDNode *N : Visited)
14606 if (N != OriginalChain.getNode())
14607 Worklist.push_back(N);
14609 while (!Worklist.empty()) {
14610 const SDNode *M = Worklist.pop_back_val();
14612 // We have already visited M, and want to make sure we've visited any uses
14613 // of M that we care about. For uses that we've not visisted, and don't
14614 // care about, queue them to the worklist.
14616 for (SDNode::use_iterator UI = M->use_begin(),
14617 UIE = M->use_end(); UI != UIE; ++UI)
14618 if (UI.getUse().getValueType() == MVT::Other &&
14619 Visited.insert(*UI).second) {
14620 if (isa<MemSDNode>(*UI)) {
14621 // We've not visited this use, and we care about it (it could have an
14622 // ordering dependency with the original node).
14624 Aliases.push_back(OriginalChain);
14628 // We've not visited this use, but we don't care about it. Mark it as
14629 // visited and enqueue it to the worklist.
14630 Worklist.push_back(*UI);
14635 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14636 /// (aliasing node.)
14637 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14638 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
14640 // Accumulate all the aliases to this node.
14641 GatherAllAliases(N, OldChain, Aliases);
14643 // If no operands then chain to entry token.
14644 if (Aliases.size() == 0)
14645 return DAG.getEntryNode();
14647 // If a single operand then chain to it. We don't need to revisit it.
14648 if (Aliases.size() == 1)
14651 // Construct a custom tailored token factor.
14652 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14655 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) {
14656 // This holds the base pointer, index, and the offset in bytes from the base
14658 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
14660 // We must have a base and an offset.
14661 if (!BasePtr.Base.getNode())
14664 // Do not handle stores to undef base pointers.
14665 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
14668 SmallVector<StoreSDNode *, 8> ChainedStores;
14669 ChainedStores.push_back(St);
14671 // Walk up the chain and look for nodes with offsets from the same
14672 // base pointer. Stop when reaching an instruction with a different kind
14673 // or instruction which has a different base pointer.
14674 StoreSDNode *Index = St;
14676 // If the chain has more than one use, then we can't reorder the mem ops.
14677 if (Index != St && !SDValue(Index, 0)->hasOneUse())
14680 if (Index->isVolatile() || Index->isIndexed())
14683 // Find the base pointer and offset for this memory node.
14684 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
14686 // Check that the base pointer is the same as the original one.
14687 if (!Ptr.equalBaseIndex(BasePtr))
14690 // Find the next memory operand in the chain. If the next operand in the
14691 // chain is a store then move up and continue the scan with the next
14692 // memory operand. If the next operand is a load save it and use alias
14693 // information to check if it interferes with anything.
14694 SDNode *NextInChain = Index->getChain().getNode();
14696 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
14697 // We found a store node. Use it for the next iteration.
14698 ChainedStores.push_back(STn);
14701 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
14702 NextInChain = Ldn->getChain().getNode();
14711 bool MadeChange = false;
14712 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
14714 for (StoreSDNode *ChainedStore : ChainedStores) {
14715 SDValue Chain = ChainedStore->getChain();
14716 SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
14718 if (Chain != BetterChain) {
14720 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
14724 // Do all replacements after finding the replacements to make to avoid making
14725 // the chains more complicated by introducing new TokenFactors.
14726 for (auto Replacement : BetterChains)
14727 replaceStoreChain(Replacement.first, Replacement.second);
14732 /// This is the entry point for the file.
14733 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14734 CodeGenOpt::Level OptLevel) {
14735 /// This is the main entry point to this class.
14736 DAGCombiner(*this, AA, OptLevel).Run(Level);