1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
11 // both before and after the DAG is legalized.
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
43 #define DEBUG_TYPE "dagcombine"
45 STATISTIC(NodesCombined , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
54 CombinerAA("combiner-alias-analysis", cl::Hidden,
55 cl::desc("Enable DAG combiner alias-analysis heuristics"));
58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59 cl::desc("Enable DAG combiner's use of IR alias analysis"));
62 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63 cl::desc("Enable DAG combiner's use of TBAA"));
66 static cl::opt<std::string>
67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68 cl::desc("Only use DAG-combiner alias analysis in this"
72 /// Hidden option to stress test load slicing, i.e., when this option
73 /// is enabled, load slicing bypasses most of its profitability guards.
75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76 cl::desc("Bypass the profitability model of load "
81 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82 cl::desc("DAG combiner may split indexing from loads"));
84 //------------------------------ DAGCombiner ---------------------------------//
88 const TargetLowering &TLI;
90 CodeGenOpt::Level OptLevel;
95 /// \brief Worklist of all of the nodes that need to be simplified.
97 /// This must behave as a stack -- new nodes to process are pushed onto the
98 /// back and when processing we pop off of the back.
100 /// The worklist will not contain duplicates but may contain null entries
101 /// due to nodes being deleted from the underlying DAG.
102 SmallVector<SDNode *, 64> Worklist;
104 /// \brief Mapping from an SDNode to its position on the worklist.
106 /// This is used to find and remove nodes from the worklist (by nulling
107 /// them) when they are deleted from the underlying DAG. It relies on
108 /// stable indices of nodes within the worklist.
109 DenseMap<SDNode *, unsigned> WorklistMap;
111 /// \brief Set of nodes which have been combined (at least once).
113 /// This is used to allow us to reliably add any operands of a DAG node
114 /// which have not yet been combined to the worklist.
115 SmallPtrSet<SDNode *, 64> CombinedNodes;
117 // AA - Used for DAG load/store alias analysis.
120 /// When an instruction is simplified, add all users of the instruction to
121 /// the work lists because they might get more simplified now.
122 void AddUsersToWorklist(SDNode *N) {
123 for (SDNode *Node : N->uses())
127 /// Call the node-specific routine that folds each particular type of node.
128 SDValue visit(SDNode *N);
131 /// Add to the worklist making sure its instance is at the back (next to be
133 void AddToWorklist(SDNode *N) {
134 // Skip handle nodes as they can't usefully be combined and confuse the
135 // zero-use deletion strategy.
136 if (N->getOpcode() == ISD::HANDLENODE)
139 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140 Worklist.push_back(N);
143 /// Remove all instances of N from the worklist.
144 void removeFromWorklist(SDNode *N) {
145 CombinedNodes.erase(N);
147 auto It = WorklistMap.find(N);
148 if (It == WorklistMap.end())
149 return; // Not in the worklist.
151 // Null out the entry rather than erasing it to avoid a linear operation.
152 Worklist[It->second] = nullptr;
153 WorklistMap.erase(It);
156 void deleteAndRecombine(SDNode *N);
157 bool recursivelyDeleteUnusedNodes(SDNode *N);
159 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
162 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163 return CombineTo(N, &Res, 1, AddTo);
166 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
168 SDValue To[] = { Res0, Res1 };
169 return CombineTo(N, To, 2, AddTo);
172 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
176 /// Check the specified integer node value to see if it can be simplified or
177 /// if things it uses can be simplified by bit propagation.
178 /// If so, return true.
179 bool SimplifyDemandedBits(SDValue Op) {
180 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181 APInt Demanded = APInt::getAllOnesValue(BitWidth);
182 return SimplifyDemandedBits(Op, Demanded);
185 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
187 bool CombineToPreIndexedLoadStore(SDNode *N);
188 bool CombineToPostIndexedLoadStore(SDNode *N);
189 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190 bool SliceUpLoad(SDNode *N);
192 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
195 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197 /// \param EltNo index of the vector element to load.
198 /// \param OriginalLoad load that EVE came from to be replaced.
199 /// \returns EVE on success SDValue() on failure.
200 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206 SDValue PromoteIntBinOp(SDValue Op);
207 SDValue PromoteIntShiftOp(SDValue Op);
208 SDValue PromoteExtend(SDValue Op);
209 bool PromoteLoad(SDValue Op);
211 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213 ISD::NodeType ExtType);
215 /// Call the node-specific routine that knows how to fold each
216 /// particular type of node. If that doesn't do anything, try the
217 /// target-specific DAG combines.
218 SDValue combine(SDNode *N);
220 // Visitation implementation - Implement dag node combining for different
221 // node types. The semantics are as follows:
223 // SDValue.getNode() == 0 - No change was made
224 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
225 // otherwise - N should be replaced by the returned Operand.
227 SDValue visitTokenFactor(SDNode *N);
228 SDValue visitMERGE_VALUES(SDNode *N);
229 SDValue visitADD(SDNode *N);
230 SDValue visitSUB(SDNode *N);
231 SDValue visitADDC(SDNode *N);
232 SDValue visitSUBC(SDNode *N);
233 SDValue visitADDE(SDNode *N);
234 SDValue visitSUBE(SDNode *N);
235 SDValue visitMUL(SDNode *N);
236 SDValue visitSDIV(SDNode *N);
237 SDValue visitUDIV(SDNode *N);
238 SDValue visitSREM(SDNode *N);
239 SDValue visitUREM(SDNode *N);
240 SDValue visitMULHU(SDNode *N);
241 SDValue visitMULHS(SDNode *N);
242 SDValue visitSMUL_LOHI(SDNode *N);
243 SDValue visitUMUL_LOHI(SDNode *N);
244 SDValue visitSMULO(SDNode *N);
245 SDValue visitUMULO(SDNode *N);
246 SDValue visitSDIVREM(SDNode *N);
247 SDValue visitUDIVREM(SDNode *N);
248 SDValue visitAND(SDNode *N);
249 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
250 SDValue visitOR(SDNode *N);
251 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
252 SDValue visitXOR(SDNode *N);
253 SDValue SimplifyVBinOp(SDNode *N);
254 SDValue visitSHL(SDNode *N);
255 SDValue visitSRA(SDNode *N);
256 SDValue visitSRL(SDNode *N);
257 SDValue visitRotate(SDNode *N);
258 SDValue visitBSWAP(SDNode *N);
259 SDValue visitCTLZ(SDNode *N);
260 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
261 SDValue visitCTTZ(SDNode *N);
262 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
263 SDValue visitCTPOP(SDNode *N);
264 SDValue visitSELECT(SDNode *N);
265 SDValue visitVSELECT(SDNode *N);
266 SDValue visitSELECT_CC(SDNode *N);
267 SDValue visitSETCC(SDNode *N);
268 SDValue visitSIGN_EXTEND(SDNode *N);
269 SDValue visitZERO_EXTEND(SDNode *N);
270 SDValue visitANY_EXTEND(SDNode *N);
271 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
272 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
273 SDValue visitTRUNCATE(SDNode *N);
274 SDValue visitBITCAST(SDNode *N);
275 SDValue visitBUILD_PAIR(SDNode *N);
276 SDValue visitFADD(SDNode *N);
277 SDValue visitFSUB(SDNode *N);
278 SDValue visitFMUL(SDNode *N);
279 SDValue visitFMA(SDNode *N);
280 SDValue visitFDIV(SDNode *N);
281 SDValue visitFREM(SDNode *N);
282 SDValue visitFSQRT(SDNode *N);
283 SDValue visitFCOPYSIGN(SDNode *N);
284 SDValue visitSINT_TO_FP(SDNode *N);
285 SDValue visitUINT_TO_FP(SDNode *N);
286 SDValue visitFP_TO_SINT(SDNode *N);
287 SDValue visitFP_TO_UINT(SDNode *N);
288 SDValue visitFP_ROUND(SDNode *N);
289 SDValue visitFP_ROUND_INREG(SDNode *N);
290 SDValue visitFP_EXTEND(SDNode *N);
291 SDValue visitFNEG(SDNode *N);
292 SDValue visitFABS(SDNode *N);
293 SDValue visitFCEIL(SDNode *N);
294 SDValue visitFTRUNC(SDNode *N);
295 SDValue visitFFLOOR(SDNode *N);
296 SDValue visitFMINNUM(SDNode *N);
297 SDValue visitFMAXNUM(SDNode *N);
298 SDValue visitBRCOND(SDNode *N);
299 SDValue visitBR_CC(SDNode *N);
300 SDValue visitLOAD(SDNode *N);
301 SDValue visitSTORE(SDNode *N);
302 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
303 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
304 SDValue visitBUILD_VECTOR(SDNode *N);
305 SDValue visitCONCAT_VECTORS(SDNode *N);
306 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
307 SDValue visitVECTOR_SHUFFLE(SDNode *N);
308 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
309 SDValue visitINSERT_SUBVECTOR(SDNode *N);
310 SDValue visitMLOAD(SDNode *N);
311 SDValue visitMSTORE(SDNode *N);
312 SDValue visitMGATHER(SDNode *N);
313 SDValue visitMSCATTER(SDNode *N);
314 SDValue visitFP_TO_FP16(SDNode *N);
316 SDValue visitFADDForFMACombine(SDNode *N);
317 SDValue visitFSUBForFMACombine(SDNode *N);
319 SDValue XformToShuffleWithZero(SDNode *N);
320 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
322 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
324 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
325 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
326 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
327 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
328 SDValue N3, ISD::CondCode CC,
329 bool NotExtCompare = false);
330 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
331 SDLoc DL, bool foldBooleans = true);
333 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
335 bool isOneUseSetCC(SDValue N) const;
337 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
339 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
340 SDValue CombineExtLoad(SDNode *N);
341 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
342 SDValue BuildSDIV(SDNode *N);
343 SDValue BuildSDIVPow2(SDNode *N);
344 SDValue BuildUDIV(SDNode *N);
345 SDValue BuildReciprocalEstimate(SDValue Op);
346 SDValue BuildRsqrtEstimate(SDValue Op);
347 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
348 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
349 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
350 bool DemandHighBits = true);
351 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
352 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
353 SDValue InnerPos, SDValue InnerNeg,
354 unsigned PosOpcode, unsigned NegOpcode,
356 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
357 SDValue ReduceLoadWidth(SDNode *N);
358 SDValue ReduceLoadOpStoreWidth(SDNode *N);
359 SDValue TransformFPLoadStorePair(SDNode *N);
360 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
361 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
363 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
365 /// Walk up chain skipping non-aliasing memory nodes,
366 /// looking for aliasing nodes and adding them to the Aliases vector.
367 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
368 SmallVectorImpl<SDValue> &Aliases);
370 /// Return true if there is any possibility that the two addresses overlap.
371 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
373 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
374 /// chain (aliasing node.)
375 SDValue FindBetterChain(SDNode *N, SDValue Chain);
377 /// Holds a pointer to an LSBaseSDNode as well as information on where it
378 /// is located in a sequence of memory operations connected by a chain.
380 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
381 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
382 // Ptr to the mem node.
383 LSBaseSDNode *MemNode;
384 // Offset from the base ptr.
385 int64_t OffsetFromBase;
386 // What is the sequence number of this mem node.
387 // Lowest mem operand in the DAG starts at zero.
388 unsigned SequenceNum;
391 /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
392 /// constant build_vector of the stored constant values in Stores.
393 SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
395 ArrayRef<MemOpLink> Stores,
398 /// This is a helper function for MergeConsecutiveStores. When the source
399 /// elements of the consecutive stores are all constants or all extracted
400 /// vector elements, try to merge them into one larger store.
401 /// \return True if a merged store was created.
402 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
403 EVT MemVT, unsigned NumElem,
404 bool IsConstantSrc, bool UseVector);
406 /// This is a helper function for MergeConsecutiveStores.
407 /// Stores that may be merged are placed in StoreNodes.
408 /// Loads that may alias with those stores are placed in AliasLoadNodes.
409 void getStoreMergeAndAliasCandidates(
410 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
411 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
413 /// Merge consecutive store operations into a wide store.
414 /// This optimization uses wide integers or vectors when possible.
415 /// \return True if some memory operations were changed.
416 bool MergeConsecutiveStores(StoreSDNode *N);
418 /// \brief Try to transform a truncation where C is a constant:
419 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
421 /// \p N needs to be a truncation and its first operand an AND. Other
422 /// requirements are checked by the function (e.g. that trunc is
423 /// single-use) and if missed an empty SDValue is returned.
424 SDValue distributeTruncateThroughAnd(SDNode *N);
427 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
428 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
429 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
430 auto *F = DAG.getMachineFunction().getFunction();
431 ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
432 F->hasFnAttribute(Attribute::MinSize);
435 /// Runs the dag combiner on all nodes in the work list
436 void Run(CombineLevel AtLevel);
438 SelectionDAG &getDAG() const { return DAG; }
440 /// Returns a type large enough to hold any valid shift amount - before type
441 /// legalization these can be huge.
442 EVT getShiftAmountTy(EVT LHSTy) {
443 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
444 if (LHSTy.isVector())
446 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
447 : TLI.getPointerTy();
450 /// This method returns true if we are running before type legalization or
451 /// if the specified VT is legal.
452 bool isTypeLegal(const EVT &VT) {
453 if (!LegalTypes) return true;
454 return TLI.isTypeLegal(VT);
457 /// Convenience wrapper around TargetLowering::getSetCCResultType
458 EVT getSetCCResultType(EVT VT) const {
459 return TLI.getSetCCResultType(*DAG.getContext(), VT);
466 /// This class is a DAGUpdateListener that removes any deleted
467 /// nodes from the worklist.
468 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
471 explicit WorklistRemover(DAGCombiner &dc)
472 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
474 void NodeDeleted(SDNode *N, SDNode *E) override {
475 DC.removeFromWorklist(N);
480 //===----------------------------------------------------------------------===//
481 // TargetLowering::DAGCombinerInfo implementation
482 //===----------------------------------------------------------------------===//
484 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
485 ((DAGCombiner*)DC)->AddToWorklist(N);
488 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
489 ((DAGCombiner*)DC)->removeFromWorklist(N);
492 SDValue TargetLowering::DAGCombinerInfo::
493 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
494 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
497 SDValue TargetLowering::DAGCombinerInfo::
498 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
499 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
503 SDValue TargetLowering::DAGCombinerInfo::
504 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
505 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
508 void TargetLowering::DAGCombinerInfo::
509 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
510 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
513 //===----------------------------------------------------------------------===//
515 //===----------------------------------------------------------------------===//
517 void DAGCombiner::deleteAndRecombine(SDNode *N) {
518 removeFromWorklist(N);
520 // If the operands of this node are only used by the node, they will now be
521 // dead. Make sure to re-visit them and recursively delete dead nodes.
522 for (const SDValue &Op : N->ops())
523 // For an operand generating multiple values, one of the values may
524 // become dead allowing further simplification (e.g. split index
525 // arithmetic from an indexed load).
526 if (Op->hasOneUse() || Op->getNumValues() > 1)
527 AddToWorklist(Op.getNode());
532 /// Return 1 if we can compute the negated form of the specified expression for
533 /// the same cost as the expression itself, or 2 if we can compute the negated
534 /// form more cheaply than the expression itself.
535 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
536 const TargetLowering &TLI,
537 const TargetOptions *Options,
538 unsigned Depth = 0) {
539 // fneg is removable even if it has multiple uses.
540 if (Op.getOpcode() == ISD::FNEG) return 2;
542 // Don't allow anything with multiple uses.
543 if (!Op.hasOneUse()) return 0;
545 // Don't recurse exponentially.
546 if (Depth > 6) return 0;
548 switch (Op.getOpcode()) {
549 default: return false;
550 case ISD::ConstantFP:
551 // Don't invert constant FP values after legalize. The negated constant
552 // isn't necessarily legal.
553 return LegalOperations ? 0 : 1;
555 // FIXME: determine better conditions for this xform.
556 if (!Options->UnsafeFPMath) return 0;
558 // After operation legalization, it might not be legal to create new FSUBs.
559 if (LegalOperations &&
560 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
563 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
564 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
567 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
568 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
571 // We can't turn -(A-B) into B-A when we honor signed zeros.
572 if (!Options->UnsafeFPMath) return 0;
574 // fold (fneg (fsub A, B)) -> (fsub B, A)
579 if (Options->HonorSignDependentRoundingFPMath()) return 0;
581 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
582 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
586 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
592 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
597 /// If isNegatibleForFree returns true, return the newly negated expression.
598 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
599 bool LegalOperations, unsigned Depth = 0) {
600 const TargetOptions &Options = DAG.getTarget().Options;
601 // fneg is removable even if it has multiple uses.
602 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
604 // Don't allow anything with multiple uses.
605 assert(Op.hasOneUse() && "Unknown reuse!");
607 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
608 switch (Op.getOpcode()) {
609 default: llvm_unreachable("Unknown code");
610 case ISD::ConstantFP: {
611 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
613 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
616 // FIXME: determine better conditions for this xform.
617 assert(Options.UnsafeFPMath);
619 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
620 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
621 DAG.getTargetLoweringInfo(), &Options, Depth+1))
622 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
623 GetNegatedExpression(Op.getOperand(0), DAG,
624 LegalOperations, Depth+1),
626 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
627 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
628 GetNegatedExpression(Op.getOperand(1), DAG,
629 LegalOperations, Depth+1),
632 // We can't turn -(A-B) into B-A when we honor signed zeros.
633 assert(Options.UnsafeFPMath);
635 // fold (fneg (fsub 0, B)) -> B
636 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
638 return Op.getOperand(1);
640 // fold (fneg (fsub A, B)) -> (fsub B, A)
641 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
642 Op.getOperand(1), Op.getOperand(0));
646 assert(!Options.HonorSignDependentRoundingFPMath());
648 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
649 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
650 DAG.getTargetLoweringInfo(), &Options, Depth+1))
651 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
652 GetNegatedExpression(Op.getOperand(0), DAG,
653 LegalOperations, Depth+1),
656 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
657 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
659 GetNegatedExpression(Op.getOperand(1), DAG,
660 LegalOperations, Depth+1));
664 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
665 GetNegatedExpression(Op.getOperand(0), DAG,
666 LegalOperations, Depth+1));
668 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
669 GetNegatedExpression(Op.getOperand(0), DAG,
670 LegalOperations, Depth+1),
675 // Return true if this node is a setcc, or is a select_cc
676 // that selects between the target values used for true and false, making it
677 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
678 // the appropriate nodes based on the type of node we are checking. This
679 // simplifies life a bit for the callers.
680 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
682 if (N.getOpcode() == ISD::SETCC) {
683 LHS = N.getOperand(0);
684 RHS = N.getOperand(1);
685 CC = N.getOperand(2);
689 if (N.getOpcode() != ISD::SELECT_CC ||
690 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
691 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
694 if (TLI.getBooleanContents(N.getValueType()) ==
695 TargetLowering::UndefinedBooleanContent)
698 LHS = N.getOperand(0);
699 RHS = N.getOperand(1);
700 CC = N.getOperand(4);
704 /// Return true if this is a SetCC-equivalent operation with only one use.
705 /// If this is true, it allows the users to invert the operation for free when
706 /// it is profitable to do so.
707 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
709 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
714 /// Returns true if N is a BUILD_VECTOR node whose
715 /// elements are all the same constant or undefined.
716 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
717 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
722 unsigned SplatBitSize;
724 EVT EltVT = N->getValueType(0).getVectorElementType();
725 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
727 EltVT.getSizeInBits() >= SplatBitSize);
730 // \brief Returns the SDNode if it is a constant integer BuildVector
731 // or constant integer.
732 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
733 if (isa<ConstantSDNode>(N))
735 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
740 // \brief Returns the SDNode if it is a constant float BuildVector
741 // or constant float.
742 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
743 if (isa<ConstantFPSDNode>(N))
745 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
750 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
752 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
753 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
756 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
757 BitVector UndefElements;
758 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
760 // BuildVectors can truncate their operands. Ignore that case here.
761 // FIXME: We blindly ignore splats which include undef which is overly
763 if (CN && UndefElements.none() &&
764 CN->getValueType(0) == N.getValueType().getScalarType())
771 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
773 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
774 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
777 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
778 BitVector UndefElements;
779 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
781 if (CN && UndefElements.none())
788 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
789 SDValue N0, SDValue N1) {
790 EVT VT = N0.getValueType();
791 if (N0.getOpcode() == Opc) {
792 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
793 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
794 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
795 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
796 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
799 if (N0.hasOneUse()) {
800 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
802 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
803 if (!OpNode.getNode())
805 AddToWorklist(OpNode.getNode());
806 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
811 if (N1.getOpcode() == Opc) {
812 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
813 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
814 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
815 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
816 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
819 if (N1.hasOneUse()) {
820 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
822 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
823 if (!OpNode.getNode())
825 AddToWorklist(OpNode.getNode());
826 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
834 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
836 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
838 DEBUG(dbgs() << "\nReplacing.1 ";
840 dbgs() << "\nWith: ";
841 To[0].getNode()->dump(&DAG);
842 dbgs() << " and " << NumTo-1 << " other values\n");
843 for (unsigned i = 0, e = NumTo; i != e; ++i)
844 assert((!To[i].getNode() ||
845 N->getValueType(i) == To[i].getValueType()) &&
846 "Cannot combine value to value of different type!");
848 WorklistRemover DeadNodes(*this);
849 DAG.ReplaceAllUsesWith(N, To);
851 // Push the new nodes and any users onto the worklist
852 for (unsigned i = 0, e = NumTo; i != e; ++i) {
853 if (To[i].getNode()) {
854 AddToWorklist(To[i].getNode());
855 AddUsersToWorklist(To[i].getNode());
860 // Finally, if the node is now dead, remove it from the graph. The node
861 // may not be dead if the replacement process recursively simplified to
862 // something else needing this node.
864 deleteAndRecombine(N);
865 return SDValue(N, 0);
869 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
870 // Replace all uses. If any nodes become isomorphic to other nodes and
871 // are deleted, make sure to remove them from our worklist.
872 WorklistRemover DeadNodes(*this);
873 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
875 // Push the new node and any (possibly new) users onto the worklist.
876 AddToWorklist(TLO.New.getNode());
877 AddUsersToWorklist(TLO.New.getNode());
879 // Finally, if the node is now dead, remove it from the graph. The node
880 // may not be dead if the replacement process recursively simplified to
881 // something else needing this node.
882 if (TLO.Old.getNode()->use_empty())
883 deleteAndRecombine(TLO.Old.getNode());
886 /// Check the specified integer node value to see if it can be simplified or if
887 /// things it uses can be simplified by bit propagation. If so, return true.
888 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
889 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
890 APInt KnownZero, KnownOne;
891 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
895 AddToWorklist(Op.getNode());
897 // Replace the old value with the new one.
899 DEBUG(dbgs() << "\nReplacing.2 ";
900 TLO.Old.getNode()->dump(&DAG);
901 dbgs() << "\nWith: ";
902 TLO.New.getNode()->dump(&DAG);
905 CommitTargetLoweringOpt(TLO);
909 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
911 EVT VT = Load->getValueType(0);
912 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
914 DEBUG(dbgs() << "\nReplacing.9 ";
916 dbgs() << "\nWith: ";
917 Trunc.getNode()->dump(&DAG);
919 WorklistRemover DeadNodes(*this);
920 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
921 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
922 deleteAndRecombine(Load);
923 AddToWorklist(Trunc.getNode());
926 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
929 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
930 EVT MemVT = LD->getMemoryVT();
931 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
932 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
934 : LD->getExtensionType();
936 return DAG.getExtLoad(ExtType, dl, PVT,
937 LD->getChain(), LD->getBasePtr(),
938 MemVT, LD->getMemOperand());
941 unsigned Opc = Op.getOpcode();
944 case ISD::AssertSext:
945 return DAG.getNode(ISD::AssertSext, dl, PVT,
946 SExtPromoteOperand(Op.getOperand(0), PVT),
948 case ISD::AssertZext:
949 return DAG.getNode(ISD::AssertZext, dl, PVT,
950 ZExtPromoteOperand(Op.getOperand(0), PVT),
952 case ISD::Constant: {
954 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
955 return DAG.getNode(ExtOpc, dl, PVT, Op);
959 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
961 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
964 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
965 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
967 EVT OldVT = Op.getValueType();
969 bool Replace = false;
970 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
971 if (!NewOp.getNode())
973 AddToWorklist(NewOp.getNode());
976 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
977 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
978 DAG.getValueType(OldVT));
981 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
982 EVT OldVT = Op.getValueType();
984 bool Replace = false;
985 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
986 if (!NewOp.getNode())
988 AddToWorklist(NewOp.getNode());
991 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
992 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
995 /// Promote the specified integer binary operation if the target indicates it is
996 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
997 /// i32 since i16 instructions are longer.
998 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
999 if (!LegalOperations)
1002 EVT VT = Op.getValueType();
1003 if (VT.isVector() || !VT.isInteger())
1006 // If operation type is 'undesirable', e.g. i16 on x86, consider
1008 unsigned Opc = Op.getOpcode();
1009 if (TLI.isTypeDesirableForOp(Opc, VT))
1013 // Consult target whether it is a good idea to promote this operation and
1014 // what's the right type to promote it to.
1015 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1016 assert(PVT != VT && "Don't know what type to promote to!");
1018 bool Replace0 = false;
1019 SDValue N0 = Op.getOperand(0);
1020 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1024 bool Replace1 = false;
1025 SDValue N1 = Op.getOperand(1);
1030 NN1 = PromoteOperand(N1, PVT, Replace1);
1035 AddToWorklist(NN0.getNode());
1037 AddToWorklist(NN1.getNode());
1040 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1042 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1044 DEBUG(dbgs() << "\nPromoting ";
1045 Op.getNode()->dump(&DAG));
1047 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1048 DAG.getNode(Opc, dl, PVT, NN0, NN1));
1053 /// Promote the specified integer shift operation if the target indicates it is
1054 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1055 /// i32 since i16 instructions are longer.
1056 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1057 if (!LegalOperations)
1060 EVT VT = Op.getValueType();
1061 if (VT.isVector() || !VT.isInteger())
1064 // If operation type is 'undesirable', e.g. i16 on x86, consider
1066 unsigned Opc = Op.getOpcode();
1067 if (TLI.isTypeDesirableForOp(Opc, VT))
1071 // Consult target whether it is a good idea to promote this operation and
1072 // what's the right type to promote it to.
1073 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1074 assert(PVT != VT && "Don't know what type to promote to!");
1076 bool Replace = false;
1077 SDValue N0 = Op.getOperand(0);
1078 if (Opc == ISD::SRA)
1079 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1080 else if (Opc == ISD::SRL)
1081 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1083 N0 = PromoteOperand(N0, PVT, Replace);
1087 AddToWorklist(N0.getNode());
1089 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1091 DEBUG(dbgs() << "\nPromoting ";
1092 Op.getNode()->dump(&DAG));
1094 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1095 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1100 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1101 if (!LegalOperations)
1104 EVT VT = Op.getValueType();
1105 if (VT.isVector() || !VT.isInteger())
1108 // If operation type is 'undesirable', e.g. i16 on x86, consider
1110 unsigned Opc = Op.getOpcode();
1111 if (TLI.isTypeDesirableForOp(Opc, VT))
1115 // Consult target whether it is a good idea to promote this operation and
1116 // what's the right type to promote it to.
1117 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1118 assert(PVT != VT && "Don't know what type to promote to!");
1119 // fold (aext (aext x)) -> (aext x)
1120 // fold (aext (zext x)) -> (zext x)
1121 // fold (aext (sext x)) -> (sext x)
1122 DEBUG(dbgs() << "\nPromoting ";
1123 Op.getNode()->dump(&DAG));
1124 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1129 bool DAGCombiner::PromoteLoad(SDValue Op) {
1130 if (!LegalOperations)
1133 EVT VT = Op.getValueType();
1134 if (VT.isVector() || !VT.isInteger())
1137 // If operation type is 'undesirable', e.g. i16 on x86, consider
1139 unsigned Opc = Op.getOpcode();
1140 if (TLI.isTypeDesirableForOp(Opc, VT))
1144 // Consult target whether it is a good idea to promote this operation and
1145 // what's the right type to promote it to.
1146 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1147 assert(PVT != VT && "Don't know what type to promote to!");
1150 SDNode *N = Op.getNode();
1151 LoadSDNode *LD = cast<LoadSDNode>(N);
1152 EVT MemVT = LD->getMemoryVT();
1153 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1154 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1156 : LD->getExtensionType();
1157 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1158 LD->getChain(), LD->getBasePtr(),
1159 MemVT, LD->getMemOperand());
1160 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1162 DEBUG(dbgs() << "\nPromoting ";
1165 Result.getNode()->dump(&DAG);
1167 WorklistRemover DeadNodes(*this);
1168 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1169 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1170 deleteAndRecombine(N);
1171 AddToWorklist(Result.getNode());
1177 /// \brief Recursively delete a node which has no uses and any operands for
1178 /// which it is the only use.
1180 /// Note that this both deletes the nodes and removes them from the worklist.
1181 /// It also adds any nodes who have had a user deleted to the worklist as they
1182 /// may now have only one use and subject to other combines.
1183 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1184 if (!N->use_empty())
1187 SmallSetVector<SDNode *, 16> Nodes;
1190 N = Nodes.pop_back_val();
1194 if (N->use_empty()) {
1195 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1196 Nodes.insert(N->getOperand(i).getNode());
1198 removeFromWorklist(N);
1203 } while (!Nodes.empty());
1207 //===----------------------------------------------------------------------===//
1208 // Main DAG Combiner implementation
1209 //===----------------------------------------------------------------------===//
1211 void DAGCombiner::Run(CombineLevel AtLevel) {
1212 // set the instance variables, so that the various visit routines may use it.
1214 LegalOperations = Level >= AfterLegalizeVectorOps;
1215 LegalTypes = Level >= AfterLegalizeTypes;
1217 // Add all the dag nodes to the worklist.
1218 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1219 E = DAG.allnodes_end(); I != E; ++I)
1222 // Create a dummy node (which is not added to allnodes), that adds a reference
1223 // to the root node, preventing it from being deleted, and tracking any
1224 // changes of the root.
1225 HandleSDNode Dummy(DAG.getRoot());
1227 // while the worklist isn't empty, find a node and
1228 // try and combine it.
1229 while (!WorklistMap.empty()) {
1231 // The Worklist holds the SDNodes in order, but it may contain null entries.
1233 N = Worklist.pop_back_val();
1236 bool GoodWorklistEntry = WorklistMap.erase(N);
1237 (void)GoodWorklistEntry;
1238 assert(GoodWorklistEntry &&
1239 "Found a worklist entry without a corresponding map entry!");
1241 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1242 // N is deleted from the DAG, since they too may now be dead or may have a
1243 // reduced number of uses, allowing other xforms.
1244 if (recursivelyDeleteUnusedNodes(N))
1247 WorklistRemover DeadNodes(*this);
1249 // If this combine is running after legalizing the DAG, re-legalize any
1250 // nodes pulled off the worklist.
1251 if (Level == AfterLegalizeDAG) {
1252 SmallSetVector<SDNode *, 16> UpdatedNodes;
1253 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1255 for (SDNode *LN : UpdatedNodes) {
1257 AddUsersToWorklist(LN);
1263 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1265 // Add any operands of the new node which have not yet been combined to the
1266 // worklist as well. Because the worklist uniques things already, this
1267 // won't repeatedly process the same operand.
1268 CombinedNodes.insert(N);
1269 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1270 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1271 AddToWorklist(N->getOperand(i).getNode());
1273 SDValue RV = combine(N);
1280 // If we get back the same node we passed in, rather than a new node or
1281 // zero, we know that the node must have defined multiple values and
1282 // CombineTo was used. Since CombineTo takes care of the worklist
1283 // mechanics for us, we have no work to do in this case.
1284 if (RV.getNode() == N)
1287 assert(N->getOpcode() != ISD::DELETED_NODE &&
1288 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1289 "Node was deleted but visit returned new node!");
1291 DEBUG(dbgs() << " ... into: ";
1292 RV.getNode()->dump(&DAG));
1294 // Transfer debug value.
1295 DAG.TransferDbgValues(SDValue(N, 0), RV);
1296 if (N->getNumValues() == RV.getNode()->getNumValues())
1297 DAG.ReplaceAllUsesWith(N, RV.getNode());
1299 assert(N->getValueType(0) == RV.getValueType() &&
1300 N->getNumValues() == 1 && "Type mismatch");
1302 DAG.ReplaceAllUsesWith(N, &OpV);
1305 // Push the new node and any users onto the worklist
1306 AddToWorklist(RV.getNode());
1307 AddUsersToWorklist(RV.getNode());
1309 // Finally, if the node is now dead, remove it from the graph. The node
1310 // may not be dead if the replacement process recursively simplified to
1311 // something else needing this node. This will also take care of adding any
1312 // operands which have lost a user to the worklist.
1313 recursivelyDeleteUnusedNodes(N);
1316 // If the root changed (e.g. it was a dead load, update the root).
1317 DAG.setRoot(Dummy.getValue());
1318 DAG.RemoveDeadNodes();
1321 SDValue DAGCombiner::visit(SDNode *N) {
1322 switch (N->getOpcode()) {
1324 case ISD::TokenFactor: return visitTokenFactor(N);
1325 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1326 case ISD::ADD: return visitADD(N);
1327 case ISD::SUB: return visitSUB(N);
1328 case ISD::ADDC: return visitADDC(N);
1329 case ISD::SUBC: return visitSUBC(N);
1330 case ISD::ADDE: return visitADDE(N);
1331 case ISD::SUBE: return visitSUBE(N);
1332 case ISD::MUL: return visitMUL(N);
1333 case ISD::SDIV: return visitSDIV(N);
1334 case ISD::UDIV: return visitUDIV(N);
1335 case ISD::SREM: return visitSREM(N);
1336 case ISD::UREM: return visitUREM(N);
1337 case ISD::MULHU: return visitMULHU(N);
1338 case ISD::MULHS: return visitMULHS(N);
1339 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1340 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1341 case ISD::SMULO: return visitSMULO(N);
1342 case ISD::UMULO: return visitUMULO(N);
1343 case ISD::SDIVREM: return visitSDIVREM(N);
1344 case ISD::UDIVREM: return visitUDIVREM(N);
1345 case ISD::AND: return visitAND(N);
1346 case ISD::OR: return visitOR(N);
1347 case ISD::XOR: return visitXOR(N);
1348 case ISD::SHL: return visitSHL(N);
1349 case ISD::SRA: return visitSRA(N);
1350 case ISD::SRL: return visitSRL(N);
1352 case ISD::ROTL: return visitRotate(N);
1353 case ISD::BSWAP: return visitBSWAP(N);
1354 case ISD::CTLZ: return visitCTLZ(N);
1355 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1356 case ISD::CTTZ: return visitCTTZ(N);
1357 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1358 case ISD::CTPOP: return visitCTPOP(N);
1359 case ISD::SELECT: return visitSELECT(N);
1360 case ISD::VSELECT: return visitVSELECT(N);
1361 case ISD::SELECT_CC: return visitSELECT_CC(N);
1362 case ISD::SETCC: return visitSETCC(N);
1363 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1364 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1365 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1366 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1367 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1368 case ISD::TRUNCATE: return visitTRUNCATE(N);
1369 case ISD::BITCAST: return visitBITCAST(N);
1370 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1371 case ISD::FADD: return visitFADD(N);
1372 case ISD::FSUB: return visitFSUB(N);
1373 case ISD::FMUL: return visitFMUL(N);
1374 case ISD::FMA: return visitFMA(N);
1375 case ISD::FDIV: return visitFDIV(N);
1376 case ISD::FREM: return visitFREM(N);
1377 case ISD::FSQRT: return visitFSQRT(N);
1378 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1379 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1380 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1381 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1382 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1383 case ISD::FP_ROUND: return visitFP_ROUND(N);
1384 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1385 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1386 case ISD::FNEG: return visitFNEG(N);
1387 case ISD::FABS: return visitFABS(N);
1388 case ISD::FFLOOR: return visitFFLOOR(N);
1389 case ISD::FMINNUM: return visitFMINNUM(N);
1390 case ISD::FMAXNUM: return visitFMAXNUM(N);
1391 case ISD::FCEIL: return visitFCEIL(N);
1392 case ISD::FTRUNC: return visitFTRUNC(N);
1393 case ISD::BRCOND: return visitBRCOND(N);
1394 case ISD::BR_CC: return visitBR_CC(N);
1395 case ISD::LOAD: return visitLOAD(N);
1396 case ISD::STORE: return visitSTORE(N);
1397 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1398 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1399 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1400 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1401 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1402 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1403 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1404 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1405 case ISD::MGATHER: return visitMGATHER(N);
1406 case ISD::MLOAD: return visitMLOAD(N);
1407 case ISD::MSCATTER: return visitMSCATTER(N);
1408 case ISD::MSTORE: return visitMSTORE(N);
1409 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
1414 SDValue DAGCombiner::combine(SDNode *N) {
1415 SDValue RV = visit(N);
1417 // If nothing happened, try a target-specific DAG combine.
1418 if (!RV.getNode()) {
1419 assert(N->getOpcode() != ISD::DELETED_NODE &&
1420 "Node was deleted but visit returned NULL!");
1422 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1423 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1425 // Expose the DAG combiner to the target combiner impls.
1426 TargetLowering::DAGCombinerInfo
1427 DagCombineInfo(DAG, Level, false, this);
1429 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1433 // If nothing happened still, try promoting the operation.
1434 if (!RV.getNode()) {
1435 switch (N->getOpcode()) {
1443 RV = PromoteIntBinOp(SDValue(N, 0));
1448 RV = PromoteIntShiftOp(SDValue(N, 0));
1450 case ISD::SIGN_EXTEND:
1451 case ISD::ZERO_EXTEND:
1452 case ISD::ANY_EXTEND:
1453 RV = PromoteExtend(SDValue(N, 0));
1456 if (PromoteLoad(SDValue(N, 0)))
1462 // If N is a commutative binary node, try commuting it to enable more
1464 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1465 N->getNumValues() == 1) {
1466 SDValue N0 = N->getOperand(0);
1467 SDValue N1 = N->getOperand(1);
1469 // Constant operands are canonicalized to RHS.
1470 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1471 SDValue Ops[] = {N1, N0};
1473 if (const auto *BinNode = dyn_cast<BinaryWithFlagsSDNode>(N)) {
1474 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1477 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1480 return SDValue(CSENode, 0);
1487 /// Given a node, return its input chain if it has one, otherwise return a null
1489 static SDValue getInputChainForNode(SDNode *N) {
1490 if (unsigned NumOps = N->getNumOperands()) {
1491 if (N->getOperand(0).getValueType() == MVT::Other)
1492 return N->getOperand(0);
1493 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1494 return N->getOperand(NumOps-1);
1495 for (unsigned i = 1; i < NumOps-1; ++i)
1496 if (N->getOperand(i).getValueType() == MVT::Other)
1497 return N->getOperand(i);
1502 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1503 // If N has two operands, where one has an input chain equal to the other,
1504 // the 'other' chain is redundant.
1505 if (N->getNumOperands() == 2) {
1506 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1507 return N->getOperand(0);
1508 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1509 return N->getOperand(1);
1512 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1513 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1514 SmallPtrSet<SDNode*, 16> SeenOps;
1515 bool Changed = false; // If we should replace this token factor.
1517 // Start out with this token factor.
1520 // Iterate through token factors. The TFs grows when new token factors are
1522 for (unsigned i = 0; i < TFs.size(); ++i) {
1523 SDNode *TF = TFs[i];
1525 // Check each of the operands.
1526 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1527 SDValue Op = TF->getOperand(i);
1529 switch (Op.getOpcode()) {
1530 case ISD::EntryToken:
1531 // Entry tokens don't need to be added to the list. They are
1536 case ISD::TokenFactor:
1537 if (Op.hasOneUse() &&
1538 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1539 // Queue up for processing.
1540 TFs.push_back(Op.getNode());
1541 // Clean up in case the token factor is removed.
1542 AddToWorklist(Op.getNode());
1549 // Only add if it isn't already in the list.
1550 if (SeenOps.insert(Op.getNode()).second)
1561 // If we've changed things around then replace token factor.
1564 // The entry token is the only possible outcome.
1565 Result = DAG.getEntryNode();
1567 // New and improved token factor.
1568 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1571 // Add users to worklist if AA is enabled, since it may introduce
1572 // a lot of new chained token factors while removing memory deps.
1573 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1574 : DAG.getSubtarget().useAA();
1575 return CombineTo(N, Result, UseAA /*add to worklist*/);
1581 /// MERGE_VALUES can always be eliminated.
1582 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1583 WorklistRemover DeadNodes(*this);
1584 // Replacing results may cause a different MERGE_VALUES to suddenly
1585 // be CSE'd with N, and carry its uses with it. Iterate until no
1586 // uses remain, to ensure that the node can be safely deleted.
1587 // First add the users of this node to the work list so that they
1588 // can be tried again once they have new operands.
1589 AddUsersToWorklist(N);
1591 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1592 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1593 } while (!N->use_empty());
1594 deleteAndRecombine(N);
1595 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1598 static bool isNullConstant(SDValue V) {
1599 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1600 return Const != nullptr && Const->isNullValue();
1603 static bool isNullFPConstant(SDValue V) {
1604 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1605 return Const != nullptr && Const->isZero() && !Const->isNegative();
1608 static bool isAllOnesConstant(SDValue V) {
1609 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1610 return Const != nullptr && Const->isAllOnesValue();
1613 static bool isOneConstant(SDValue V) {
1614 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1615 return Const != nullptr && Const->isOne();
1618 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1619 /// ContantSDNode pointer else nullptr.
1620 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1621 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1622 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1625 SDValue DAGCombiner::visitADD(SDNode *N) {
1626 SDValue N0 = N->getOperand(0);
1627 SDValue N1 = N->getOperand(1);
1628 EVT VT = N0.getValueType();
1631 if (VT.isVector()) {
1632 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1635 // fold (add x, 0) -> x, vector edition
1636 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1638 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1642 // fold (add x, undef) -> undef
1643 if (N0.getOpcode() == ISD::UNDEF)
1645 if (N1.getOpcode() == ISD::UNDEF)
1647 // fold (add c1, c2) -> c1+c2
1648 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1649 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1651 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1652 // canonicalize constant to RHS
1653 if (isConstantIntBuildVectorOrConstantInt(N0) &&
1654 !isConstantIntBuildVectorOrConstantInt(N1))
1655 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1656 // fold (add x, 0) -> x
1657 if (isNullConstant(N1))
1659 // fold (add Sym, c) -> Sym+c
1660 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1661 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1662 GA->getOpcode() == ISD::GlobalAddress)
1663 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1665 (uint64_t)N1C->getSExtValue());
1666 // fold ((c1-A)+c2) -> (c1+c2)-A
1667 if (N1C && N0.getOpcode() == ISD::SUB)
1668 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1670 return DAG.getNode(ISD::SUB, DL, VT,
1671 DAG.getConstant(N1C->getAPIntValue()+
1672 N0C->getAPIntValue(), DL, VT),
1676 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1678 // fold ((0-A) + B) -> B-A
1679 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1680 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1681 // fold (A + (0-B)) -> A-B
1682 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1683 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1684 // fold (A+(B-A)) -> B
1685 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1686 return N1.getOperand(0);
1687 // fold ((B-A)+A) -> B
1688 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1689 return N0.getOperand(0);
1690 // fold (A+(B-(A+C))) to (B-C)
1691 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1692 N0 == N1.getOperand(1).getOperand(0))
1693 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1694 N1.getOperand(1).getOperand(1));
1695 // fold (A+(B-(C+A))) to (B-C)
1696 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1697 N0 == N1.getOperand(1).getOperand(1))
1698 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1699 N1.getOperand(1).getOperand(0));
1700 // fold (A+((B-A)+or-C)) to (B+or-C)
1701 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1702 N1.getOperand(0).getOpcode() == ISD::SUB &&
1703 N0 == N1.getOperand(0).getOperand(1))
1704 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1705 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1707 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1708 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1709 SDValue N00 = N0.getOperand(0);
1710 SDValue N01 = N0.getOperand(1);
1711 SDValue N10 = N1.getOperand(0);
1712 SDValue N11 = N1.getOperand(1);
1714 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1715 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1716 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1717 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1720 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1721 return SDValue(N, 0);
1723 // fold (a+b) -> (a|b) iff a and b share no bits.
1724 if (VT.isInteger() && !VT.isVector()) {
1725 APInt LHSZero, LHSOne;
1726 APInt RHSZero, RHSOne;
1727 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1729 if (LHSZero.getBoolValue()) {
1730 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1732 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1733 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1734 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1735 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1736 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1741 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1742 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1743 isNullConstant(N1.getOperand(0).getOperand(0)))
1744 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1745 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1746 N1.getOperand(0).getOperand(1),
1748 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1749 isNullConstant(N0.getOperand(0).getOperand(0)))
1750 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1751 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1752 N0.getOperand(0).getOperand(1),
1755 if (N1.getOpcode() == ISD::AND) {
1756 SDValue AndOp0 = N1.getOperand(0);
1757 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1758 unsigned DestBits = VT.getScalarType().getSizeInBits();
1760 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1761 // and similar xforms where the inner op is either ~0 or 0.
1762 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1764 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1768 // add (sext i1), X -> sub X, (zext i1)
1769 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1770 N0.getOperand(0).getValueType() == MVT::i1 &&
1771 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1773 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1774 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1777 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1778 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1779 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1780 if (TN->getVT() == MVT::i1) {
1782 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1783 DAG.getConstant(1, DL, VT));
1784 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1791 SDValue DAGCombiner::visitADDC(SDNode *N) {
1792 SDValue N0 = N->getOperand(0);
1793 SDValue N1 = N->getOperand(1);
1794 EVT VT = N0.getValueType();
1796 // If the flag result is dead, turn this into an ADD.
1797 if (!N->hasAnyUseOfValue(1))
1798 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1799 DAG.getNode(ISD::CARRY_FALSE,
1800 SDLoc(N), MVT::Glue));
1802 // canonicalize constant to RHS.
1803 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1804 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1806 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1808 // fold (addc x, 0) -> x + no carry out
1809 if (isNullConstant(N1))
1810 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1811 SDLoc(N), MVT::Glue));
1813 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1814 APInt LHSZero, LHSOne;
1815 APInt RHSZero, RHSOne;
1816 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1818 if (LHSZero.getBoolValue()) {
1819 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1821 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1822 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1823 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1824 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1825 DAG.getNode(ISD::CARRY_FALSE,
1826 SDLoc(N), MVT::Glue));
1832 SDValue DAGCombiner::visitADDE(SDNode *N) {
1833 SDValue N0 = N->getOperand(0);
1834 SDValue N1 = N->getOperand(1);
1835 SDValue CarryIn = N->getOperand(2);
1837 // canonicalize constant to RHS
1838 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1839 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1841 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1844 // fold (adde x, y, false) -> (addc x, y)
1845 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1846 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1851 // Since it may not be valid to emit a fold to zero for vector initializers
1852 // check if we can before folding.
1853 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1855 bool LegalOperations, bool LegalTypes) {
1857 return DAG.getConstant(0, DL, VT);
1858 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1859 return DAG.getConstant(0, DL, VT);
1863 SDValue DAGCombiner::visitSUB(SDNode *N) {
1864 SDValue N0 = N->getOperand(0);
1865 SDValue N1 = N->getOperand(1);
1866 EVT VT = N0.getValueType();
1869 if (VT.isVector()) {
1870 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1873 // fold (sub x, 0) -> x, vector edition
1874 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1878 // fold (sub x, x) -> 0
1879 // FIXME: Refactor this and xor and other similar operations together.
1881 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1882 // fold (sub c1, c2) -> c1-c2
1883 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1884 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1886 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1887 // fold (sub x, c) -> (add x, -c)
1890 return DAG.getNode(ISD::ADD, DL, VT, N0,
1891 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1893 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1894 if (isAllOnesConstant(N0))
1895 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1896 // fold A-(A-B) -> B
1897 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1898 return N1.getOperand(1);
1899 // fold (A+B)-A -> B
1900 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1901 return N0.getOperand(1);
1902 // fold (A+B)-B -> A
1903 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1904 return N0.getOperand(0);
1905 // fold C2-(A+C1) -> (C2-C1)-A
1906 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1907 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1908 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1910 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1912 return DAG.getNode(ISD::SUB, DL, VT, NewC,
1915 // fold ((A+(B+or-C))-B) -> A+or-C
1916 if (N0.getOpcode() == ISD::ADD &&
1917 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1918 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1919 N0.getOperand(1).getOperand(0) == N1)
1920 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1921 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1922 // fold ((A+(C+B))-B) -> A+C
1923 if (N0.getOpcode() == ISD::ADD &&
1924 N0.getOperand(1).getOpcode() == ISD::ADD &&
1925 N0.getOperand(1).getOperand(1) == N1)
1926 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1927 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1928 // fold ((A-(B-C))-C) -> A-B
1929 if (N0.getOpcode() == ISD::SUB &&
1930 N0.getOperand(1).getOpcode() == ISD::SUB &&
1931 N0.getOperand(1).getOperand(1) == N1)
1932 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1933 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1935 // If either operand of a sub is undef, the result is undef
1936 if (N0.getOpcode() == ISD::UNDEF)
1938 if (N1.getOpcode() == ISD::UNDEF)
1941 // If the relocation model supports it, consider symbol offsets.
1942 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1943 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1944 // fold (sub Sym, c) -> Sym-c
1945 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1946 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1948 (uint64_t)N1C->getSExtValue());
1949 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1950 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1951 if (GA->getGlobal() == GB->getGlobal())
1952 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1956 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1957 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1958 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1959 if (TN->getVT() == MVT::i1) {
1961 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1962 DAG.getConstant(1, DL, VT));
1963 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1970 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1971 SDValue N0 = N->getOperand(0);
1972 SDValue N1 = N->getOperand(1);
1973 EVT VT = N0.getValueType();
1975 // If the flag result is dead, turn this into an SUB.
1976 if (!N->hasAnyUseOfValue(1))
1977 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1978 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1981 // fold (subc x, x) -> 0 + no borrow
1984 return CombineTo(N, DAG.getConstant(0, DL, VT),
1985 DAG.getNode(ISD::CARRY_FALSE, DL,
1989 // fold (subc x, 0) -> x + no borrow
1990 if (isNullConstant(N1))
1991 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1994 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1995 if (isAllOnesConstant(N0))
1996 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1997 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
2003 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2004 SDValue N0 = N->getOperand(0);
2005 SDValue N1 = N->getOperand(1);
2006 SDValue CarryIn = N->getOperand(2);
2008 // fold (sube x, y, false) -> (subc x, y)
2009 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2010 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2015 SDValue DAGCombiner::visitMUL(SDNode *N) {
2016 SDValue N0 = N->getOperand(0);
2017 SDValue N1 = N->getOperand(1);
2018 EVT VT = N0.getValueType();
2020 // fold (mul x, undef) -> 0
2021 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2022 return DAG.getConstant(0, SDLoc(N), VT);
2024 bool N0IsConst = false;
2025 bool N1IsConst = false;
2026 bool N1IsOpaqueConst = false;
2027 bool N0IsOpaqueConst = false;
2028 APInt ConstValue0, ConstValue1;
2030 if (VT.isVector()) {
2031 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2034 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2035 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2037 N0IsConst = isa<ConstantSDNode>(N0);
2039 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2040 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2042 N1IsConst = isa<ConstantSDNode>(N1);
2044 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2045 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2049 // fold (mul c1, c2) -> c1*c2
2050 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2051 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2052 N0.getNode(), N1.getNode());
2054 // canonicalize constant to RHS (vector doesn't have to splat)
2055 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2056 !isConstantIntBuildVectorOrConstantInt(N1))
2057 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2058 // fold (mul x, 0) -> 0
2059 if (N1IsConst && ConstValue1 == 0)
2061 // We require a splat of the entire scalar bit width for non-contiguous
2064 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2065 // fold (mul x, 1) -> x
2066 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2068 // fold (mul x, -1) -> 0-x
2069 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2071 return DAG.getNode(ISD::SUB, DL, VT,
2072 DAG.getConstant(0, DL, VT), N0);
2074 // fold (mul x, (1 << c)) -> x << c
2075 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2078 return DAG.getNode(ISD::SHL, DL, VT, N0,
2079 DAG.getConstant(ConstValue1.logBase2(), DL,
2080 getShiftAmountTy(N0.getValueType())));
2082 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2083 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2085 unsigned Log2Val = (-ConstValue1).logBase2();
2087 // FIXME: If the input is something that is easily negated (e.g. a
2088 // single-use add), we should put the negate there.
2089 return DAG.getNode(ISD::SUB, DL, VT,
2090 DAG.getConstant(0, DL, VT),
2091 DAG.getNode(ISD::SHL, DL, VT, N0,
2092 DAG.getConstant(Log2Val, DL,
2093 getShiftAmountTy(N0.getValueType()))));
2097 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2098 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2099 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2100 isa<ConstantSDNode>(N0.getOperand(1)))) {
2101 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2102 N1, N0.getOperand(1));
2103 AddToWorklist(C3.getNode());
2104 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2105 N0.getOperand(0), C3);
2108 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2111 SDValue Sh(nullptr,0), Y(nullptr,0);
2112 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2113 if (N0.getOpcode() == ISD::SHL &&
2114 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2115 isa<ConstantSDNode>(N0.getOperand(1))) &&
2116 N0.getNode()->hasOneUse()) {
2118 } else if (N1.getOpcode() == ISD::SHL &&
2119 isa<ConstantSDNode>(N1.getOperand(1)) &&
2120 N1.getNode()->hasOneUse()) {
2125 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2126 Sh.getOperand(0), Y);
2127 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2128 Mul, Sh.getOperand(1));
2132 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2133 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2134 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2135 isa<ConstantSDNode>(N0.getOperand(1))))
2136 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2137 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2138 N0.getOperand(0), N1),
2139 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2140 N0.getOperand(1), N1));
2143 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2149 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2150 SDValue N0 = N->getOperand(0);
2151 SDValue N1 = N->getOperand(1);
2152 EVT VT = N->getValueType(0);
2156 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2159 // fold (sdiv c1, c2) -> c1/c2
2160 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2161 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2162 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2163 return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2164 // fold (sdiv X, 1) -> X
2165 if (N1C && N1C->isOne())
2167 // fold (sdiv X, -1) -> 0-X
2168 if (N1C && N1C->isAllOnesValue()) {
2170 return DAG.getNode(ISD::SUB, DL, VT,
2171 DAG.getConstant(0, DL, VT), N0);
2173 // If we know the sign bits of both operands are zero, strength reduce to a
2174 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2175 if (!VT.isVector()) {
2176 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2177 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2181 // fold (sdiv X, pow2) -> simple ops after legalize
2182 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2183 (N1C->getAPIntValue().isPowerOf2() ||
2184 (-N1C->getAPIntValue()).isPowerOf2())) {
2185 // If dividing by powers of two is cheap, then don't perform the following
2187 if (TLI.isPow2SDivCheap())
2190 // Target-specific implementation of sdiv x, pow2.
2191 SDValue Res = BuildSDIVPow2(N);
2195 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2198 // Splat the sign bit into the register
2200 DAG.getNode(ISD::SRA, DL, VT, N0,
2201 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2202 getShiftAmountTy(N0.getValueType())));
2203 AddToWorklist(SGN.getNode());
2205 // Add (N0 < 0) ? abs2 - 1 : 0;
2207 DAG.getNode(ISD::SRL, DL, VT, SGN,
2208 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2209 getShiftAmountTy(SGN.getValueType())));
2210 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2211 AddToWorklist(SRL.getNode());
2212 AddToWorklist(ADD.getNode()); // Divide by pow2
2213 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2214 DAG.getConstant(lg2, DL,
2215 getShiftAmountTy(ADD.getValueType())));
2217 // If we're dividing by a positive value, we're done. Otherwise, we must
2218 // negate the result.
2219 if (N1C->getAPIntValue().isNonNegative())
2222 AddToWorklist(SRA.getNode());
2223 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2226 // If integer divide is expensive and we satisfy the requirements, emit an
2227 // alternate sequence.
2228 if (N1C && !TLI.isIntDivCheap()) {
2229 SDValue Op = BuildSDIV(N);
2230 if (Op.getNode()) return Op;
2234 if (N0.getOpcode() == ISD::UNDEF)
2235 return DAG.getConstant(0, SDLoc(N), VT);
2236 // X / undef -> undef
2237 if (N1.getOpcode() == ISD::UNDEF)
2243 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2244 SDValue N0 = N->getOperand(0);
2245 SDValue N1 = N->getOperand(1);
2246 EVT VT = N->getValueType(0);
2250 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2253 // fold (udiv c1, c2) -> c1/c2
2254 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2255 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2257 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT,
2260 // fold (udiv x, (1 << c)) -> x >>u c
2261 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) {
2263 return DAG.getNode(ISD::SRL, DL, VT, N0,
2264 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2265 getShiftAmountTy(N0.getValueType())));
2267 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2268 if (N1.getOpcode() == ISD::SHL) {
2269 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2270 if (SHC->getAPIntValue().isPowerOf2()) {
2271 EVT ADDVT = N1.getOperand(1).getValueType();
2273 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2275 DAG.getConstant(SHC->getAPIntValue()
2278 AddToWorklist(Add.getNode());
2279 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2283 // fold (udiv x, c) -> alternate
2284 if (N1C && !TLI.isIntDivCheap()) {
2285 SDValue Op = BuildUDIV(N);
2286 if (Op.getNode()) return Op;
2290 if (N0.getOpcode() == ISD::UNDEF)
2291 return DAG.getConstant(0, SDLoc(N), VT);
2292 // X / undef -> undef
2293 if (N1.getOpcode() == ISD::UNDEF)
2299 SDValue DAGCombiner::visitSREM(SDNode *N) {
2300 SDValue N0 = N->getOperand(0);
2301 SDValue N1 = N->getOperand(1);
2302 EVT VT = N->getValueType(0);
2304 // fold (srem c1, c2) -> c1%c2
2305 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2306 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2308 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT,
2311 // If we know the sign bits of both operands are zero, strength reduce to a
2312 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2313 if (!VT.isVector()) {
2314 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2315 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2318 // If X/C can be simplified by the division-by-constant logic, lower
2319 // X%C to the equivalent of X-X/C*C.
2320 if (N1C && !N1C->isNullValue()) {
2321 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2322 AddToWorklist(Div.getNode());
2323 SDValue OptimizedDiv = combine(Div.getNode());
2324 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2325 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2327 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2328 AddToWorklist(Mul.getNode());
2334 if (N0.getOpcode() == ISD::UNDEF)
2335 return DAG.getConstant(0, SDLoc(N), VT);
2336 // X % undef -> undef
2337 if (N1.getOpcode() == ISD::UNDEF)
2343 SDValue DAGCombiner::visitUREM(SDNode *N) {
2344 SDValue N0 = N->getOperand(0);
2345 SDValue N1 = N->getOperand(1);
2346 EVT VT = N->getValueType(0);
2348 // fold (urem c1, c2) -> c1%c2
2349 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2350 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2352 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT,
2355 // fold (urem x, pow2) -> (and x, pow2-1)
2356 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2357 N1C->getAPIntValue().isPowerOf2()) {
2359 return DAG.getNode(ISD::AND, DL, VT, N0,
2360 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2362 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2363 if (N1.getOpcode() == ISD::SHL) {
2364 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2365 if (SHC->getAPIntValue().isPowerOf2()) {
2368 DAG.getNode(ISD::ADD, DL, VT, N1,
2369 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2371 AddToWorklist(Add.getNode());
2372 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2377 // If X/C can be simplified by the division-by-constant logic, lower
2378 // X%C to the equivalent of X-X/C*C.
2379 if (N1C && !N1C->isNullValue()) {
2380 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2381 AddToWorklist(Div.getNode());
2382 SDValue OptimizedDiv = combine(Div.getNode());
2383 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2384 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2386 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2387 AddToWorklist(Mul.getNode());
2393 if (N0.getOpcode() == ISD::UNDEF)
2394 return DAG.getConstant(0, SDLoc(N), VT);
2395 // X % undef -> undef
2396 if (N1.getOpcode() == ISD::UNDEF)
2402 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2403 SDValue N0 = N->getOperand(0);
2404 SDValue N1 = N->getOperand(1);
2405 EVT VT = N->getValueType(0);
2408 // fold (mulhs x, 0) -> 0
2409 if (isNullConstant(N1))
2411 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2412 if (isOneConstant(N1)) {
2414 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2415 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2417 getShiftAmountTy(N0.getValueType())));
2419 // fold (mulhs x, undef) -> 0
2420 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2421 return DAG.getConstant(0, SDLoc(N), VT);
2423 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2425 if (VT.isSimple() && !VT.isVector()) {
2426 MVT Simple = VT.getSimpleVT();
2427 unsigned SimpleSize = Simple.getSizeInBits();
2428 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2429 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2430 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2431 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2432 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2433 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2434 DAG.getConstant(SimpleSize, DL,
2435 getShiftAmountTy(N1.getValueType())));
2436 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2443 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2444 SDValue N0 = N->getOperand(0);
2445 SDValue N1 = N->getOperand(1);
2446 EVT VT = N->getValueType(0);
2449 // fold (mulhu x, 0) -> 0
2450 if (isNullConstant(N1))
2452 // fold (mulhu x, 1) -> 0
2453 if (isOneConstant(N1))
2454 return DAG.getConstant(0, DL, N0.getValueType());
2455 // fold (mulhu x, undef) -> 0
2456 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2457 return DAG.getConstant(0, DL, VT);
2459 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2461 if (VT.isSimple() && !VT.isVector()) {
2462 MVT Simple = VT.getSimpleVT();
2463 unsigned SimpleSize = Simple.getSizeInBits();
2464 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2465 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2466 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2467 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2468 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2469 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2470 DAG.getConstant(SimpleSize, DL,
2471 getShiftAmountTy(N1.getValueType())));
2472 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2479 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2480 /// give the opcodes for the two computations that are being performed. Return
2481 /// true if a simplification was made.
2482 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2484 // If the high half is not needed, just compute the low half.
2485 bool HiExists = N->hasAnyUseOfValue(1);
2487 (!LegalOperations ||
2488 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2489 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2490 return CombineTo(N, Res, Res);
2493 // If the low half is not needed, just compute the high half.
2494 bool LoExists = N->hasAnyUseOfValue(0);
2496 (!LegalOperations ||
2497 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2498 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2499 return CombineTo(N, Res, Res);
2502 // If both halves are used, return as it is.
2503 if (LoExists && HiExists)
2506 // If the two computed results can be simplified separately, separate them.
2508 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2509 AddToWorklist(Lo.getNode());
2510 SDValue LoOpt = combine(Lo.getNode());
2511 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2512 (!LegalOperations ||
2513 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2514 return CombineTo(N, LoOpt, LoOpt);
2518 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2519 AddToWorklist(Hi.getNode());
2520 SDValue HiOpt = combine(Hi.getNode());
2521 if (HiOpt.getNode() && HiOpt != Hi &&
2522 (!LegalOperations ||
2523 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2524 return CombineTo(N, HiOpt, HiOpt);
2530 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2531 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2532 if (Res.getNode()) return Res;
2534 EVT VT = N->getValueType(0);
2537 // If the type is twice as wide is legal, transform the mulhu to a wider
2538 // multiply plus a shift.
2539 if (VT.isSimple() && !VT.isVector()) {
2540 MVT Simple = VT.getSimpleVT();
2541 unsigned SimpleSize = Simple.getSizeInBits();
2542 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2543 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2544 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2545 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2546 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2547 // Compute the high part as N1.
2548 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2549 DAG.getConstant(SimpleSize, DL,
2550 getShiftAmountTy(Lo.getValueType())));
2551 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2552 // Compute the low part as N0.
2553 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2554 return CombineTo(N, Lo, Hi);
2561 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2562 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2563 if (Res.getNode()) return Res;
2565 EVT VT = N->getValueType(0);
2568 // If the type is twice as wide is legal, transform the mulhu to a wider
2569 // multiply plus a shift.
2570 if (VT.isSimple() && !VT.isVector()) {
2571 MVT Simple = VT.getSimpleVT();
2572 unsigned SimpleSize = Simple.getSizeInBits();
2573 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2574 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2575 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2576 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2577 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2578 // Compute the high part as N1.
2579 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2580 DAG.getConstant(SimpleSize, DL,
2581 getShiftAmountTy(Lo.getValueType())));
2582 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2583 // Compute the low part as N0.
2584 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2585 return CombineTo(N, Lo, Hi);
2592 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2593 // (smulo x, 2) -> (saddo x, x)
2594 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2595 if (C2->getAPIntValue() == 2)
2596 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2597 N->getOperand(0), N->getOperand(0));
2602 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2603 // (umulo x, 2) -> (uaddo x, x)
2604 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2605 if (C2->getAPIntValue() == 2)
2606 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2607 N->getOperand(0), N->getOperand(0));
2612 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2613 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2614 if (Res.getNode()) return Res;
2619 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2620 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2621 if (Res.getNode()) return Res;
2626 /// If this is a binary operator with two operands of the same opcode, try to
2628 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2629 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2630 EVT VT = N0.getValueType();
2631 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2633 // Bail early if none of these transforms apply.
2634 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2636 // For each of OP in AND/OR/XOR:
2637 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2638 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2639 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2640 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2641 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2643 // do not sink logical op inside of a vector extend, since it may combine
2645 EVT Op0VT = N0.getOperand(0).getValueType();
2646 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2647 N0.getOpcode() == ISD::SIGN_EXTEND ||
2648 N0.getOpcode() == ISD::BSWAP ||
2649 // Avoid infinite looping with PromoteIntBinOp.
2650 (N0.getOpcode() == ISD::ANY_EXTEND &&
2651 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2652 (N0.getOpcode() == ISD::TRUNCATE &&
2653 (!TLI.isZExtFree(VT, Op0VT) ||
2654 !TLI.isTruncateFree(Op0VT, VT)) &&
2655 TLI.isTypeLegal(Op0VT))) &&
2657 Op0VT == N1.getOperand(0).getValueType() &&
2658 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2659 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2660 N0.getOperand(0).getValueType(),
2661 N0.getOperand(0), N1.getOperand(0));
2662 AddToWorklist(ORNode.getNode());
2663 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2666 // For each of OP in SHL/SRL/SRA/AND...
2667 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2668 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2669 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2670 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2671 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2672 N0.getOperand(1) == N1.getOperand(1)) {
2673 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2674 N0.getOperand(0).getValueType(),
2675 N0.getOperand(0), N1.getOperand(0));
2676 AddToWorklist(ORNode.getNode());
2677 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2678 ORNode, N0.getOperand(1));
2681 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2682 // Only perform this optimization after type legalization and before
2683 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2684 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2685 // we don't want to undo this promotion.
2686 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2688 if ((N0.getOpcode() == ISD::BITCAST ||
2689 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2690 Level == AfterLegalizeTypes) {
2691 SDValue In0 = N0.getOperand(0);
2692 SDValue In1 = N1.getOperand(0);
2693 EVT In0Ty = In0.getValueType();
2694 EVT In1Ty = In1.getValueType();
2696 // If both incoming values are integers, and the original types are the
2698 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2699 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2700 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2701 AddToWorklist(Op.getNode());
2706 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2707 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2708 // If both shuffles use the same mask, and both shuffle within a single
2709 // vector, then it is worthwhile to move the swizzle after the operation.
2710 // The type-legalizer generates this pattern when loading illegal
2711 // vector types from memory. In many cases this allows additional shuffle
2713 // There are other cases where moving the shuffle after the xor/and/or
2714 // is profitable even if shuffles don't perform a swizzle.
2715 // If both shuffles use the same mask, and both shuffles have the same first
2716 // or second operand, then it might still be profitable to move the shuffle
2717 // after the xor/and/or operation.
2718 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2719 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2720 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2722 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2723 "Inputs to shuffles are not the same type");
2725 // Check that both shuffles use the same mask. The masks are known to be of
2726 // the same length because the result vector type is the same.
2727 // Check also that shuffles have only one use to avoid introducing extra
2729 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2730 SVN0->getMask().equals(SVN1->getMask())) {
2731 SDValue ShOp = N0->getOperand(1);
2733 // Don't try to fold this node if it requires introducing a
2734 // build vector of all zeros that might be illegal at this stage.
2735 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2737 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2742 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2743 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2744 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2745 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2746 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2747 N0->getOperand(0), N1->getOperand(0));
2748 AddToWorklist(NewNode.getNode());
2749 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2750 &SVN0->getMask()[0]);
2753 // Don't try to fold this node if it requires introducing a
2754 // build vector of all zeros that might be illegal at this stage.
2755 ShOp = N0->getOperand(0);
2756 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2758 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2763 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2764 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2765 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2766 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2767 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2768 N0->getOperand(1), N1->getOperand(1));
2769 AddToWorklist(NewNode.getNode());
2770 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2771 &SVN0->getMask()[0]);
2779 /// This contains all DAGCombine rules which reduce two values combined by
2780 /// an And operation to a single value. This makes them reusable in the context
2781 /// of visitSELECT(). Rules involving constants are not included as
2782 /// visitSELECT() already handles those cases.
2783 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2784 SDNode *LocReference) {
2785 EVT VT = N1.getValueType();
2787 // fold (and x, undef) -> 0
2788 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2789 return DAG.getConstant(0, SDLoc(LocReference), VT);
2790 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2791 SDValue LL, LR, RL, RR, CC0, CC1;
2792 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2793 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2794 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2796 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2797 LL.getValueType().isInteger()) {
2798 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2799 if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2800 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2801 LR.getValueType(), LL, RL);
2802 AddToWorklist(ORNode.getNode());
2803 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2805 if (isAllOnesConstant(LR)) {
2806 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2807 if (Op1 == ISD::SETEQ) {
2808 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2809 LR.getValueType(), LL, RL);
2810 AddToWorklist(ANDNode.getNode());
2811 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2813 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2814 if (Op1 == ISD::SETGT) {
2815 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2816 LR.getValueType(), LL, RL);
2817 AddToWorklist(ORNode.getNode());
2818 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2822 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2823 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2824 Op0 == Op1 && LL.getValueType().isInteger() &&
2825 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2826 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2828 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2829 LL, DAG.getConstant(1, DL,
2830 LL.getValueType()));
2831 AddToWorklist(ADDNode.getNode());
2832 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2833 DAG.getConstant(2, DL, LL.getValueType()),
2836 // canonicalize equivalent to ll == rl
2837 if (LL == RR && LR == RL) {
2838 Op1 = ISD::getSetCCSwappedOperands(Op1);
2841 if (LL == RL && LR == RR) {
2842 bool isInteger = LL.getValueType().isInteger();
2843 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2844 if (Result != ISD::SETCC_INVALID &&
2845 (!LegalOperations ||
2846 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2847 TLI.isOperationLegal(ISD::SETCC,
2848 getSetCCResultType(N0.getSimpleValueType())))))
2849 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2854 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2855 VT.getSizeInBits() <= 64) {
2856 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2857 APInt ADDC = ADDI->getAPIntValue();
2858 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2859 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2860 // immediate for an add, but it is legal if its top c2 bits are set,
2861 // transform the ADD so the immediate doesn't need to be materialized
2863 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2864 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2865 SRLI->getZExtValue());
2866 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2868 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2871 DAG.getNode(ISD::ADD, DL, VT,
2872 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2873 CombineTo(N0.getNode(), NewAdd);
2874 // Return N so it doesn't get rechecked!
2875 return SDValue(LocReference, 0);
2886 SDValue DAGCombiner::visitAND(SDNode *N) {
2887 SDValue N0 = N->getOperand(0);
2888 SDValue N1 = N->getOperand(1);
2889 EVT VT = N1.getValueType();
2892 if (VT.isVector()) {
2893 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2896 // fold (and x, 0) -> 0, vector edition
2897 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2898 // do not return N0, because undef node may exist in N0
2899 return DAG.getConstant(
2900 APInt::getNullValue(
2901 N0.getValueType().getScalarType().getSizeInBits()),
2902 SDLoc(N), N0.getValueType());
2903 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2904 // do not return N1, because undef node may exist in N1
2905 return DAG.getConstant(
2906 APInt::getNullValue(
2907 N1.getValueType().getScalarType().getSizeInBits()),
2908 SDLoc(N), N1.getValueType());
2910 // fold (and x, -1) -> x, vector edition
2911 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2913 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2917 // fold (and c1, c2) -> c1&c2
2918 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2919 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2920 if (N0C && N1C && !N1C->isOpaque())
2921 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2922 // canonicalize constant to RHS
2923 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2924 !isConstantIntBuildVectorOrConstantInt(N1))
2925 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2926 // fold (and x, -1) -> x
2927 if (isAllOnesConstant(N1))
2929 // if (and x, c) is known to be zero, return 0
2930 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2931 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2932 APInt::getAllOnesValue(BitWidth)))
2933 return DAG.getConstant(0, SDLoc(N), VT);
2935 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2937 // fold (and (or x, C), D) -> D if (C & D) == D
2938 if (N1C && N0.getOpcode() == ISD::OR)
2939 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2940 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2942 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2943 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2944 SDValue N0Op0 = N0.getOperand(0);
2945 APInt Mask = ~N1C->getAPIntValue();
2946 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2947 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2948 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2949 N0.getValueType(), N0Op0);
2951 // Replace uses of the AND with uses of the Zero extend node.
2954 // We actually want to replace all uses of the any_extend with the
2955 // zero_extend, to avoid duplicating things. This will later cause this
2956 // AND to be folded.
2957 CombineTo(N0.getNode(), Zext);
2958 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2961 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2962 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2963 // already be zero by virtue of the width of the base type of the load.
2965 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2967 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2968 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2969 N0.getOpcode() == ISD::LOAD) {
2970 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2971 N0 : N0.getOperand(0) );
2973 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2974 // This can be a pure constant or a vector splat, in which case we treat the
2975 // vector as a scalar and use the splat value.
2976 APInt Constant = APInt::getNullValue(1);
2977 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2978 Constant = C->getAPIntValue();
2979 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2980 APInt SplatValue, SplatUndef;
2981 unsigned SplatBitSize;
2983 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2984 SplatBitSize, HasAnyUndefs);
2986 // Undef bits can contribute to a possible optimisation if set, so
2988 SplatValue |= SplatUndef;
2990 // The splat value may be something like "0x00FFFFFF", which means 0 for
2991 // the first vector value and FF for the rest, repeating. We need a mask
2992 // that will apply equally to all members of the vector, so AND all the
2993 // lanes of the constant together.
2994 EVT VT = Vector->getValueType(0);
2995 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2997 // If the splat value has been compressed to a bitlength lower
2998 // than the size of the vector lane, we need to re-expand it to
3000 if (BitWidth > SplatBitSize)
3001 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3002 SplatBitSize < BitWidth;
3003 SplatBitSize = SplatBitSize * 2)
3004 SplatValue |= SplatValue.shl(SplatBitSize);
3006 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3007 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3008 if (SplatBitSize % BitWidth == 0) {
3009 Constant = APInt::getAllOnesValue(BitWidth);
3010 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3011 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3016 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3017 // actually legal and isn't going to get expanded, else this is a false
3019 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3020 Load->getValueType(0),
3021 Load->getMemoryVT());
3023 // Resize the constant to the same size as the original memory access before
3024 // extension. If it is still the AllOnesValue then this AND is completely
3027 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3030 switch (Load->getExtensionType()) {
3031 default: B = false; break;
3032 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3034 case ISD::NON_EXTLOAD: B = true; break;
3037 if (B && Constant.isAllOnesValue()) {
3038 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3039 // preserve semantics once we get rid of the AND.
3040 SDValue NewLoad(Load, 0);
3041 if (Load->getExtensionType() == ISD::EXTLOAD) {
3042 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3043 Load->getValueType(0), SDLoc(Load),
3044 Load->getChain(), Load->getBasePtr(),
3045 Load->getOffset(), Load->getMemoryVT(),
3046 Load->getMemOperand());
3047 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3048 if (Load->getNumValues() == 3) {
3049 // PRE/POST_INC loads have 3 values.
3050 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3051 NewLoad.getValue(2) };
3052 CombineTo(Load, To, 3, true);
3054 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3058 // Fold the AND away, taking care not to fold to the old load node if we
3060 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3062 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3066 // fold (and (load x), 255) -> (zextload x, i8)
3067 // fold (and (extload x, i16), 255) -> (zextload x, i8)
3068 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3069 if (N1C && (N0.getOpcode() == ISD::LOAD ||
3070 (N0.getOpcode() == ISD::ANY_EXTEND &&
3071 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3072 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3073 LoadSDNode *LN0 = HasAnyExt
3074 ? cast<LoadSDNode>(N0.getOperand(0))
3075 : cast<LoadSDNode>(N0);
3076 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3077 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3078 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3079 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3080 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3081 EVT LoadedVT = LN0->getMemoryVT();
3082 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3084 if (ExtVT == LoadedVT &&
3085 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3089 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3090 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3091 LN0->getMemOperand());
3093 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3094 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3097 // Do not change the width of a volatile load.
3098 // Do not generate loads of non-round integer types since these can
3099 // be expensive (and would be wrong if the type is not byte sized).
3100 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3101 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3103 EVT PtrType = LN0->getOperand(1).getValueType();
3105 unsigned Alignment = LN0->getAlignment();
3106 SDValue NewPtr = LN0->getBasePtr();
3108 // For big endian targets, we need to add an offset to the pointer
3109 // to load the correct bytes. For little endian systems, we merely
3110 // need to read fewer bytes from the same pointer.
3111 if (TLI.isBigEndian()) {
3112 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3113 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3114 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3116 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3117 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3118 Alignment = MinAlign(Alignment, PtrOff);
3121 AddToWorklist(NewPtr.getNode());
3124 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3125 LN0->getChain(), NewPtr,
3126 LN0->getPointerInfo(),
3127 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3128 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3130 CombineTo(LN0, Load, Load.getValue(1));
3131 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3137 if (SDValue Combined = visitANDLike(N0, N1, N))
3140 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3141 if (N0.getOpcode() == N1.getOpcode()) {
3142 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3143 if (Tmp.getNode()) return Tmp;
3146 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3147 // fold (and (sra)) -> (and (srl)) when possible.
3148 if (!VT.isVector() &&
3149 SimplifyDemandedBits(SDValue(N, 0)))
3150 return SDValue(N, 0);
3152 // fold (zext_inreg (extload x)) -> (zextload x)
3153 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3154 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3155 EVT MemVT = LN0->getMemoryVT();
3156 // If we zero all the possible extended bits, then we can turn this into
3157 // a zextload if we are running before legalize or the operation is legal.
3158 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3159 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3160 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3161 ((!LegalOperations && !LN0->isVolatile()) ||
3162 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3163 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3164 LN0->getChain(), LN0->getBasePtr(),
3165 MemVT, LN0->getMemOperand());
3167 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3168 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3171 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3172 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3174 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3175 EVT MemVT = LN0->getMemoryVT();
3176 // If we zero all the possible extended bits, then we can turn this into
3177 // a zextload if we are running before legalize or the operation is legal.
3178 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3179 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3180 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3181 ((!LegalOperations && !LN0->isVolatile()) ||
3182 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3183 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3184 LN0->getChain(), LN0->getBasePtr(),
3185 MemVT, LN0->getMemOperand());
3187 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3188 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3191 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3192 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3193 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3194 N0.getOperand(1), false);
3195 if (BSwap.getNode())
3202 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3203 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3204 bool DemandHighBits) {
3205 if (!LegalOperations)
3208 EVT VT = N->getValueType(0);
3209 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3211 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3214 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3215 bool LookPassAnd0 = false;
3216 bool LookPassAnd1 = false;
3217 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3219 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3221 if (N0.getOpcode() == ISD::AND) {
3222 if (!N0.getNode()->hasOneUse())
3224 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3225 if (!N01C || N01C->getZExtValue() != 0xFF00)
3227 N0 = N0.getOperand(0);
3228 LookPassAnd0 = true;
3231 if (N1.getOpcode() == ISD::AND) {
3232 if (!N1.getNode()->hasOneUse())
3234 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3235 if (!N11C || N11C->getZExtValue() != 0xFF)
3237 N1 = N1.getOperand(0);
3238 LookPassAnd1 = true;
3241 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3243 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3245 if (!N0.getNode()->hasOneUse() ||
3246 !N1.getNode()->hasOneUse())
3249 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3250 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3253 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3256 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3257 SDValue N00 = N0->getOperand(0);
3258 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3259 if (!N00.getNode()->hasOneUse())
3261 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3262 if (!N001C || N001C->getZExtValue() != 0xFF)
3264 N00 = N00.getOperand(0);
3265 LookPassAnd0 = true;
3268 SDValue N10 = N1->getOperand(0);
3269 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3270 if (!N10.getNode()->hasOneUse())
3272 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3273 if (!N101C || N101C->getZExtValue() != 0xFF00)
3275 N10 = N10.getOperand(0);
3276 LookPassAnd1 = true;
3282 // Make sure everything beyond the low halfword gets set to zero since the SRL
3283 // 16 will clear the top bits.
3284 unsigned OpSizeInBits = VT.getSizeInBits();
3285 if (DemandHighBits && OpSizeInBits > 16) {
3286 // If the left-shift isn't masked out then the only way this is a bswap is
3287 // if all bits beyond the low 8 are 0. In that case the entire pattern
3288 // reduces to a left shift anyway: leave it for other parts of the combiner.
3292 // However, if the right shift isn't masked out then it might be because
3293 // it's not needed. See if we can spot that too.
3294 if (!LookPassAnd1 &&
3295 !DAG.MaskedValueIsZero(
3296 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3300 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3301 if (OpSizeInBits > 16) {
3303 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3304 DAG.getConstant(OpSizeInBits - 16, DL,
3305 getShiftAmountTy(VT)));
3310 /// Return true if the specified node is an element that makes up a 32-bit
3311 /// packed halfword byteswap.
3312 /// ((x & 0x000000ff) << 8) |
3313 /// ((x & 0x0000ff00) >> 8) |
3314 /// ((x & 0x00ff0000) << 8) |
3315 /// ((x & 0xff000000) >> 8)
3316 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3317 if (!N.getNode()->hasOneUse())
3320 unsigned Opc = N.getOpcode();
3321 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3324 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3329 switch (N1C->getZExtValue()) {
3332 case 0xFF: Num = 0; break;
3333 case 0xFF00: Num = 1; break;
3334 case 0xFF0000: Num = 2; break;
3335 case 0xFF000000: Num = 3; break;
3338 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3339 SDValue N0 = N.getOperand(0);
3340 if (Opc == ISD::AND) {
3341 if (Num == 0 || Num == 2) {
3343 // (x >> 8) & 0xff0000
3344 if (N0.getOpcode() != ISD::SRL)
3346 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3347 if (!C || C->getZExtValue() != 8)
3350 // (x << 8) & 0xff00
3351 // (x << 8) & 0xff000000
3352 if (N0.getOpcode() != ISD::SHL)
3354 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3355 if (!C || C->getZExtValue() != 8)
3358 } else if (Opc == ISD::SHL) {
3360 // (x & 0xff0000) << 8
3361 if (Num != 0 && Num != 2)
3363 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3364 if (!C || C->getZExtValue() != 8)
3366 } else { // Opc == ISD::SRL
3367 // (x & 0xff00) >> 8
3368 // (x & 0xff000000) >> 8
3369 if (Num != 1 && Num != 3)
3371 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3372 if (!C || C->getZExtValue() != 8)
3379 Parts[Num] = N0.getOperand(0).getNode();
3383 /// Match a 32-bit packed halfword bswap. That is
3384 /// ((x & 0x000000ff) << 8) |
3385 /// ((x & 0x0000ff00) >> 8) |
3386 /// ((x & 0x00ff0000) << 8) |
3387 /// ((x & 0xff000000) >> 8)
3388 /// => (rotl (bswap x), 16)
3389 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3390 if (!LegalOperations)
3393 EVT VT = N->getValueType(0);
3396 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3400 // (or (or (and), (and)), (or (and), (and)))
3401 // (or (or (or (and), (and)), (and)), (and))
3402 if (N0.getOpcode() != ISD::OR)
3404 SDValue N00 = N0.getOperand(0);
3405 SDValue N01 = N0.getOperand(1);
3406 SDNode *Parts[4] = {};
3408 if (N1.getOpcode() == ISD::OR &&
3409 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3410 // (or (or (and), (and)), (or (and), (and)))
3411 SDValue N000 = N00.getOperand(0);
3412 if (!isBSwapHWordElement(N000, Parts))
3415 SDValue N001 = N00.getOperand(1);
3416 if (!isBSwapHWordElement(N001, Parts))
3418 SDValue N010 = N01.getOperand(0);
3419 if (!isBSwapHWordElement(N010, Parts))
3421 SDValue N011 = N01.getOperand(1);
3422 if (!isBSwapHWordElement(N011, Parts))
3425 // (or (or (or (and), (and)), (and)), (and))
3426 if (!isBSwapHWordElement(N1, Parts))
3428 if (!isBSwapHWordElement(N01, Parts))
3430 if (N00.getOpcode() != ISD::OR)
3432 SDValue N000 = N00.getOperand(0);
3433 if (!isBSwapHWordElement(N000, Parts))
3435 SDValue N001 = N00.getOperand(1);
3436 if (!isBSwapHWordElement(N001, Parts))
3440 // Make sure the parts are all coming from the same node.
3441 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3445 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3446 SDValue(Parts[0], 0));
3448 // Result of the bswap should be rotated by 16. If it's not legal, then
3449 // do (x << 16) | (x >> 16).
3450 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3451 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3452 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3453 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3454 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3455 return DAG.getNode(ISD::OR, DL, VT,
3456 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3457 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3460 /// This contains all DAGCombine rules which reduce two values combined by
3461 /// an Or operation to a single value \see visitANDLike().
3462 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3463 EVT VT = N1.getValueType();
3464 // fold (or x, undef) -> -1
3465 if (!LegalOperations &&
3466 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3467 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3468 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3469 SDLoc(LocReference), VT);
3471 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3472 SDValue LL, LR, RL, RR, CC0, CC1;
3473 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3474 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3475 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3477 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3478 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3479 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3480 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3481 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3482 LR.getValueType(), LL, RL);
3483 AddToWorklist(ORNode.getNode());
3484 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3486 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3487 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3488 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3489 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3490 LR.getValueType(), LL, RL);
3491 AddToWorklist(ANDNode.getNode());
3492 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3495 // canonicalize equivalent to ll == rl
3496 if (LL == RR && LR == RL) {
3497 Op1 = ISD::getSetCCSwappedOperands(Op1);
3500 if (LL == RL && LR == RR) {
3501 bool isInteger = LL.getValueType().isInteger();
3502 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3503 if (Result != ISD::SETCC_INVALID &&
3504 (!LegalOperations ||
3505 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3506 TLI.isOperationLegal(ISD::SETCC,
3507 getSetCCResultType(N0.getValueType())))))
3508 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3513 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3514 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3515 // Don't increase # computations.
3516 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3517 // We can only do this xform if we know that bits from X that are set in C2
3518 // but not in C1 are already zero. Likewise for Y.
3519 if (const ConstantSDNode *N0O1C =
3520 getAsNonOpaqueConstant(N0.getOperand(1))) {
3521 if (const ConstantSDNode *N1O1C =
3522 getAsNonOpaqueConstant(N1.getOperand(1))) {
3523 // We can only do this xform if we know that bits from X that are set in
3524 // C2 but not in C1 are already zero. Likewise for Y.
3525 const APInt &LHSMask = N0O1C->getAPIntValue();
3526 const APInt &RHSMask = N1O1C->getAPIntValue();
3528 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3529 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3530 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3531 N0.getOperand(0), N1.getOperand(0));
3532 SDLoc DL(LocReference);
3533 return DAG.getNode(ISD::AND, DL, VT, X,
3534 DAG.getConstant(LHSMask | RHSMask, DL, VT));
3540 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3541 if (N0.getOpcode() == ISD::AND &&
3542 N1.getOpcode() == ISD::AND &&
3543 N0.getOperand(0) == N1.getOperand(0) &&
3544 // Don't increase # computations.
3545 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3546 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3547 N0.getOperand(1), N1.getOperand(1));
3548 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3554 SDValue DAGCombiner::visitOR(SDNode *N) {
3555 SDValue N0 = N->getOperand(0);
3556 SDValue N1 = N->getOperand(1);
3557 EVT VT = N1.getValueType();
3560 if (VT.isVector()) {
3561 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3564 // fold (or x, 0) -> x, vector edition
3565 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3567 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3570 // fold (or x, -1) -> -1, vector edition
3571 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3572 // do not return N0, because undef node may exist in N0
3573 return DAG.getConstant(
3574 APInt::getAllOnesValue(
3575 N0.getValueType().getScalarType().getSizeInBits()),
3576 SDLoc(N), N0.getValueType());
3577 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3578 // do not return N1, because undef node may exist in N1
3579 return DAG.getConstant(
3580 APInt::getAllOnesValue(
3581 N1.getValueType().getScalarType().getSizeInBits()),
3582 SDLoc(N), N1.getValueType());
3584 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3585 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3586 // Do this only if the resulting shuffle is legal.
3587 if (isa<ShuffleVectorSDNode>(N0) &&
3588 isa<ShuffleVectorSDNode>(N1) &&
3589 // Avoid folding a node with illegal type.
3590 TLI.isTypeLegal(VT) &&
3591 N0->getOperand(1) == N1->getOperand(1) &&
3592 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3593 bool CanFold = true;
3594 unsigned NumElts = VT.getVectorNumElements();
3595 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3596 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3597 // We construct two shuffle masks:
3598 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3599 // and N1 as the second operand.
3600 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3601 // and N0 as the second operand.
3602 // We do this because OR is commutable and therefore there might be
3603 // two ways to fold this node into a shuffle.
3604 SmallVector<int,4> Mask1;
3605 SmallVector<int,4> Mask2;
3607 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3608 int M0 = SV0->getMaskElt(i);
3609 int M1 = SV1->getMaskElt(i);
3611 // Both shuffle indexes are undef. Propagate Undef.
3612 if (M0 < 0 && M1 < 0) {
3613 Mask1.push_back(M0);
3614 Mask2.push_back(M0);
3618 if (M0 < 0 || M1 < 0 ||
3619 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3620 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3625 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3626 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3630 // Fold this sequence only if the resulting shuffle is 'legal'.
3631 if (TLI.isShuffleMaskLegal(Mask1, VT))
3632 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3633 N1->getOperand(0), &Mask1[0]);
3634 if (TLI.isShuffleMaskLegal(Mask2, VT))
3635 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3636 N0->getOperand(0), &Mask2[0]);
3641 // fold (or c1, c2) -> c1|c2
3642 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3643 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3644 if (N0C && N1C && !N1C->isOpaque())
3645 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3646 // canonicalize constant to RHS
3647 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3648 !isConstantIntBuildVectorOrConstantInt(N1))
3649 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3650 // fold (or x, 0) -> x
3651 if (isNullConstant(N1))
3653 // fold (or x, -1) -> -1
3654 if (isAllOnesConstant(N1))
3656 // fold (or x, c) -> c iff (x & ~c) == 0
3657 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3660 if (SDValue Combined = visitORLike(N0, N1, N))
3663 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3664 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3665 if (BSwap.getNode())
3667 BSwap = MatchBSwapHWordLow(N, N0, N1);
3668 if (BSwap.getNode())
3672 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3674 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3675 // iff (c1 & c2) == 0.
3676 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3677 isa<ConstantSDNode>(N0.getOperand(1))) {
3678 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3679 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3680 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3683 ISD::AND, SDLoc(N), VT,
3684 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3688 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3689 if (N0.getOpcode() == N1.getOpcode()) {
3690 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3691 if (Tmp.getNode()) return Tmp;
3694 // See if this is some rotate idiom.
3695 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3696 return SDValue(Rot, 0);
3698 // Simplify the operands using demanded-bits information.
3699 if (!VT.isVector() &&
3700 SimplifyDemandedBits(SDValue(N, 0)))
3701 return SDValue(N, 0);
3706 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3707 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3708 if (Op.getOpcode() == ISD::AND) {
3709 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3710 Mask = Op.getOperand(1);
3711 Op = Op.getOperand(0);
3717 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3725 // Return true if we can prove that, whenever Neg and Pos are both in the
3726 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3727 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3729 // (or (shift1 X, Neg), (shift2 X, Pos))
3731 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3732 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3733 // to consider shift amounts with defined behavior.
3734 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3735 // If OpSize is a power of 2 then:
3737 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3738 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3740 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3741 // for the stronger condition:
3743 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3745 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3746 // we can just replace Neg with Neg' for the rest of the function.
3748 // In other cases we check for the even stronger condition:
3750 // Neg == OpSize - Pos [B]
3752 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3753 // behavior if Pos == 0 (and consequently Neg == OpSize).
3755 // We could actually use [A] whenever OpSize is a power of 2, but the
3756 // only extra cases that it would match are those uninteresting ones
3757 // where Neg and Pos are never in range at the same time. E.g. for
3758 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3759 // as well as (sub 32, Pos), but:
3761 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3763 // always invokes undefined behavior for 32-bit X.
3765 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3766 unsigned MaskLoBits = 0;
3767 if (Neg.getOpcode() == ISD::AND &&
3768 isPowerOf2_64(OpSize) &&
3769 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3770 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3771 Neg = Neg.getOperand(0);
3772 MaskLoBits = Log2_64(OpSize);
3775 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3776 if (Neg.getOpcode() != ISD::SUB)
3778 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3781 SDValue NegOp1 = Neg.getOperand(1);
3783 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3784 // Pos'. The truncation is redundant for the purpose of the equality.
3786 Pos.getOpcode() == ISD::AND &&
3787 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3788 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3789 Pos = Pos.getOperand(0);
3791 // The condition we need is now:
3793 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3795 // If NegOp1 == Pos then we need:
3797 // OpSize & Mask == NegC & Mask
3799 // (because "x & Mask" is a truncation and distributes through subtraction).
3802 Width = NegC->getAPIntValue();
3803 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3804 // Then the condition we want to prove becomes:
3806 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3808 // which, again because "x & Mask" is a truncation, becomes:
3810 // NegC & Mask == (OpSize - PosC) & Mask
3811 // OpSize & Mask == (NegC + PosC) & Mask
3812 else if (Pos.getOpcode() == ISD::ADD &&
3813 Pos.getOperand(0) == NegOp1 &&
3814 Pos.getOperand(1).getOpcode() == ISD::Constant)
3815 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3816 NegC->getAPIntValue());
3820 // Now we just need to check that OpSize & Mask == Width & Mask.
3822 // Opsize & Mask is 0 since Mask is Opsize - 1.
3823 return Width.getLoBits(MaskLoBits) == 0;
3824 return Width == OpSize;
3827 // A subroutine of MatchRotate used once we have found an OR of two opposite
3828 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3829 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3830 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3831 // Neg with outer conversions stripped away.
3832 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3833 SDValue Neg, SDValue InnerPos,
3834 SDValue InnerNeg, unsigned PosOpcode,
3835 unsigned NegOpcode, SDLoc DL) {
3836 // fold (or (shl x, (*ext y)),
3837 // (srl x, (*ext (sub 32, y)))) ->
3838 // (rotl x, y) or (rotr x, (sub 32, y))
3840 // fold (or (shl x, (*ext (sub 32, y))),
3841 // (srl x, (*ext y))) ->
3842 // (rotr x, y) or (rotl x, (sub 32, y))
3843 EVT VT = Shifted.getValueType();
3844 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3845 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3846 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3847 HasPos ? Pos : Neg).getNode();
3853 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3854 // idioms for rotate, and if the target supports rotation instructions, generate
3856 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3857 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3858 EVT VT = LHS.getValueType();
3859 if (!TLI.isTypeLegal(VT)) return nullptr;
3861 // The target must have at least one rotate flavor.
3862 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3863 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3864 if (!HasROTL && !HasROTR) return nullptr;
3866 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3867 SDValue LHSShift; // The shift.
3868 SDValue LHSMask; // AND value if any.
3869 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3870 return nullptr; // Not part of a rotate.
3872 SDValue RHSShift; // The shift.
3873 SDValue RHSMask; // AND value if any.
3874 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3875 return nullptr; // Not part of a rotate.
3877 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3878 return nullptr; // Not shifting the same value.
3880 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3881 return nullptr; // Shifts must disagree.
3883 // Canonicalize shl to left side in a shl/srl pair.
3884 if (RHSShift.getOpcode() == ISD::SHL) {
3885 std::swap(LHS, RHS);
3886 std::swap(LHSShift, RHSShift);
3887 std::swap(LHSMask , RHSMask );
3890 unsigned OpSizeInBits = VT.getSizeInBits();
3891 SDValue LHSShiftArg = LHSShift.getOperand(0);
3892 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3893 SDValue RHSShiftArg = RHSShift.getOperand(0);
3894 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3896 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3897 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3898 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3899 RHSShiftAmt.getOpcode() == ISD::Constant) {
3900 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3901 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3902 if ((LShVal + RShVal) != OpSizeInBits)
3905 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3906 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3908 // If there is an AND of either shifted operand, apply it to the result.
3909 if (LHSMask.getNode() || RHSMask.getNode()) {
3910 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3912 if (LHSMask.getNode()) {
3913 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3914 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3916 if (RHSMask.getNode()) {
3917 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3918 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3921 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3924 return Rot.getNode();
3927 // If there is a mask here, and we have a variable shift, we can't be sure
3928 // that we're masking out the right stuff.
3929 if (LHSMask.getNode() || RHSMask.getNode())
3932 // If the shift amount is sign/zext/any-extended just peel it off.
3933 SDValue LExtOp0 = LHSShiftAmt;
3934 SDValue RExtOp0 = RHSShiftAmt;
3935 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3936 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3937 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3938 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3939 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3940 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3941 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3942 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3943 LExtOp0 = LHSShiftAmt.getOperand(0);
3944 RExtOp0 = RHSShiftAmt.getOperand(0);
3947 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3948 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3952 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3953 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3960 SDValue DAGCombiner::visitXOR(SDNode *N) {
3961 SDValue N0 = N->getOperand(0);
3962 SDValue N1 = N->getOperand(1);
3963 EVT VT = N0.getValueType();
3966 if (VT.isVector()) {
3967 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3970 // fold (xor x, 0) -> x, vector edition
3971 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3973 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3977 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3978 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3979 return DAG.getConstant(0, SDLoc(N), VT);
3980 // fold (xor x, undef) -> undef
3981 if (N0.getOpcode() == ISD::UNDEF)
3983 if (N1.getOpcode() == ISD::UNDEF)
3985 // fold (xor c1, c2) -> c1^c2
3986 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3987 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3989 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3990 // canonicalize constant to RHS
3991 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3992 !isConstantIntBuildVectorOrConstantInt(N1))
3993 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3994 // fold (xor x, 0) -> x
3995 if (isNullConstant(N1))
3998 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4001 // fold !(x cc y) -> (x !cc y)
4002 SDValue LHS, RHS, CC;
4003 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4004 bool isInt = LHS.getValueType().isInteger();
4005 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4008 if (!LegalOperations ||
4009 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4010 switch (N0.getOpcode()) {
4012 llvm_unreachable("Unhandled SetCC Equivalent!");
4014 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4015 case ISD::SELECT_CC:
4016 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4017 N0.getOperand(3), NotCC);
4022 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4023 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4024 N0.getNode()->hasOneUse() &&
4025 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4026 SDValue V = N0.getOperand(0);
4028 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4029 DAG.getConstant(1, DL, V.getValueType()));
4030 AddToWorklist(V.getNode());
4031 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4034 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4035 if (isOneConstant(N1) && VT == MVT::i1 &&
4036 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4037 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4038 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4039 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4040 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4041 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4042 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4043 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4046 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4047 if (isAllOnesConstant(N1) &&
4048 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4049 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4050 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4051 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4052 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4053 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4054 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4055 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4058 // fold (xor (and x, y), y) -> (and (not x), y)
4059 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4060 N0->getOperand(1) == N1) {
4061 SDValue X = N0->getOperand(0);
4062 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4063 AddToWorklist(NotX.getNode());
4064 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4066 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4067 if (N1C && N0.getOpcode() == ISD::XOR) {
4068 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4070 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4071 DAG.getConstant(N1C->getAPIntValue() ^
4072 N00C->getAPIntValue(), DL, VT));
4074 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4076 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4077 DAG.getConstant(N1C->getAPIntValue() ^
4078 N01C->getAPIntValue(), DL, VT));
4081 // fold (xor x, x) -> 0
4083 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4085 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4086 // Here is a concrete example of this equivalence:
4088 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
4089 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4093 // i16 ~1 == 0b1111111111111110
4094 // i16 rol(~1, 14) == 0b1011111111111111
4096 // Some additional tips to help conceptualize this transform:
4097 // - Try to see the operation as placing a single zero in a value of all ones.
4098 // - There exists no value for x which would allow the result to contain zero.
4099 // - Values of x larger than the bitwidth are undefined and do not require a
4100 // consistent result.
4101 // - Pushing the zero left requires shifting one bits in from the right.
4102 // A rotate left of ~1 is a nice way of achieving the desired result.
4103 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4104 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4106 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4110 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4111 if (N0.getOpcode() == N1.getOpcode()) {
4112 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4113 if (Tmp.getNode()) return Tmp;
4116 // Simplify the expression using non-local knowledge.
4117 if (!VT.isVector() &&
4118 SimplifyDemandedBits(SDValue(N, 0)))
4119 return SDValue(N, 0);
4124 /// Handle transforms common to the three shifts, when the shift amount is a
4126 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4127 SDNode *LHS = N->getOperand(0).getNode();
4128 if (!LHS->hasOneUse()) return SDValue();
4130 // We want to pull some binops through shifts, so that we have (and (shift))
4131 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4132 // thing happens with address calculations, so it's important to canonicalize
4134 bool HighBitSet = false; // Can we transform this if the high bit is set?
4136 switch (LHS->getOpcode()) {
4137 default: return SDValue();
4140 HighBitSet = false; // We can only transform sra if the high bit is clear.
4143 HighBitSet = true; // We can only transform sra if the high bit is set.
4146 if (N->getOpcode() != ISD::SHL)
4147 return SDValue(); // only shl(add) not sr[al](add).
4148 HighBitSet = false; // We can only transform sra if the high bit is clear.
4152 // We require the RHS of the binop to be a constant and not opaque as well.
4153 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4154 if (!BinOpCst) return SDValue();
4156 // FIXME: disable this unless the input to the binop is a shift by a constant.
4157 // If it is not a shift, it pessimizes some common cases like:
4159 // void foo(int *X, int i) { X[i & 1235] = 1; }
4160 // int bar(int *X, int i) { return X[i & 255]; }
4161 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4162 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4163 BinOpLHSVal->getOpcode() != ISD::SRA &&
4164 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4165 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4168 EVT VT = N->getValueType(0);
4170 // If this is a signed shift right, and the high bit is modified by the
4171 // logical operation, do not perform the transformation. The highBitSet
4172 // boolean indicates the value of the high bit of the constant which would
4173 // cause it to be modified for this operation.
4174 if (N->getOpcode() == ISD::SRA) {
4175 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4176 if (BinOpRHSSignSet != HighBitSet)
4180 if (!TLI.isDesirableToCommuteWithShift(LHS))
4183 // Fold the constants, shifting the binop RHS by the shift amount.
4184 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4186 LHS->getOperand(1), N->getOperand(1));
4187 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4189 // Create the new shift.
4190 SDValue NewShift = DAG.getNode(N->getOpcode(),
4191 SDLoc(LHS->getOperand(0)),
4192 VT, LHS->getOperand(0), N->getOperand(1));
4194 // Create the new binop.
4195 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4198 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4199 assert(N->getOpcode() == ISD::TRUNCATE);
4200 assert(N->getOperand(0).getOpcode() == ISD::AND);
4202 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4203 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4204 SDValue N01 = N->getOperand(0).getOperand(1);
4206 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4207 if (!N01C->isOpaque()) {
4208 EVT TruncVT = N->getValueType(0);
4209 SDValue N00 = N->getOperand(0).getOperand(0);
4210 APInt TruncC = N01C->getAPIntValue();
4211 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4214 return DAG.getNode(ISD::AND, DL, TruncVT,
4215 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4216 DAG.getConstant(TruncC, DL, TruncVT));
4224 SDValue DAGCombiner::visitRotate(SDNode *N) {
4225 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4226 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4227 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4228 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4229 if (NewOp1.getNode())
4230 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4231 N->getOperand(0), NewOp1);
4236 SDValue DAGCombiner::visitSHL(SDNode *N) {
4237 SDValue N0 = N->getOperand(0);
4238 SDValue N1 = N->getOperand(1);
4239 EVT VT = N0.getValueType();
4240 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4243 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4244 if (VT.isVector()) {
4245 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4248 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4249 // If setcc produces all-one true value then:
4250 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4251 if (N1CV && N1CV->isConstant()) {
4252 if (N0.getOpcode() == ISD::AND) {
4253 SDValue N00 = N0->getOperand(0);
4254 SDValue N01 = N0->getOperand(1);
4255 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4257 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4258 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4259 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4260 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4262 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4265 N1C = isConstOrConstSplat(N1);
4270 // fold (shl c1, c2) -> c1<<c2
4271 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4272 if (N0C && N1C && !N1C->isOpaque())
4273 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4274 // fold (shl 0, x) -> 0
4275 if (isNullConstant(N0))
4277 // fold (shl x, c >= size(x)) -> undef
4278 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4279 return DAG.getUNDEF(VT);
4280 // fold (shl x, 0) -> x
4281 if (N1C && N1C->isNullValue())
4283 // fold (shl undef, x) -> 0
4284 if (N0.getOpcode() == ISD::UNDEF)
4285 return DAG.getConstant(0, SDLoc(N), VT);
4286 // if (shl x, c) is known to be zero, return 0
4287 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4288 APInt::getAllOnesValue(OpSizeInBits)))
4289 return DAG.getConstant(0, SDLoc(N), VT);
4290 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4291 if (N1.getOpcode() == ISD::TRUNCATE &&
4292 N1.getOperand(0).getOpcode() == ISD::AND) {
4293 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4294 if (NewOp1.getNode())
4295 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4298 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4299 return SDValue(N, 0);
4301 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4302 if (N1C && N0.getOpcode() == ISD::SHL) {
4303 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4304 uint64_t c1 = N0C1->getZExtValue();
4305 uint64_t c2 = N1C->getZExtValue();
4307 if (c1 + c2 >= OpSizeInBits)
4308 return DAG.getConstant(0, DL, VT);
4309 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4310 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4314 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4315 // For this to be valid, the second form must not preserve any of the bits
4316 // that are shifted out by the inner shift in the first form. This means
4317 // the outer shift size must be >= the number of bits added by the ext.
4318 // As a corollary, we don't care what kind of ext it is.
4319 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4320 N0.getOpcode() == ISD::ANY_EXTEND ||
4321 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4322 N0.getOperand(0).getOpcode() == ISD::SHL) {
4323 SDValue N0Op0 = N0.getOperand(0);
4324 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4325 uint64_t c1 = N0Op0C1->getZExtValue();
4326 uint64_t c2 = N1C->getZExtValue();
4327 EVT InnerShiftVT = N0Op0.getValueType();
4328 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4329 if (c2 >= OpSizeInBits - InnerShiftSize) {
4331 if (c1 + c2 >= OpSizeInBits)
4332 return DAG.getConstant(0, DL, VT);
4333 return DAG.getNode(ISD::SHL, DL, VT,
4334 DAG.getNode(N0.getOpcode(), DL, VT,
4335 N0Op0->getOperand(0)),
4336 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4341 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4342 // Only fold this if the inner zext has no other uses to avoid increasing
4343 // the total number of instructions.
4344 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4345 N0.getOperand(0).getOpcode() == ISD::SRL) {
4346 SDValue N0Op0 = N0.getOperand(0);
4347 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4348 uint64_t c1 = N0Op0C1->getZExtValue();
4349 if (c1 < VT.getScalarSizeInBits()) {
4350 uint64_t c2 = N1C->getZExtValue();
4352 SDValue NewOp0 = N0.getOperand(0);
4353 EVT CountVT = NewOp0.getOperand(1).getValueType();
4355 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4357 DAG.getConstant(c2, DL, CountVT));
4358 AddToWorklist(NewSHL.getNode());
4359 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4365 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4366 // (and (srl x, (sub c1, c2), MASK)
4367 // Only fold this if the inner shift has no other uses -- if it does, folding
4368 // this will increase the total number of instructions.
4369 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4370 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4371 uint64_t c1 = N0C1->getZExtValue();
4372 if (c1 < OpSizeInBits) {
4373 uint64_t c2 = N1C->getZExtValue();
4374 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4377 Mask = Mask.shl(c2 - c1);
4379 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4380 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4382 Mask = Mask.lshr(c1 - c2);
4384 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4385 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4388 return DAG.getNode(ISD::AND, DL, VT, Shift,
4389 DAG.getConstant(Mask, DL, VT));
4393 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4394 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4395 unsigned BitSize = VT.getScalarSizeInBits();
4397 SDValue HiBitsMask =
4398 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4399 BitSize - N1C->getZExtValue()),
4401 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4405 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4406 // Variant of version done on multiply, except mul by a power of 2 is turned
4409 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4410 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4411 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4412 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4413 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4414 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4417 if (N1C && !N1C->isOpaque()) {
4418 SDValue NewSHL = visitShiftByConstant(N, N1C);
4419 if (NewSHL.getNode())
4426 SDValue DAGCombiner::visitSRA(SDNode *N) {
4427 SDValue N0 = N->getOperand(0);
4428 SDValue N1 = N->getOperand(1);
4429 EVT VT = N0.getValueType();
4430 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4433 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4434 if (VT.isVector()) {
4435 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4438 N1C = isConstOrConstSplat(N1);
4441 // fold (sra c1, c2) -> (sra c1, c2)
4442 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4443 if (N0C && N1C && !N1C->isOpaque())
4444 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4445 // fold (sra 0, x) -> 0
4446 if (isNullConstant(N0))
4448 // fold (sra -1, x) -> -1
4449 if (isAllOnesConstant(N0))
4451 // fold (sra x, (setge c, size(x))) -> undef
4452 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4453 return DAG.getUNDEF(VT);
4454 // fold (sra x, 0) -> x
4455 if (N1C && N1C->isNullValue())
4457 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4459 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4460 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4461 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4463 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4464 ExtVT, VT.getVectorNumElements());
4465 if ((!LegalOperations ||
4466 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4467 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4468 N0.getOperand(0), DAG.getValueType(ExtVT));
4471 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4472 if (N1C && N0.getOpcode() == ISD::SRA) {
4473 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4474 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4475 if (Sum >= OpSizeInBits)
4476 Sum = OpSizeInBits - 1;
4478 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4479 DAG.getConstant(Sum, DL, N1.getValueType()));
4483 // fold (sra (shl X, m), (sub result_size, n))
4484 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4485 // result_size - n != m.
4486 // If truncate is free for the target sext(shl) is likely to result in better
4488 if (N0.getOpcode() == ISD::SHL && N1C) {
4489 // Get the two constanst of the shifts, CN0 = m, CN = n.
4490 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4492 LLVMContext &Ctx = *DAG.getContext();
4493 // Determine what the truncate's result bitsize and type would be.
4494 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4497 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4499 // Determine the residual right-shift amount.
4500 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4502 // If the shift is not a no-op (in which case this should be just a sign
4503 // extend already), the truncated to type is legal, sign_extend is legal
4504 // on that type, and the truncate to that type is both legal and free,
4505 // perform the transform.
4506 if ((ShiftAmt > 0) &&
4507 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4508 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4509 TLI.isTruncateFree(VT, TruncVT)) {
4512 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4513 getShiftAmountTy(N0.getOperand(0).getValueType()));
4514 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4515 N0.getOperand(0), Amt);
4516 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4518 return DAG.getNode(ISD::SIGN_EXTEND, DL,
4519 N->getValueType(0), Trunc);
4524 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4525 if (N1.getOpcode() == ISD::TRUNCATE &&
4526 N1.getOperand(0).getOpcode() == ISD::AND) {
4527 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4528 if (NewOp1.getNode())
4529 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4532 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4533 // if c1 is equal to the number of bits the trunc removes
4534 if (N0.getOpcode() == ISD::TRUNCATE &&
4535 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4536 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4537 N0.getOperand(0).hasOneUse() &&
4538 N0.getOperand(0).getOperand(1).hasOneUse() &&
4540 SDValue N0Op0 = N0.getOperand(0);
4541 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4542 unsigned LargeShiftVal = LargeShift->getZExtValue();
4543 EVT LargeVT = N0Op0.getValueType();
4545 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4548 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4549 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4550 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4551 N0Op0.getOperand(0), Amt);
4552 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4557 // Simplify, based on bits shifted out of the LHS.
4558 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4559 return SDValue(N, 0);
4562 // If the sign bit is known to be zero, switch this to a SRL.
4563 if (DAG.SignBitIsZero(N0))
4564 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4566 if (N1C && !N1C->isOpaque()) {
4567 SDValue NewSRA = visitShiftByConstant(N, N1C);
4568 if (NewSRA.getNode())
4575 SDValue DAGCombiner::visitSRL(SDNode *N) {
4576 SDValue N0 = N->getOperand(0);
4577 SDValue N1 = N->getOperand(1);
4578 EVT VT = N0.getValueType();
4579 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4582 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4583 if (VT.isVector()) {
4584 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4587 N1C = isConstOrConstSplat(N1);
4590 // fold (srl c1, c2) -> c1 >>u c2
4591 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4592 if (N0C && N1C && !N1C->isOpaque())
4593 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4594 // fold (srl 0, x) -> 0
4595 if (isNullConstant(N0))
4597 // fold (srl x, c >= size(x)) -> undef
4598 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4599 return DAG.getUNDEF(VT);
4600 // fold (srl x, 0) -> x
4601 if (N1C && N1C->isNullValue())
4603 // if (srl x, c) is known to be zero, return 0
4604 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4605 APInt::getAllOnesValue(OpSizeInBits)))
4606 return DAG.getConstant(0, SDLoc(N), VT);
4608 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4609 if (N1C && N0.getOpcode() == ISD::SRL) {
4610 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4611 uint64_t c1 = N01C->getZExtValue();
4612 uint64_t c2 = N1C->getZExtValue();
4614 if (c1 + c2 >= OpSizeInBits)
4615 return DAG.getConstant(0, DL, VT);
4616 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4617 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4621 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4622 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4623 N0.getOperand(0).getOpcode() == ISD::SRL &&
4624 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4626 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4627 uint64_t c2 = N1C->getZExtValue();
4628 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4629 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4630 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4631 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4632 if (c1 + OpSizeInBits == InnerShiftSize) {
4634 if (c1 + c2 >= InnerShiftSize)
4635 return DAG.getConstant(0, DL, VT);
4636 return DAG.getNode(ISD::TRUNCATE, DL, VT,
4637 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4638 N0.getOperand(0)->getOperand(0),
4639 DAG.getConstant(c1 + c2, DL,
4644 // fold (srl (shl x, c), c) -> (and x, cst2)
4645 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4646 unsigned BitSize = N0.getScalarValueSizeInBits();
4647 if (BitSize <= 64) {
4648 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4650 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4651 DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4655 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4656 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4657 // Shifting in all undef bits?
4658 EVT SmallVT = N0.getOperand(0).getValueType();
4659 unsigned BitSize = SmallVT.getScalarSizeInBits();
4660 if (N1C->getZExtValue() >= BitSize)
4661 return DAG.getUNDEF(VT);
4663 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4664 uint64_t ShiftAmt = N1C->getZExtValue();
4666 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4668 DAG.getConstant(ShiftAmt, DL0,
4669 getShiftAmountTy(SmallVT)));
4670 AddToWorklist(SmallShift.getNode());
4671 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4673 return DAG.getNode(ISD::AND, DL, VT,
4674 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4675 DAG.getConstant(Mask, DL, VT));
4679 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4680 // bit, which is unmodified by sra.
4681 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4682 if (N0.getOpcode() == ISD::SRA)
4683 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4686 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4687 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4688 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4689 APInt KnownZero, KnownOne;
4690 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4692 // If any of the input bits are KnownOne, then the input couldn't be all
4693 // zeros, thus the result of the srl will always be zero.
4694 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4696 // If all of the bits input the to ctlz node are known to be zero, then
4697 // the result of the ctlz is "32" and the result of the shift is one.
4698 APInt UnknownBits = ~KnownZero;
4699 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4701 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4702 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4703 // Okay, we know that only that the single bit specified by UnknownBits
4704 // could be set on input to the CTLZ node. If this bit is set, the SRL
4705 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4706 // to an SRL/XOR pair, which is likely to simplify more.
4707 unsigned ShAmt = UnknownBits.countTrailingZeros();
4708 SDValue Op = N0.getOperand(0);
4712 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4713 DAG.getConstant(ShAmt, DL,
4714 getShiftAmountTy(Op.getValueType())));
4715 AddToWorklist(Op.getNode());
4719 return DAG.getNode(ISD::XOR, DL, VT,
4720 Op, DAG.getConstant(1, DL, VT));
4724 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4725 if (N1.getOpcode() == ISD::TRUNCATE &&
4726 N1.getOperand(0).getOpcode() == ISD::AND) {
4727 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4728 if (NewOp1.getNode())
4729 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4732 // fold operands of srl based on knowledge that the low bits are not
4734 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4735 return SDValue(N, 0);
4737 if (N1C && !N1C->isOpaque()) {
4738 SDValue NewSRL = visitShiftByConstant(N, N1C);
4739 if (NewSRL.getNode())
4743 // Attempt to convert a srl of a load into a narrower zero-extending load.
4744 SDValue NarrowLoad = ReduceLoadWidth(N);
4745 if (NarrowLoad.getNode())
4748 // Here is a common situation. We want to optimize:
4751 // %b = and i32 %a, 2
4752 // %c = srl i32 %b, 1
4753 // brcond i32 %c ...
4759 // %c = setcc eq %b, 0
4762 // However when after the source operand of SRL is optimized into AND, the SRL
4763 // itself may not be optimized further. Look for it and add the BRCOND into
4765 if (N->hasOneUse()) {
4766 SDNode *Use = *N->use_begin();
4767 if (Use->getOpcode() == ISD::BRCOND)
4769 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4770 // Also look pass the truncate.
4771 Use = *Use->use_begin();
4772 if (Use->getOpcode() == ISD::BRCOND)
4780 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4781 SDValue N0 = N->getOperand(0);
4782 EVT VT = N->getValueType(0);
4784 // fold (bswap c1) -> c2
4785 if (isConstantIntBuildVectorOrConstantInt(N0))
4786 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4787 // fold (bswap (bswap x)) -> x
4788 if (N0.getOpcode() == ISD::BSWAP)
4789 return N0->getOperand(0);
4793 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4794 SDValue N0 = N->getOperand(0);
4795 EVT VT = N->getValueType(0);
4797 // fold (ctlz c1) -> c2
4798 if (isConstantIntBuildVectorOrConstantInt(N0))
4799 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4803 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4804 SDValue N0 = N->getOperand(0);
4805 EVT VT = N->getValueType(0);
4807 // fold (ctlz_zero_undef c1) -> c2
4808 if (isConstantIntBuildVectorOrConstantInt(N0))
4809 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4813 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4814 SDValue N0 = N->getOperand(0);
4815 EVT VT = N->getValueType(0);
4817 // fold (cttz c1) -> c2
4818 if (isConstantIntBuildVectorOrConstantInt(N0))
4819 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4823 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4824 SDValue N0 = N->getOperand(0);
4825 EVT VT = N->getValueType(0);
4827 // fold (cttz_zero_undef c1) -> c2
4828 if (isConstantIntBuildVectorOrConstantInt(N0))
4829 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4833 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4834 SDValue N0 = N->getOperand(0);
4835 EVT VT = N->getValueType(0);
4837 // fold (ctpop c1) -> c2
4838 if (isConstantIntBuildVectorOrConstantInt(N0))
4839 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4844 /// \brief Generate Min/Max node
4845 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4846 SDValue True, SDValue False,
4847 ISD::CondCode CC, const TargetLowering &TLI,
4848 SelectionDAG &DAG) {
4849 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4859 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4860 if (TLI.isOperationLegal(Opcode, VT))
4861 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4870 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4871 if (TLI.isOperationLegal(Opcode, VT))
4872 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4880 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4881 SDValue N0 = N->getOperand(0);
4882 SDValue N1 = N->getOperand(1);
4883 SDValue N2 = N->getOperand(2);
4884 EVT VT = N->getValueType(0);
4885 EVT VT0 = N0.getValueType();
4887 // fold (select C, X, X) -> X
4890 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4891 // fold (select true, X, Y) -> X
4892 // fold (select false, X, Y) -> Y
4893 return !N0C->isNullValue() ? N1 : N2;
4895 // fold (select C, 1, X) -> (or C, X)
4896 if (VT == MVT::i1 && isOneConstant(N1))
4897 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4898 // fold (select C, 0, 1) -> (xor C, 1)
4899 // We can't do this reliably if integer based booleans have different contents
4900 // to floating point based booleans. This is because we can't tell whether we
4901 // have an integer-based boolean or a floating-point-based boolean unless we
4902 // can find the SETCC that produced it and inspect its operands. This is
4903 // fairly easy if C is the SETCC node, but it can potentially be
4904 // undiscoverable (or not reasonably discoverable). For example, it could be
4905 // in another basic block or it could require searching a complicated
4907 if (VT.isInteger() &&
4908 (VT0 == MVT::i1 || (VT0.isInteger() &&
4909 TLI.getBooleanContents(false, false) ==
4910 TLI.getBooleanContents(false, true) &&
4911 TLI.getBooleanContents(false, false) ==
4912 TargetLowering::ZeroOrOneBooleanContent)) &&
4913 isNullConstant(N1) && isOneConstant(N2)) {
4917 return DAG.getNode(ISD::XOR, DL, VT0,
4918 N0, DAG.getConstant(1, DL, VT0));
4921 XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4922 N0, DAG.getConstant(1, DL0, VT0));
4923 AddToWorklist(XORNode.getNode());
4925 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4926 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4928 // fold (select C, 0, X) -> (and (not C), X)
4929 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4930 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4931 AddToWorklist(NOTNode.getNode());
4932 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4934 // fold (select C, X, 1) -> (or (not C), X)
4935 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
4936 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4937 AddToWorklist(NOTNode.getNode());
4938 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4940 // fold (select C, X, 0) -> (and C, X)
4941 if (VT == MVT::i1 && isNullConstant(N2))
4942 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4943 // fold (select X, X, Y) -> (or X, Y)
4944 // fold (select X, 1, Y) -> (or X, Y)
4945 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
4946 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4947 // fold (select X, Y, X) -> (and X, Y)
4948 // fold (select X, Y, 0) -> (and X, Y)
4949 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
4950 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4952 // If we can fold this based on the true/false value, do so.
4953 if (SimplifySelectOps(N, N1, N2))
4954 return SDValue(N, 0); // Don't revisit N.
4956 // fold selects based on a setcc into other things, such as min/max/abs
4957 if (N0.getOpcode() == ISD::SETCC) {
4958 // select x, y (fcmp lt x, y) -> fminnum x, y
4959 // select x, y (fcmp gt x, y) -> fmaxnum x, y
4961 // This is OK if we don't care about what happens if either operand is a
4965 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4966 // no signed zeros as well as no nans.
4967 const TargetOptions &Options = DAG.getTarget().Options;
4968 if (Options.UnsafeFPMath &&
4969 VT.isFloatingPoint() && N0.hasOneUse() &&
4970 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4971 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4974 combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4975 N1, N2, CC, TLI, DAG);
4980 if ((!LegalOperations &&
4981 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4982 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4983 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4984 N0.getOperand(0), N0.getOperand(1),
4985 N1, N2, N0.getOperand(2));
4986 return SimplifySelect(SDLoc(N), N0, N1, N2);
4989 if (VT0 == MVT::i1) {
4990 if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4991 // select (and Cond0, Cond1), X, Y
4992 // -> select Cond0, (select Cond1, X, Y), Y
4993 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4994 SDValue Cond0 = N0->getOperand(0);
4995 SDValue Cond1 = N0->getOperand(1);
4996 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4997 N1.getValueType(), Cond1, N1, N2);
4998 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5001 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5002 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5003 SDValue Cond0 = N0->getOperand(0);
5004 SDValue Cond1 = N0->getOperand(1);
5005 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5006 N1.getValueType(), Cond1, N1, N2);
5007 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5012 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5013 if (N1->getOpcode() == ISD::SELECT) {
5014 SDValue N1_0 = N1->getOperand(0);
5015 SDValue N1_1 = N1->getOperand(1);
5016 SDValue N1_2 = N1->getOperand(2);
5017 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5018 // Create the actual and node if we can generate good code for it.
5019 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
5020 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5022 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5025 // Otherwise see if we can optimize the "and" to a better pattern.
5026 if (SDValue Combined = visitANDLike(N0, N1_0, N))
5027 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5031 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5032 if (N2->getOpcode() == ISD::SELECT) {
5033 SDValue N2_0 = N2->getOperand(0);
5034 SDValue N2_1 = N2->getOperand(1);
5035 SDValue N2_2 = N2->getOperand(2);
5036 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5037 // Create the actual or node if we can generate good code for it.
5038 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
5039 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5041 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5044 // Otherwise see if we can optimize to a better pattern.
5045 if (SDValue Combined = visitORLike(N0, N2_0, N))
5046 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5056 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5059 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5061 // Split the inputs.
5062 SDValue Lo, Hi, LL, LH, RL, RH;
5063 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5064 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5066 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5067 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5069 return std::make_pair(Lo, Hi);
5072 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5073 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5074 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5076 SDValue Cond = N->getOperand(0);
5077 SDValue LHS = N->getOperand(1);
5078 SDValue RHS = N->getOperand(2);
5079 EVT VT = N->getValueType(0);
5080 int NumElems = VT.getVectorNumElements();
5081 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5082 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5083 Cond.getOpcode() == ISD::BUILD_VECTOR);
5085 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5086 // binary ones here.
5087 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5090 // We're sure we have an even number of elements due to the
5091 // concat_vectors we have as arguments to vselect.
5092 // Skip BV elements until we find one that's not an UNDEF
5093 // After we find an UNDEF element, keep looping until we get to half the
5094 // length of the BV and see if all the non-undef nodes are the same.
5095 ConstantSDNode *BottomHalf = nullptr;
5096 for (int i = 0; i < NumElems / 2; ++i) {
5097 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5100 if (BottomHalf == nullptr)
5101 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5102 else if (Cond->getOperand(i).getNode() != BottomHalf)
5106 // Do the same for the second half of the BuildVector
5107 ConstantSDNode *TopHalf = nullptr;
5108 for (int i = NumElems / 2; i < NumElems; ++i) {
5109 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5112 if (TopHalf == nullptr)
5113 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5114 else if (Cond->getOperand(i).getNode() != TopHalf)
5118 assert(TopHalf && BottomHalf &&
5119 "One half of the selector was all UNDEFs and the other was all the "
5120 "same value. This should have been addressed before this function.");
5122 ISD::CONCAT_VECTORS, dl, VT,
5123 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5124 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5127 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5129 if (Level >= AfterLegalizeTypes)
5132 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5133 SDValue Mask = MSC->getMask();
5134 SDValue Data = MSC->getValue();
5137 // If the MSCATTER data type requires splitting and the mask is provided by a
5138 // SETCC, then split both nodes and its operands before legalization. This
5139 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5140 // and enables future optimizations (e.g. min/max pattern matching on X86).
5141 if (Mask.getOpcode() != ISD::SETCC)
5144 // Check if any splitting is required.
5145 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5146 TargetLowering::TypeSplitVector)
5148 SDValue MaskLo, MaskHi, Lo, Hi;
5149 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5152 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5154 SDValue Chain = MSC->getChain();
5156 EVT MemoryVT = MSC->getMemoryVT();
5157 unsigned Alignment = MSC->getOriginalAlignment();
5159 EVT LoMemVT, HiMemVT;
5160 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5162 SDValue DataLo, DataHi;
5163 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5165 SDValue BasePtr = MSC->getBasePtr();
5166 SDValue IndexLo, IndexHi;
5167 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5169 MachineMemOperand *MMO = DAG.getMachineFunction().
5170 getMachineMemOperand(MSC->getPointerInfo(),
5171 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5172 Alignment, MSC->getAAInfo(), MSC->getRanges());
5174 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5175 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5178 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5179 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5182 AddToWorklist(Lo.getNode());
5183 AddToWorklist(Hi.getNode());
5185 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5188 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5190 if (Level >= AfterLegalizeTypes)
5193 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5194 SDValue Mask = MST->getMask();
5195 SDValue Data = MST->getValue();
5198 // If the MSTORE data type requires splitting and the mask is provided by a
5199 // SETCC, then split both nodes and its operands before legalization. This
5200 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5201 // and enables future optimizations (e.g. min/max pattern matching on X86).
5202 if (Mask.getOpcode() == ISD::SETCC) {
5204 // Check if any splitting is required.
5205 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5206 TargetLowering::TypeSplitVector)
5209 SDValue MaskLo, MaskHi, Lo, Hi;
5210 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5213 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5215 SDValue Chain = MST->getChain();
5216 SDValue Ptr = MST->getBasePtr();
5218 EVT MemoryVT = MST->getMemoryVT();
5219 unsigned Alignment = MST->getOriginalAlignment();
5221 // if Alignment is equal to the vector size,
5222 // take the half of it for the second part
5223 unsigned SecondHalfAlignment =
5224 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5225 Alignment/2 : Alignment;
5227 EVT LoMemVT, HiMemVT;
5228 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5230 SDValue DataLo, DataHi;
5231 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5233 MachineMemOperand *MMO = DAG.getMachineFunction().
5234 getMachineMemOperand(MST->getPointerInfo(),
5235 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5236 Alignment, MST->getAAInfo(), MST->getRanges());
5238 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5239 MST->isTruncatingStore());
5241 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5242 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5243 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5245 MMO = DAG.getMachineFunction().
5246 getMachineMemOperand(MST->getPointerInfo(),
5247 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5248 SecondHalfAlignment, MST->getAAInfo(),
5251 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5252 MST->isTruncatingStore());
5254 AddToWorklist(Lo.getNode());
5255 AddToWorklist(Hi.getNode());
5257 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5262 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5264 if (Level >= AfterLegalizeTypes)
5267 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5268 SDValue Mask = MGT->getMask();
5271 // If the MGATHER result requires splitting and the mask is provided by a
5272 // SETCC, then split both nodes and its operands before legalization. This
5273 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5274 // and enables future optimizations (e.g. min/max pattern matching on X86).
5276 if (Mask.getOpcode() != ISD::SETCC)
5279 EVT VT = N->getValueType(0);
5281 // Check if any splitting is required.
5282 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5283 TargetLowering::TypeSplitVector)
5286 SDValue MaskLo, MaskHi, Lo, Hi;
5287 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5289 SDValue Src0 = MGT->getValue();
5290 SDValue Src0Lo, Src0Hi;
5291 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5294 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5296 SDValue Chain = MGT->getChain();
5297 EVT MemoryVT = MGT->getMemoryVT();
5298 unsigned Alignment = MGT->getOriginalAlignment();
5300 EVT LoMemVT, HiMemVT;
5301 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5303 SDValue BasePtr = MGT->getBasePtr();
5304 SDValue Index = MGT->getIndex();
5305 SDValue IndexLo, IndexHi;
5306 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5308 MachineMemOperand *MMO = DAG.getMachineFunction().
5309 getMachineMemOperand(MGT->getPointerInfo(),
5310 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5311 Alignment, MGT->getAAInfo(), MGT->getRanges());
5313 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5314 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5317 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5318 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5321 AddToWorklist(Lo.getNode());
5322 AddToWorklist(Hi.getNode());
5324 // Build a factor node to remember that this load is independent of the
5326 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5329 // Legalized the chain result - switch anything that used the old chain to
5331 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5333 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5335 SDValue RetOps[] = { GatherRes, Chain };
5336 return DAG.getMergeValues(RetOps, DL);
5339 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5341 if (Level >= AfterLegalizeTypes)
5344 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5345 SDValue Mask = MLD->getMask();
5348 // If the MLOAD result requires splitting and the mask is provided by a
5349 // SETCC, then split both nodes and its operands before legalization. This
5350 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5351 // and enables future optimizations (e.g. min/max pattern matching on X86).
5353 if (Mask.getOpcode() == ISD::SETCC) {
5354 EVT VT = N->getValueType(0);
5356 // Check if any splitting is required.
5357 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5358 TargetLowering::TypeSplitVector)
5361 SDValue MaskLo, MaskHi, Lo, Hi;
5362 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5364 SDValue Src0 = MLD->getSrc0();
5365 SDValue Src0Lo, Src0Hi;
5366 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5369 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5371 SDValue Chain = MLD->getChain();
5372 SDValue Ptr = MLD->getBasePtr();
5373 EVT MemoryVT = MLD->getMemoryVT();
5374 unsigned Alignment = MLD->getOriginalAlignment();
5376 // if Alignment is equal to the vector size,
5377 // take the half of it for the second part
5378 unsigned SecondHalfAlignment =
5379 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5380 Alignment/2 : Alignment;
5382 EVT LoMemVT, HiMemVT;
5383 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5385 MachineMemOperand *MMO = DAG.getMachineFunction().
5386 getMachineMemOperand(MLD->getPointerInfo(),
5387 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5388 Alignment, MLD->getAAInfo(), MLD->getRanges());
5390 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5393 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5394 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5395 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5397 MMO = DAG.getMachineFunction().
5398 getMachineMemOperand(MLD->getPointerInfo(),
5399 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5400 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5402 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5405 AddToWorklist(Lo.getNode());
5406 AddToWorklist(Hi.getNode());
5408 // Build a factor node to remember that this load is independent of the
5410 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5413 // Legalized the chain result - switch anything that used the old chain to
5415 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5417 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5419 SDValue RetOps[] = { LoadRes, Chain };
5420 return DAG.getMergeValues(RetOps, DL);
5425 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5426 SDValue N0 = N->getOperand(0);
5427 SDValue N1 = N->getOperand(1);
5428 SDValue N2 = N->getOperand(2);
5431 // Canonicalize integer abs.
5432 // vselect (setg[te] X, 0), X, -X ->
5433 // vselect (setgt X, -1), X, -X ->
5434 // vselect (setl[te] X, 0), -X, X ->
5435 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5436 if (N0.getOpcode() == ISD::SETCC) {
5437 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5438 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5440 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5442 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5443 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5444 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5445 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5446 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5447 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5448 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5451 EVT VT = LHS.getValueType();
5452 SDValue Shift = DAG.getNode(
5453 ISD::SRA, DL, VT, LHS,
5454 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5455 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5456 AddToWorklist(Shift.getNode());
5457 AddToWorklist(Add.getNode());
5458 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5462 if (SimplifySelectOps(N, N1, N2))
5463 return SDValue(N, 0); // Don't revisit N.
5465 // If the VSELECT result requires splitting and the mask is provided by a
5466 // SETCC, then split both nodes and its operands before legalization. This
5467 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5468 // and enables future optimizations (e.g. min/max pattern matching on X86).
5469 if (N0.getOpcode() == ISD::SETCC) {
5470 EVT VT = N->getValueType(0);
5472 // Check if any splitting is required.
5473 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5474 TargetLowering::TypeSplitVector)
5477 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5478 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5479 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5480 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5482 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5483 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5485 // Add the new VSELECT nodes to the work list in case they need to be split
5487 AddToWorklist(Lo.getNode());
5488 AddToWorklist(Hi.getNode());
5490 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5493 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5494 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5496 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5497 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5500 // The ConvertSelectToConcatVector function is assuming both the above
5501 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5503 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5504 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5505 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5506 SDValue CV = ConvertSelectToConcatVector(N, DAG);
5514 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5515 SDValue N0 = N->getOperand(0);
5516 SDValue N1 = N->getOperand(1);
5517 SDValue N2 = N->getOperand(2);
5518 SDValue N3 = N->getOperand(3);
5519 SDValue N4 = N->getOperand(4);
5520 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5522 // fold select_cc lhs, rhs, x, x, cc -> x
5526 // Determine if the condition we're dealing with is constant
5527 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5528 N0, N1, CC, SDLoc(N), false);
5529 if (SCC.getNode()) {
5530 AddToWorklist(SCC.getNode());
5532 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5533 if (!SCCC->isNullValue())
5534 return N2; // cond always true -> true val
5536 return N3; // cond always false -> false val
5537 } else if (SCC->getOpcode() == ISD::UNDEF) {
5538 // When the condition is UNDEF, just return the first operand. This is
5539 // coherent the DAG creation, no setcc node is created in this case
5541 } else if (SCC.getOpcode() == ISD::SETCC) {
5542 // Fold to a simpler select_cc
5543 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5544 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5549 // If we can fold this based on the true/false value, do so.
5550 if (SimplifySelectOps(N, N2, N3))
5551 return SDValue(N, 0); // Don't revisit N.
5553 // fold select_cc into other things, such as min/max/abs
5554 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5557 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5558 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5559 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5563 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5564 // dag node into a ConstantSDNode or a build_vector of constants.
5565 // This function is called by the DAGCombiner when visiting sext/zext/aext
5566 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5567 // Vector extends are not folded if operations are legal; this is to
5568 // avoid introducing illegal build_vector dag nodes.
5569 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5570 SelectionDAG &DAG, bool LegalTypes,
5571 bool LegalOperations) {
5572 unsigned Opcode = N->getOpcode();
5573 SDValue N0 = N->getOperand(0);
5574 EVT VT = N->getValueType(0);
5576 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5577 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5578 && "Expected EXTEND dag node in input!");
5580 // fold (sext c1) -> c1
5581 // fold (zext c1) -> c1
5582 // fold (aext c1) -> c1
5583 if (isa<ConstantSDNode>(N0))
5584 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5586 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5587 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5588 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5589 EVT SVT = VT.getScalarType();
5590 if (!(VT.isVector() &&
5591 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5592 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5595 // We can fold this node into a build_vector.
5596 unsigned VTBits = SVT.getSizeInBits();
5597 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5598 unsigned ShAmt = VTBits - EVTBits;
5599 SmallVector<SDValue, 8> Elts;
5600 unsigned NumElts = VT.getVectorNumElements();
5603 for (unsigned i=0; i != NumElts; ++i) {
5604 SDValue Op = N0->getOperand(i);
5605 if (Op->getOpcode() == ISD::UNDEF) {
5606 Elts.push_back(DAG.getUNDEF(SVT));
5611 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5612 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5613 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5614 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5617 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5621 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5624 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5625 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5626 // transformation. Returns true if extension are possible and the above
5627 // mentioned transformation is profitable.
5628 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5630 SmallVectorImpl<SDNode *> &ExtendNodes,
5631 const TargetLowering &TLI) {
5632 bool HasCopyToRegUses = false;
5633 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5634 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5635 UE = N0.getNode()->use_end();
5640 if (UI.getUse().getResNo() != N0.getResNo())
5642 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5643 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5644 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5645 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5646 // Sign bits will be lost after a zext.
5649 for (unsigned i = 0; i != 2; ++i) {
5650 SDValue UseOp = User->getOperand(i);
5653 if (!isa<ConstantSDNode>(UseOp))
5658 ExtendNodes.push_back(User);
5661 // If truncates aren't free and there are users we can't
5662 // extend, it isn't worthwhile.
5665 // Remember if this value is live-out.
5666 if (User->getOpcode() == ISD::CopyToReg)
5667 HasCopyToRegUses = true;
5670 if (HasCopyToRegUses) {
5671 bool BothLiveOut = false;
5672 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5674 SDUse &Use = UI.getUse();
5675 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5681 // Both unextended and extended values are live out. There had better be
5682 // a good reason for the transformation.
5683 return ExtendNodes.size();
5688 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5689 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5690 ISD::NodeType ExtType) {
5691 // Extend SetCC uses if necessary.
5692 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5693 SDNode *SetCC = SetCCs[i];
5694 SmallVector<SDValue, 4> Ops;
5696 for (unsigned j = 0; j != 2; ++j) {
5697 SDValue SOp = SetCC->getOperand(j);
5699 Ops.push_back(ExtLoad);
5701 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5704 Ops.push_back(SetCC->getOperand(2));
5705 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5709 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5710 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5711 SDValue N0 = N->getOperand(0);
5712 EVT DstVT = N->getValueType(0);
5713 EVT SrcVT = N0.getValueType();
5715 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5716 N->getOpcode() == ISD::ZERO_EXTEND) &&
5717 "Unexpected node type (not an extend)!");
5719 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5720 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5721 // (v8i32 (sext (v8i16 (load x))))
5723 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5724 // (v4i32 (sextload (x + 16)))))
5725 // Where uses of the original load, i.e.:
5727 // are replaced with:
5729 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5730 // (v4i32 (sextload (x + 16)))))))
5732 // This combine is only applicable to illegal, but splittable, vectors.
5733 // All legal types, and illegal non-vector types, are handled elsewhere.
5734 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5736 if (N0->getOpcode() != ISD::LOAD)
5739 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5741 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5742 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5743 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5746 SmallVector<SDNode *, 4> SetCCs;
5747 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5750 ISD::LoadExtType ExtType =
5751 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5753 // Try to split the vector types to get down to legal types.
5754 EVT SplitSrcVT = SrcVT;
5755 EVT SplitDstVT = DstVT;
5756 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5757 SplitSrcVT.getVectorNumElements() > 1) {
5758 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5759 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5762 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5766 const unsigned NumSplits =
5767 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5768 const unsigned Stride = SplitSrcVT.getStoreSize();
5769 SmallVector<SDValue, 4> Loads;
5770 SmallVector<SDValue, 4> Chains;
5772 SDValue BasePtr = LN0->getBasePtr();
5773 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5774 const unsigned Offset = Idx * Stride;
5775 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5777 SDValue SplitLoad = DAG.getExtLoad(
5778 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5779 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5780 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5781 Align, LN0->getAAInfo());
5783 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5784 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5786 Loads.push_back(SplitLoad.getValue(0));
5787 Chains.push_back(SplitLoad.getValue(1));
5790 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5791 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5793 CombineTo(N, NewValue);
5795 // Replace uses of the original load (before extension)
5796 // with a truncate of the concatenated sextloaded vectors.
5798 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5799 CombineTo(N0.getNode(), Trunc, NewChain);
5800 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5801 (ISD::NodeType)N->getOpcode());
5802 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5805 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5806 SDValue N0 = N->getOperand(0);
5807 EVT VT = N->getValueType(0);
5809 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5811 return SDValue(Res, 0);
5813 // fold (sext (sext x)) -> (sext x)
5814 // fold (sext (aext x)) -> (sext x)
5815 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5816 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5819 if (N0.getOpcode() == ISD::TRUNCATE) {
5820 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5821 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5822 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5823 if (NarrowLoad.getNode()) {
5824 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5825 if (NarrowLoad.getNode() != N0.getNode()) {
5826 CombineTo(N0.getNode(), NarrowLoad);
5827 // CombineTo deleted the truncate, if needed, but not what's under it.
5830 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5833 // See if the value being truncated is already sign extended. If so, just
5834 // eliminate the trunc/sext pair.
5835 SDValue Op = N0.getOperand(0);
5836 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5837 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5838 unsigned DestBits = VT.getScalarType().getSizeInBits();
5839 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5841 if (OpBits == DestBits) {
5842 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5843 // bits, it is already ready.
5844 if (NumSignBits > DestBits-MidBits)
5846 } else if (OpBits < DestBits) {
5847 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5848 // bits, just sext from i32.
5849 if (NumSignBits > OpBits-MidBits)
5850 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5852 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5853 // bits, just truncate to i32.
5854 if (NumSignBits > OpBits-MidBits)
5855 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5858 // fold (sext (truncate x)) -> (sextinreg x).
5859 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5860 N0.getValueType())) {
5861 if (OpBits < DestBits)
5862 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5863 else if (OpBits > DestBits)
5864 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5865 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5866 DAG.getValueType(N0.getValueType()));
5870 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5871 // Only generate vector extloads when 1) they're legal, and 2) they are
5872 // deemed desirable by the target.
5873 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5874 ((!LegalOperations && !VT.isVector() &&
5875 !cast<LoadSDNode>(N0)->isVolatile()) ||
5876 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5877 bool DoXform = true;
5878 SmallVector<SDNode*, 4> SetCCs;
5879 if (!N0.hasOneUse())
5880 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5882 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5884 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5885 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5887 LN0->getBasePtr(), N0.getValueType(),
5888 LN0->getMemOperand());
5889 CombineTo(N, ExtLoad);
5890 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5891 N0.getValueType(), ExtLoad);
5892 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5893 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5895 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5899 // fold (sext (load x)) to multiple smaller sextloads.
5900 // Only on illegal but splittable vectors.
5901 if (SDValue ExtLoad = CombineExtLoad(N))
5904 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5905 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5906 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5907 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5908 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5909 EVT MemVT = LN0->getMemoryVT();
5910 if ((!LegalOperations && !LN0->isVolatile()) ||
5911 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5912 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5914 LN0->getBasePtr(), MemVT,
5915 LN0->getMemOperand());
5916 CombineTo(N, ExtLoad);
5917 CombineTo(N0.getNode(),
5918 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5919 N0.getValueType(), ExtLoad),
5920 ExtLoad.getValue(1));
5921 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5925 // fold (sext (and/or/xor (load x), cst)) ->
5926 // (and/or/xor (sextload x), (sext cst))
5927 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5928 N0.getOpcode() == ISD::XOR) &&
5929 isa<LoadSDNode>(N0.getOperand(0)) &&
5930 N0.getOperand(1).getOpcode() == ISD::Constant &&
5931 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5932 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5933 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5934 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5935 bool DoXform = true;
5936 SmallVector<SDNode*, 4> SetCCs;
5937 if (!N0.hasOneUse())
5938 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5941 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5942 LN0->getChain(), LN0->getBasePtr(),
5944 LN0->getMemOperand());
5945 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5946 Mask = Mask.sext(VT.getSizeInBits());
5948 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5949 ExtLoad, DAG.getConstant(Mask, DL, VT));
5950 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5951 SDLoc(N0.getOperand(0)),
5952 N0.getOperand(0).getValueType(), ExtLoad);
5954 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5955 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5957 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5962 if (N0.getOpcode() == ISD::SETCC) {
5963 EVT N0VT = N0.getOperand(0).getValueType();
5964 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5965 // Only do this before legalize for now.
5966 if (VT.isVector() && !LegalOperations &&
5967 TLI.getBooleanContents(N0VT) ==
5968 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5969 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5970 // of the same size as the compared operands. Only optimize sext(setcc())
5971 // if this is the case.
5972 EVT SVT = getSetCCResultType(N0VT);
5974 // We know that the # elements of the results is the same as the
5975 // # elements of the compare (and the # elements of the compare result
5976 // for that matter). Check to see that they are the same size. If so,
5977 // we know that the element size of the sext'd result matches the
5978 // element size of the compare operands.
5979 if (VT.getSizeInBits() == SVT.getSizeInBits())
5980 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5982 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5984 // If the desired elements are smaller or larger than the source
5985 // elements we can use a matching integer vector type and then
5986 // truncate/sign extend
5987 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5988 if (SVT == MatchingVectorType) {
5989 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5990 N0.getOperand(0), N0.getOperand(1),
5991 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5992 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5996 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5997 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6000 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6002 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6003 NegOne, DAG.getConstant(0, DL, VT),
6004 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6005 if (SCC.getNode()) return SCC;
6007 if (!VT.isVector()) {
6008 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6009 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
6011 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6012 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6013 N0.getOperand(0), N0.getOperand(1), CC);
6014 return DAG.getSelect(DL, VT, SetCC,
6015 NegOne, DAG.getConstant(0, DL, VT));
6020 // fold (sext x) -> (zext x) if the sign bit is known zero.
6021 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6022 DAG.SignBitIsZero(N0))
6023 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6028 // isTruncateOf - If N is a truncate of some other value, return true, record
6029 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6030 // This function computes KnownZero to avoid a duplicated call to
6031 // computeKnownBits in the caller.
6032 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6035 if (N->getOpcode() == ISD::TRUNCATE) {
6036 Op = N->getOperand(0);
6037 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6041 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6042 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6045 SDValue Op0 = N->getOperand(0);
6046 SDValue Op1 = N->getOperand(1);
6047 assert(Op0.getValueType() == Op1.getValueType());
6049 if (isNullConstant(Op0))
6051 else if (isNullConstant(Op1))
6056 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6058 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6064 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6065 SDValue N0 = N->getOperand(0);
6066 EVT VT = N->getValueType(0);
6068 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6070 return SDValue(Res, 0);
6072 // fold (zext (zext x)) -> (zext x)
6073 // fold (zext (aext x)) -> (zext x)
6074 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6075 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6078 // fold (zext (truncate x)) -> (zext x) or
6079 // (zext (truncate x)) -> (truncate x)
6080 // This is valid when the truncated bits of x are already zero.
6081 // FIXME: We should extend this to work for vectors too.
6084 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6085 APInt TruncatedBits =
6086 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6087 APInt(Op.getValueSizeInBits(), 0) :
6088 APInt::getBitsSet(Op.getValueSizeInBits(),
6089 N0.getValueSizeInBits(),
6090 std::min(Op.getValueSizeInBits(),
6091 VT.getSizeInBits()));
6092 if (TruncatedBits == (KnownZero & TruncatedBits)) {
6093 if (VT.bitsGT(Op.getValueType()))
6094 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6095 if (VT.bitsLT(Op.getValueType()))
6096 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6102 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6103 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6104 if (N0.getOpcode() == ISD::TRUNCATE) {
6105 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6106 if (NarrowLoad.getNode()) {
6107 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6108 if (NarrowLoad.getNode() != N0.getNode()) {
6109 CombineTo(N0.getNode(), NarrowLoad);
6110 // CombineTo deleted the truncate, if needed, but not what's under it.
6113 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6117 // fold (zext (truncate x)) -> (and x, mask)
6118 if (N0.getOpcode() == ISD::TRUNCATE &&
6119 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
6121 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6122 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6123 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6124 if (NarrowLoad.getNode()) {
6125 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6126 if (NarrowLoad.getNode() != N0.getNode()) {
6127 CombineTo(N0.getNode(), NarrowLoad);
6128 // CombineTo deleted the truncate, if needed, but not what's under it.
6131 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6134 SDValue Op = N0.getOperand(0);
6135 if (Op.getValueType().bitsLT(VT)) {
6136 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6137 AddToWorklist(Op.getNode());
6138 } else if (Op.getValueType().bitsGT(VT)) {
6139 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6140 AddToWorklist(Op.getNode());
6142 return DAG.getZeroExtendInReg(Op, SDLoc(N),
6143 N0.getValueType().getScalarType());
6146 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6147 // if either of the casts is not free.
6148 if (N0.getOpcode() == ISD::AND &&
6149 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6150 N0.getOperand(1).getOpcode() == ISD::Constant &&
6151 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6152 N0.getValueType()) ||
6153 !TLI.isZExtFree(N0.getValueType(), VT))) {
6154 SDValue X = N0.getOperand(0).getOperand(0);
6155 if (X.getValueType().bitsLT(VT)) {
6156 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6157 } else if (X.getValueType().bitsGT(VT)) {
6158 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6160 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6161 Mask = Mask.zext(VT.getSizeInBits());
6163 return DAG.getNode(ISD::AND, DL, VT,
6164 X, DAG.getConstant(Mask, DL, VT));
6167 // fold (zext (load x)) -> (zext (truncate (zextload x)))
6168 // Only generate vector extloads when 1) they're legal, and 2) they are
6169 // deemed desirable by the target.
6170 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6171 ((!LegalOperations && !VT.isVector() &&
6172 !cast<LoadSDNode>(N0)->isVolatile()) ||
6173 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6174 bool DoXform = true;
6175 SmallVector<SDNode*, 4> SetCCs;
6176 if (!N0.hasOneUse())
6177 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6179 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6181 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6182 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6184 LN0->getBasePtr(), N0.getValueType(),
6185 LN0->getMemOperand());
6186 CombineTo(N, ExtLoad);
6187 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6188 N0.getValueType(), ExtLoad);
6189 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6191 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6193 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6197 // fold (zext (load x)) to multiple smaller zextloads.
6198 // Only on illegal but splittable vectors.
6199 if (SDValue ExtLoad = CombineExtLoad(N))
6202 // fold (zext (and/or/xor (load x), cst)) ->
6203 // (and/or/xor (zextload x), (zext cst))
6204 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6205 N0.getOpcode() == ISD::XOR) &&
6206 isa<LoadSDNode>(N0.getOperand(0)) &&
6207 N0.getOperand(1).getOpcode() == ISD::Constant &&
6208 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6209 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6210 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6211 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6212 bool DoXform = true;
6213 SmallVector<SDNode*, 4> SetCCs;
6214 if (!N0.hasOneUse())
6215 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6218 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6219 LN0->getChain(), LN0->getBasePtr(),
6221 LN0->getMemOperand());
6222 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6223 Mask = Mask.zext(VT.getSizeInBits());
6225 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6226 ExtLoad, DAG.getConstant(Mask, DL, VT));
6227 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6228 SDLoc(N0.getOperand(0)),
6229 N0.getOperand(0).getValueType(), ExtLoad);
6231 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6232 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6234 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6239 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6240 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6241 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6242 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6243 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6244 EVT MemVT = LN0->getMemoryVT();
6245 if ((!LegalOperations && !LN0->isVolatile()) ||
6246 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6247 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6249 LN0->getBasePtr(), MemVT,
6250 LN0->getMemOperand());
6251 CombineTo(N, ExtLoad);
6252 CombineTo(N0.getNode(),
6253 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6255 ExtLoad.getValue(1));
6256 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6260 if (N0.getOpcode() == ISD::SETCC) {
6261 if (!LegalOperations && VT.isVector() &&
6262 N0.getValueType().getVectorElementType() == MVT::i1) {
6263 EVT N0VT = N0.getOperand(0).getValueType();
6264 if (getSetCCResultType(N0VT) == N0.getValueType())
6267 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6268 // Only do this before legalize for now.
6269 EVT EltVT = VT.getVectorElementType();
6271 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6272 DAG.getConstant(1, DL, EltVT));
6273 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6274 // We know that the # elements of the results is the same as the
6275 // # elements of the compare (and the # elements of the compare result
6276 // for that matter). Check to see that they are the same size. If so,
6277 // we know that the element size of the sext'd result matches the
6278 // element size of the compare operands.
6279 return DAG.getNode(ISD::AND, DL, VT,
6280 DAG.getSetCC(DL, VT, N0.getOperand(0),
6282 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6283 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6286 // If the desired elements are smaller or larger than the source
6287 // elements we can use a matching integer vector type and then
6288 // truncate/sign extend
6289 EVT MatchingElementType =
6290 EVT::getIntegerVT(*DAG.getContext(),
6291 N0VT.getScalarType().getSizeInBits());
6292 EVT MatchingVectorType =
6293 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6294 N0VT.getVectorNumElements());
6296 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6298 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6299 return DAG.getNode(ISD::AND, DL, VT,
6300 DAG.getSExtOrTrunc(VsetCC, DL, VT),
6301 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6304 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6307 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6308 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6309 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6310 if (SCC.getNode()) return SCC;
6313 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6314 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6315 isa<ConstantSDNode>(N0.getOperand(1)) &&
6316 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6318 SDValue ShAmt = N0.getOperand(1);
6319 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6320 if (N0.getOpcode() == ISD::SHL) {
6321 SDValue InnerZExt = N0.getOperand(0);
6322 // If the original shl may be shifting out bits, do not perform this
6324 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6325 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6326 if (ShAmtVal > KnownZeroBits)
6332 // Ensure that the shift amount is wide enough for the shifted value.
6333 if (VT.getSizeInBits() >= 256)
6334 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6336 return DAG.getNode(N0.getOpcode(), DL, VT,
6337 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6344 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6345 SDValue N0 = N->getOperand(0);
6346 EVT VT = N->getValueType(0);
6348 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6350 return SDValue(Res, 0);
6352 // fold (aext (aext x)) -> (aext x)
6353 // fold (aext (zext x)) -> (zext x)
6354 // fold (aext (sext x)) -> (sext x)
6355 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6356 N0.getOpcode() == ISD::ZERO_EXTEND ||
6357 N0.getOpcode() == ISD::SIGN_EXTEND)
6358 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6360 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6361 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6362 if (N0.getOpcode() == ISD::TRUNCATE) {
6363 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6364 if (NarrowLoad.getNode()) {
6365 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6366 if (NarrowLoad.getNode() != N0.getNode()) {
6367 CombineTo(N0.getNode(), NarrowLoad);
6368 // CombineTo deleted the truncate, if needed, but not what's under it.
6371 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6375 // fold (aext (truncate x))
6376 if (N0.getOpcode() == ISD::TRUNCATE) {
6377 SDValue TruncOp = N0.getOperand(0);
6378 if (TruncOp.getValueType() == VT)
6379 return TruncOp; // x iff x size == zext size.
6380 if (TruncOp.getValueType().bitsGT(VT))
6381 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6382 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6385 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6386 // if the trunc is not free.
6387 if (N0.getOpcode() == ISD::AND &&
6388 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6389 N0.getOperand(1).getOpcode() == ISD::Constant &&
6390 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6391 N0.getValueType())) {
6392 SDValue X = N0.getOperand(0).getOperand(0);
6393 if (X.getValueType().bitsLT(VT)) {
6394 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6395 } else if (X.getValueType().bitsGT(VT)) {
6396 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6398 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6399 Mask = Mask.zext(VT.getSizeInBits());
6401 return DAG.getNode(ISD::AND, DL, VT,
6402 X, DAG.getConstant(Mask, DL, VT));
6405 // fold (aext (load x)) -> (aext (truncate (extload x)))
6406 // None of the supported targets knows how to perform load and any_ext
6407 // on vectors in one instruction. We only perform this transformation on
6409 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6410 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6411 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6412 bool DoXform = true;
6413 SmallVector<SDNode*, 4> SetCCs;
6414 if (!N0.hasOneUse())
6415 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6417 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6418 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6420 LN0->getBasePtr(), N0.getValueType(),
6421 LN0->getMemOperand());
6422 CombineTo(N, ExtLoad);
6423 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6424 N0.getValueType(), ExtLoad);
6425 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6426 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6428 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6432 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6433 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6434 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6435 if (N0.getOpcode() == ISD::LOAD &&
6436 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6438 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6439 ISD::LoadExtType ExtType = LN0->getExtensionType();
6440 EVT MemVT = LN0->getMemoryVT();
6441 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6442 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6443 VT, LN0->getChain(), LN0->getBasePtr(),
6444 MemVT, LN0->getMemOperand());
6445 CombineTo(N, ExtLoad);
6446 CombineTo(N0.getNode(),
6447 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6448 N0.getValueType(), ExtLoad),
6449 ExtLoad.getValue(1));
6450 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6454 if (N0.getOpcode() == ISD::SETCC) {
6456 // aext(setcc) -> vsetcc
6457 // aext(setcc) -> truncate(vsetcc)
6458 // aext(setcc) -> aext(vsetcc)
6459 // Only do this before legalize for now.
6460 if (VT.isVector() && !LegalOperations) {
6461 EVT N0VT = N0.getOperand(0).getValueType();
6462 // We know that the # elements of the results is the same as the
6463 // # elements of the compare (and the # elements of the compare result
6464 // for that matter). Check to see that they are the same size. If so,
6465 // we know that the element size of the sext'd result matches the
6466 // element size of the compare operands.
6467 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6468 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6470 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6471 // If the desired elements are smaller or larger than the source
6472 // elements we can use a matching integer vector type and then
6473 // truncate/any extend
6475 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6477 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6479 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6480 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6484 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6487 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6488 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6489 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6497 /// See if the specified operand can be simplified with the knowledge that only
6498 /// the bits specified by Mask are used. If so, return the simpler operand,
6499 /// otherwise return a null SDValue.
6500 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6501 switch (V.getOpcode()) {
6503 case ISD::Constant: {
6504 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6505 assert(CV && "Const value should be ConstSDNode.");
6506 const APInt &CVal = CV->getAPIntValue();
6507 APInt NewVal = CVal & Mask;
6509 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6514 // If the LHS or RHS don't contribute bits to the or, drop them.
6515 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6516 return V.getOperand(1);
6517 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6518 return V.getOperand(0);
6521 // Only look at single-use SRLs.
6522 if (!V.getNode()->hasOneUse())
6524 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6525 // See if we can recursively simplify the LHS.
6526 unsigned Amt = RHSC->getZExtValue();
6528 // Watch out for shift count overflow though.
6529 if (Amt >= Mask.getBitWidth()) break;
6530 APInt NewMask = Mask << Amt;
6531 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6532 if (SimplifyLHS.getNode())
6533 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6534 SimplifyLHS, V.getOperand(1));
6540 /// If the result of a wider load is shifted to right of N bits and then
6541 /// truncated to a narrower type and where N is a multiple of number of bits of
6542 /// the narrower type, transform it to a narrower load from address + N / num of
6543 /// bits of new type. If the result is to be extended, also fold the extension
6544 /// to form a extending load.
6545 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6546 unsigned Opc = N->getOpcode();
6548 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6549 SDValue N0 = N->getOperand(0);
6550 EVT VT = N->getValueType(0);
6553 // This transformation isn't valid for vector loads.
6557 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6559 if (Opc == ISD::SIGN_EXTEND_INREG) {
6560 ExtType = ISD::SEXTLOAD;
6561 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6562 } else if (Opc == ISD::SRL) {
6563 // Another special-case: SRL is basically zero-extending a narrower value.
6564 ExtType = ISD::ZEXTLOAD;
6566 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6567 if (!N01) return SDValue();
6568 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6569 VT.getSizeInBits() - N01->getZExtValue());
6571 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6574 unsigned EVTBits = ExtVT.getSizeInBits();
6576 // Do not generate loads of non-round integer types since these can
6577 // be expensive (and would be wrong if the type is not byte sized).
6578 if (!ExtVT.isRound())
6582 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6583 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6584 ShAmt = N01->getZExtValue();
6585 // Is the shift amount a multiple of size of VT?
6586 if ((ShAmt & (EVTBits-1)) == 0) {
6587 N0 = N0.getOperand(0);
6588 // Is the load width a multiple of size of VT?
6589 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6593 // At this point, we must have a load or else we can't do the transform.
6594 if (!isa<LoadSDNode>(N0)) return SDValue();
6596 // Because a SRL must be assumed to *need* to zero-extend the high bits
6597 // (as opposed to anyext the high bits), we can't combine the zextload
6598 // lowering of SRL and an sextload.
6599 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6602 // If the shift amount is larger than the input type then we're not
6603 // accessing any of the loaded bytes. If the load was a zextload/extload
6604 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6605 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6610 // If the load is shifted left (and the result isn't shifted back right),
6611 // we can fold the truncate through the shift.
6612 unsigned ShLeftAmt = 0;
6613 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6614 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6615 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6616 ShLeftAmt = N01->getZExtValue();
6617 N0 = N0.getOperand(0);
6621 // If we haven't found a load, we can't narrow it. Don't transform one with
6622 // multiple uses, this would require adding a new load.
6623 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6626 // Don't change the width of a volatile load.
6627 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6628 if (LN0->isVolatile())
6631 // Verify that we are actually reducing a load width here.
6632 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6635 // For the transform to be legal, the load must produce only two values
6636 // (the value loaded and the chain). Don't transform a pre-increment
6637 // load, for example, which produces an extra value. Otherwise the
6638 // transformation is not equivalent, and the downstream logic to replace
6639 // uses gets things wrong.
6640 if (LN0->getNumValues() > 2)
6643 // If the load that we're shrinking is an extload and we're not just
6644 // discarding the extension we can't simply shrink the load. Bail.
6645 // TODO: It would be possible to merge the extensions in some cases.
6646 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6647 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6650 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6653 EVT PtrType = N0.getOperand(1).getValueType();
6655 if (PtrType == MVT::Untyped || PtrType.isExtended())
6656 // It's not possible to generate a constant of extended or untyped type.
6659 // For big endian targets, we need to adjust the offset to the pointer to
6660 // load the correct bytes.
6661 if (TLI.isBigEndian()) {
6662 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6663 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6664 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6667 uint64_t PtrOff = ShAmt / 8;
6668 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6670 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6671 PtrType, LN0->getBasePtr(),
6672 DAG.getConstant(PtrOff, DL, PtrType));
6673 AddToWorklist(NewPtr.getNode());
6676 if (ExtType == ISD::NON_EXTLOAD)
6677 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6678 LN0->getPointerInfo().getWithOffset(PtrOff),
6679 LN0->isVolatile(), LN0->isNonTemporal(),
6680 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6682 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6683 LN0->getPointerInfo().getWithOffset(PtrOff),
6684 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6685 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6687 // Replace the old load's chain with the new load's chain.
6688 WorklistRemover DeadNodes(*this);
6689 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6691 // Shift the result left, if we've swallowed a left shift.
6692 SDValue Result = Load;
6693 if (ShLeftAmt != 0) {
6694 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6695 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6697 // If the shift amount is as large as the result size (but, presumably,
6698 // no larger than the source) then the useful bits of the result are
6699 // zero; we can't simply return the shortened shift, because the result
6700 // of that operation is undefined.
6702 if (ShLeftAmt >= VT.getSizeInBits())
6703 Result = DAG.getConstant(0, DL, VT);
6705 Result = DAG.getNode(ISD::SHL, DL, VT,
6706 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6709 // Return the new loaded value.
6713 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6714 SDValue N0 = N->getOperand(0);
6715 SDValue N1 = N->getOperand(1);
6716 EVT VT = N->getValueType(0);
6717 EVT EVT = cast<VTSDNode>(N1)->getVT();
6718 unsigned VTBits = VT.getScalarType().getSizeInBits();
6719 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6721 // fold (sext_in_reg c1) -> c1
6722 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6723 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6725 // If the input is already sign extended, just drop the extension.
6726 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6729 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6730 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6731 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6732 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6733 N0.getOperand(0), N1);
6735 // fold (sext_in_reg (sext x)) -> (sext x)
6736 // fold (sext_in_reg (aext x)) -> (sext x)
6737 // if x is small enough.
6738 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6739 SDValue N00 = N0.getOperand(0);
6740 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6741 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6742 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6745 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6746 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6747 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6749 // fold operands of sext_in_reg based on knowledge that the top bits are not
6751 if (SimplifyDemandedBits(SDValue(N, 0)))
6752 return SDValue(N, 0);
6754 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6755 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6756 SDValue NarrowLoad = ReduceLoadWidth(N);
6757 if (NarrowLoad.getNode())
6760 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6761 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6762 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6763 if (N0.getOpcode() == ISD::SRL) {
6764 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6765 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6766 // We can turn this into an SRA iff the input to the SRL is already sign
6768 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6769 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6770 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6771 N0.getOperand(0), N0.getOperand(1));
6775 // fold (sext_inreg (extload x)) -> (sextload x)
6776 if (ISD::isEXTLoad(N0.getNode()) &&
6777 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6778 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6779 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6780 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6781 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6782 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6784 LN0->getBasePtr(), EVT,
6785 LN0->getMemOperand());
6786 CombineTo(N, ExtLoad);
6787 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6788 AddToWorklist(ExtLoad.getNode());
6789 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6791 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6792 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6794 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6795 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6796 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6797 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6798 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6800 LN0->getBasePtr(), EVT,
6801 LN0->getMemOperand());
6802 CombineTo(N, ExtLoad);
6803 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6804 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6807 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6808 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6809 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6810 N0.getOperand(1), false);
6811 if (BSwap.getNode())
6812 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6816 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6817 // into a build_vector.
6818 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6819 SmallVector<SDValue, 8> Elts;
6820 unsigned NumElts = N0->getNumOperands();
6821 unsigned ShAmt = VTBits - EVTBits;
6823 for (unsigned i = 0; i != NumElts; ++i) {
6824 SDValue Op = N0->getOperand(i);
6825 if (Op->getOpcode() == ISD::UNDEF) {
6830 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6831 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6832 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6833 SDLoc(Op), Op.getValueType()));
6836 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6842 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6843 SDValue N0 = N->getOperand(0);
6844 EVT VT = N->getValueType(0);
6846 if (N0.getOpcode() == ISD::UNDEF)
6847 return DAG.getUNDEF(VT);
6849 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6851 return SDValue(Res, 0);
6856 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6857 SDValue N0 = N->getOperand(0);
6858 EVT VT = N->getValueType(0);
6859 bool isLE = TLI.isLittleEndian();
6862 if (N0.getValueType() == N->getValueType(0))
6864 // fold (truncate c1) -> c1
6865 if (isConstantIntBuildVectorOrConstantInt(N0))
6866 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6867 // fold (truncate (truncate x)) -> (truncate x)
6868 if (N0.getOpcode() == ISD::TRUNCATE)
6869 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6870 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6871 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6872 N0.getOpcode() == ISD::SIGN_EXTEND ||
6873 N0.getOpcode() == ISD::ANY_EXTEND) {
6874 if (N0.getOperand(0).getValueType().bitsLT(VT))
6875 // if the source is smaller than the dest, we still need an extend
6876 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6878 if (N0.getOperand(0).getValueType().bitsGT(VT))
6879 // if the source is larger than the dest, than we just need the truncate
6880 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6881 // if the source and dest are the same type, we can drop both the extend
6882 // and the truncate.
6883 return N0.getOperand(0);
6886 // Fold extract-and-trunc into a narrow extract. For example:
6887 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6888 // i32 y = TRUNCATE(i64 x)
6890 // v16i8 b = BITCAST (v2i64 val)
6891 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6893 // Note: We only run this optimization after type legalization (which often
6894 // creates this pattern) and before operation legalization after which
6895 // we need to be more careful about the vector instructions that we generate.
6896 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6897 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6899 EVT VecTy = N0.getOperand(0).getValueType();
6900 EVT ExTy = N0.getValueType();
6901 EVT TrTy = N->getValueType(0);
6903 unsigned NumElem = VecTy.getVectorNumElements();
6904 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6906 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6907 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6909 SDValue EltNo = N0->getOperand(1);
6910 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6911 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6912 EVT IndexTy = TLI.getVectorIdxTy();
6913 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6915 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6916 NVT, N0.getOperand(0));
6919 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6921 DAG.getConstant(Index, DL, IndexTy));
6925 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6926 if (N0.getOpcode() == ISD::SELECT) {
6927 EVT SrcVT = N0.getValueType();
6928 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6929 TLI.isTruncateFree(SrcVT, VT)) {
6931 SDValue Cond = N0.getOperand(0);
6932 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6933 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6934 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6938 // Fold a series of buildvector, bitcast, and truncate if possible.
6940 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6941 // (2xi32 (buildvector x, y)).
6942 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6943 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6944 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6945 N0.getOperand(0).hasOneUse()) {
6947 SDValue BuildVect = N0.getOperand(0);
6948 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6949 EVT TruncVecEltTy = VT.getVectorElementType();
6951 // Check that the element types match.
6952 if (BuildVectEltTy == TruncVecEltTy) {
6953 // Now we only need to compute the offset of the truncated elements.
6954 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6955 unsigned TruncVecNumElts = VT.getVectorNumElements();
6956 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6958 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6959 "Invalid number of elements");
6961 SmallVector<SDValue, 8> Opnds;
6962 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6963 Opnds.push_back(BuildVect.getOperand(i));
6965 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6969 // See if we can simplify the input to this truncate through knowledge that
6970 // only the low bits are being used.
6971 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6972 // Currently we only perform this optimization on scalars because vectors
6973 // may have different active low bits.
6974 if (!VT.isVector()) {
6976 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6977 VT.getSizeInBits()));
6978 if (Shorter.getNode())
6979 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6981 // fold (truncate (load x)) -> (smaller load x)
6982 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6983 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6984 SDValue Reduced = ReduceLoadWidth(N);
6985 if (Reduced.getNode())
6987 // Handle the case where the load remains an extending load even
6988 // after truncation.
6989 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6990 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6991 if (!LN0->isVolatile() &&
6992 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6993 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6994 VT, LN0->getChain(), LN0->getBasePtr(),
6996 LN0->getMemOperand());
6997 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7002 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7003 // where ... are all 'undef'.
7004 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7005 SmallVector<EVT, 8> VTs;
7008 unsigned NumDefs = 0;
7010 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7011 SDValue X = N0.getOperand(i);
7012 if (X.getOpcode() != ISD::UNDEF) {
7017 // Stop if more than one members are non-undef.
7020 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7021 VT.getVectorElementType(),
7022 X.getValueType().getVectorNumElements()));
7026 return DAG.getUNDEF(VT);
7029 assert(V.getNode() && "The single defined operand is empty!");
7030 SmallVector<SDValue, 8> Opnds;
7031 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7033 Opnds.push_back(DAG.getUNDEF(VTs[i]));
7036 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7037 AddToWorklist(NV.getNode());
7038 Opnds.push_back(NV);
7040 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7044 // Simplify the operands using demanded-bits information.
7045 if (!VT.isVector() &&
7046 SimplifyDemandedBits(SDValue(N, 0)))
7047 return SDValue(N, 0);
7052 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7053 SDValue Elt = N->getOperand(i);
7054 if (Elt.getOpcode() != ISD::MERGE_VALUES)
7055 return Elt.getNode();
7056 return Elt.getOperand(Elt.getResNo()).getNode();
7059 /// build_pair (load, load) -> load
7060 /// if load locations are consecutive.
7061 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7062 assert(N->getOpcode() == ISD::BUILD_PAIR);
7064 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7065 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7066 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7067 LD1->getAddressSpace() != LD2->getAddressSpace())
7069 EVT LD1VT = LD1->getValueType(0);
7071 if (ISD::isNON_EXTLoad(LD2) &&
7073 // If both are volatile this would reduce the number of volatile loads.
7074 // If one is volatile it might be ok, but play conservative and bail out.
7075 !LD1->isVolatile() &&
7076 !LD2->isVolatile() &&
7077 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7078 unsigned Align = LD1->getAlignment();
7079 unsigned NewAlign = TLI.getDataLayout()->
7080 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7082 if (NewAlign <= Align &&
7083 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7084 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7085 LD1->getBasePtr(), LD1->getPointerInfo(),
7086 false, false, false, Align);
7092 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7093 SDValue N0 = N->getOperand(0);
7094 EVT VT = N->getValueType(0);
7096 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7097 // Only do this before legalize, since afterward the target may be depending
7098 // on the bitconvert.
7099 // First check to see if this is all constant.
7101 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7103 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7105 EVT DestEltVT = N->getValueType(0).getVectorElementType();
7106 assert(!DestEltVT.isVector() &&
7107 "Element type of vector ValueType must not be vector!");
7109 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7112 // If the input is a constant, let getNode fold it.
7113 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7114 // If we can't allow illegal operations, we need to check that this is just
7115 // a fp -> int or int -> conversion and that the resulting operation will
7117 if (!LegalOperations ||
7118 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7119 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7120 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7121 TLI.isOperationLegal(ISD::Constant, VT)))
7122 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7125 // (conv (conv x, t1), t2) -> (conv x, t2)
7126 if (N0.getOpcode() == ISD::BITCAST)
7127 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7130 // fold (conv (load x)) -> (load (conv*)x)
7131 // If the resultant load doesn't need a higher alignment than the original!
7132 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7133 // Do not change the width of a volatile load.
7134 !cast<LoadSDNode>(N0)->isVolatile() &&
7135 // Do not remove the cast if the types differ in endian layout.
7136 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
7137 TLI.hasBigEndianPartOrdering(VT) &&
7138 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7139 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7140 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7141 unsigned Align = TLI.getDataLayout()->
7142 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7143 unsigned OrigAlign = LN0->getAlignment();
7145 if (Align <= OrigAlign) {
7146 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7147 LN0->getBasePtr(), LN0->getPointerInfo(),
7148 LN0->isVolatile(), LN0->isNonTemporal(),
7149 LN0->isInvariant(), OrigAlign,
7151 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7156 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7157 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7158 // This often reduces constant pool loads.
7159 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7160 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7161 N0.getNode()->hasOneUse() && VT.isInteger() &&
7162 !VT.isVector() && !N0.getValueType().isVector()) {
7163 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7165 AddToWorklist(NewConv.getNode());
7168 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7169 if (N0.getOpcode() == ISD::FNEG)
7170 return DAG.getNode(ISD::XOR, DL, VT,
7171 NewConv, DAG.getConstant(SignBit, DL, VT));
7172 assert(N0.getOpcode() == ISD::FABS);
7173 return DAG.getNode(ISD::AND, DL, VT,
7174 NewConv, DAG.getConstant(~SignBit, DL, VT));
7177 // fold (bitconvert (fcopysign cst, x)) ->
7178 // (or (and (bitconvert x), sign), (and cst, (not sign)))
7179 // Note that we don't handle (copysign x, cst) because this can always be
7180 // folded to an fneg or fabs.
7181 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7182 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7183 VT.isInteger() && !VT.isVector()) {
7184 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7185 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7186 if (isTypeLegal(IntXVT)) {
7187 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7188 IntXVT, N0.getOperand(1));
7189 AddToWorklist(X.getNode());
7191 // If X has a different width than the result/lhs, sext it or truncate it.
7192 unsigned VTWidth = VT.getSizeInBits();
7193 if (OrigXWidth < VTWidth) {
7194 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7195 AddToWorklist(X.getNode());
7196 } else if (OrigXWidth > VTWidth) {
7197 // To get the sign bit in the right place, we have to shift it right
7198 // before truncating.
7200 X = DAG.getNode(ISD::SRL, DL,
7201 X.getValueType(), X,
7202 DAG.getConstant(OrigXWidth-VTWidth, DL,
7204 AddToWorklist(X.getNode());
7205 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7206 AddToWorklist(X.getNode());
7209 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7210 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7211 X, DAG.getConstant(SignBit, SDLoc(X), VT));
7212 AddToWorklist(X.getNode());
7214 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7215 VT, N0.getOperand(0));
7216 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7217 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7218 AddToWorklist(Cst.getNode());
7220 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7224 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7225 if (N0.getOpcode() == ISD::BUILD_PAIR) {
7226 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
7227 if (CombineLD.getNode())
7231 // Remove double bitcasts from shuffles - this is often a legacy of
7232 // XformToShuffleWithZero being used to combine bitmaskings (of
7233 // float vectors bitcast to integer vectors) into shuffles.
7234 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7235 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7236 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7237 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7238 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7239 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7241 // If operands are a bitcast, peek through if it casts the original VT.
7242 // If operands are a UNDEF or constant, just bitcast back to original VT.
7243 auto PeekThroughBitcast = [&](SDValue Op) {
7244 if (Op.getOpcode() == ISD::BITCAST &&
7245 Op.getOperand(0)->getValueType(0) == VT)
7246 return SDValue(Op.getOperand(0));
7247 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7248 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7249 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7253 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7254 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7259 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7260 SmallVector<int, 8> NewMask;
7261 for (int M : SVN->getMask())
7262 for (int i = 0; i != MaskScale; ++i)
7263 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7265 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7267 std::swap(SV0, SV1);
7268 ShuffleVectorSDNode::commuteMask(NewMask);
7269 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7273 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7279 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7280 EVT VT = N->getValueType(0);
7281 return CombineConsecutiveLoads(N, VT);
7284 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7285 /// operands. DstEltVT indicates the destination element value type.
7286 SDValue DAGCombiner::
7287 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7288 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7290 // If this is already the right type, we're done.
7291 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7293 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7294 unsigned DstBitSize = DstEltVT.getSizeInBits();
7296 // If this is a conversion of N elements of one type to N elements of another
7297 // type, convert each element. This handles FP<->INT cases.
7298 if (SrcBitSize == DstBitSize) {
7299 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7300 BV->getValueType(0).getVectorNumElements());
7302 // Due to the FP element handling below calling this routine recursively,
7303 // we can end up with a scalar-to-vector node here.
7304 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7305 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7306 DAG.getNode(ISD::BITCAST, SDLoc(BV),
7307 DstEltVT, BV->getOperand(0)));
7309 SmallVector<SDValue, 8> Ops;
7310 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7311 SDValue Op = BV->getOperand(i);
7312 // If the vector element type is not legal, the BUILD_VECTOR operands
7313 // are promoted and implicitly truncated. Make that explicit here.
7314 if (Op.getValueType() != SrcEltVT)
7315 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7316 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7318 AddToWorklist(Ops.back().getNode());
7320 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7323 // Otherwise, we're growing or shrinking the elements. To avoid having to
7324 // handle annoying details of growing/shrinking FP values, we convert them to
7326 if (SrcEltVT.isFloatingPoint()) {
7327 // Convert the input float vector to a int vector where the elements are the
7329 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7330 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7334 // Now we know the input is an integer vector. If the output is a FP type,
7335 // convert to integer first, then to FP of the right size.
7336 if (DstEltVT.isFloatingPoint()) {
7337 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7338 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7340 // Next, convert to FP elements of the same size.
7341 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7346 // Okay, we know the src/dst types are both integers of differing types.
7347 // Handling growing first.
7348 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7349 if (SrcBitSize < DstBitSize) {
7350 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7352 SmallVector<SDValue, 8> Ops;
7353 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7354 i += NumInputsPerOutput) {
7355 bool isLE = TLI.isLittleEndian();
7356 APInt NewBits = APInt(DstBitSize, 0);
7357 bool EltIsUndef = true;
7358 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7359 // Shift the previously computed bits over.
7360 NewBits <<= SrcBitSize;
7361 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7362 if (Op.getOpcode() == ISD::UNDEF) continue;
7365 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7366 zextOrTrunc(SrcBitSize).zext(DstBitSize);
7370 Ops.push_back(DAG.getUNDEF(DstEltVT));
7372 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7375 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7376 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7379 // Finally, this must be the case where we are shrinking elements: each input
7380 // turns into multiple outputs.
7381 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7382 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7383 NumOutputsPerInput*BV->getNumOperands());
7384 SmallVector<SDValue, 8> Ops;
7386 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7387 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7388 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7392 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7393 getAPIntValue().zextOrTrunc(SrcBitSize);
7395 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7396 APInt ThisVal = OpVal.trunc(DstBitSize);
7397 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7398 OpVal = OpVal.lshr(DstBitSize);
7401 // For big endian targets, swap the order of the pieces of each element.
7402 if (TLI.isBigEndian())
7403 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7406 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7409 /// Try to perform FMA combining on a given FADD node.
7410 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7411 SDValue N0 = N->getOperand(0);
7412 SDValue N1 = N->getOperand(1);
7413 EVT VT = N->getValueType(0);
7416 const TargetOptions &Options = DAG.getTarget().Options;
7417 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7418 Options.UnsafeFPMath);
7420 // Floating-point multiply-add with intermediate rounding.
7421 bool HasFMAD = (LegalOperations &&
7422 TLI.isOperationLegal(ISD::FMAD, VT));
7424 // Floating-point multiply-add without intermediate rounding.
7425 bool HasFMA = ((!LegalOperations ||
7426 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7427 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7430 // No valid opcode, do not combine.
7431 if (!HasFMAD && !HasFMA)
7434 // Always prefer FMAD to FMA for precision.
7435 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7436 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7437 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7439 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7440 if (N0.getOpcode() == ISD::FMUL &&
7441 (Aggressive || N0->hasOneUse())) {
7442 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7443 N0.getOperand(0), N0.getOperand(1), N1);
7446 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7447 // Note: Commutes FADD operands.
7448 if (N1.getOpcode() == ISD::FMUL &&
7449 (Aggressive || N1->hasOneUse())) {
7450 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7451 N1.getOperand(0), N1.getOperand(1), N0);
7454 // Look through FP_EXTEND nodes to do more combining.
7455 if (UnsafeFPMath && LookThroughFPExt) {
7456 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7457 if (N0.getOpcode() == ISD::FP_EXTEND) {
7458 SDValue N00 = N0.getOperand(0);
7459 if (N00.getOpcode() == ISD::FMUL)
7460 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7461 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7463 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7464 N00.getOperand(1)), N1);
7467 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7468 // Note: Commutes FADD operands.
7469 if (N1.getOpcode() == ISD::FP_EXTEND) {
7470 SDValue N10 = N1.getOperand(0);
7471 if (N10.getOpcode() == ISD::FMUL)
7472 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7473 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7475 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7476 N10.getOperand(1)), N0);
7480 // More folding opportunities when target permits.
7481 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7482 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7483 if (N0.getOpcode() == PreferredFusedOpcode &&
7484 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7485 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7486 N0.getOperand(0), N0.getOperand(1),
7487 DAG.getNode(PreferredFusedOpcode, SL, VT,
7488 N0.getOperand(2).getOperand(0),
7489 N0.getOperand(2).getOperand(1),
7493 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7494 if (N1->getOpcode() == PreferredFusedOpcode &&
7495 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7496 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7497 N1.getOperand(0), N1.getOperand(1),
7498 DAG.getNode(PreferredFusedOpcode, SL, VT,
7499 N1.getOperand(2).getOperand(0),
7500 N1.getOperand(2).getOperand(1),
7504 if (UnsafeFPMath && LookThroughFPExt) {
7505 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7506 // -> (fma x, y, (fma (fpext u), (fpext v), z))
7507 auto FoldFAddFMAFPExtFMul = [&] (
7508 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7509 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7510 DAG.getNode(PreferredFusedOpcode, SL, VT,
7511 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7512 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7515 if (N0.getOpcode() == PreferredFusedOpcode) {
7516 SDValue N02 = N0.getOperand(2);
7517 if (N02.getOpcode() == ISD::FP_EXTEND) {
7518 SDValue N020 = N02.getOperand(0);
7519 if (N020.getOpcode() == ISD::FMUL)
7520 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7521 N020.getOperand(0), N020.getOperand(1),
7526 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7527 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7528 // FIXME: This turns two single-precision and one double-precision
7529 // operation into two double-precision operations, which might not be
7530 // interesting for all targets, especially GPUs.
7531 auto FoldFAddFPExtFMAFMul = [&] (
7532 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7533 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7534 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7535 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7536 DAG.getNode(PreferredFusedOpcode, SL, VT,
7537 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7538 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7541 if (N0.getOpcode() == ISD::FP_EXTEND) {
7542 SDValue N00 = N0.getOperand(0);
7543 if (N00.getOpcode() == PreferredFusedOpcode) {
7544 SDValue N002 = N00.getOperand(2);
7545 if (N002.getOpcode() == ISD::FMUL)
7546 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7547 N002.getOperand(0), N002.getOperand(1),
7552 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7553 // -> (fma y, z, (fma (fpext u), (fpext v), x))
7554 if (N1.getOpcode() == PreferredFusedOpcode) {
7555 SDValue N12 = N1.getOperand(2);
7556 if (N12.getOpcode() == ISD::FP_EXTEND) {
7557 SDValue N120 = N12.getOperand(0);
7558 if (N120.getOpcode() == ISD::FMUL)
7559 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7560 N120.getOperand(0), N120.getOperand(1),
7565 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7566 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7567 // FIXME: This turns two single-precision and one double-precision
7568 // operation into two double-precision operations, which might not be
7569 // interesting for all targets, especially GPUs.
7570 if (N1.getOpcode() == ISD::FP_EXTEND) {
7571 SDValue N10 = N1.getOperand(0);
7572 if (N10.getOpcode() == PreferredFusedOpcode) {
7573 SDValue N102 = N10.getOperand(2);
7574 if (N102.getOpcode() == ISD::FMUL)
7575 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7576 N102.getOperand(0), N102.getOperand(1),
7586 /// Try to perform FMA combining on a given FSUB node.
7587 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7588 SDValue N0 = N->getOperand(0);
7589 SDValue N1 = N->getOperand(1);
7590 EVT VT = N->getValueType(0);
7593 const TargetOptions &Options = DAG.getTarget().Options;
7594 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7595 Options.UnsafeFPMath);
7597 // Floating-point multiply-add with intermediate rounding.
7598 bool HasFMAD = (LegalOperations &&
7599 TLI.isOperationLegal(ISD::FMAD, VT));
7601 // Floating-point multiply-add without intermediate rounding.
7602 bool HasFMA = ((!LegalOperations ||
7603 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7604 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7607 // No valid opcode, do not combine.
7608 if (!HasFMAD && !HasFMA)
7611 // Always prefer FMAD to FMA for precision.
7612 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7613 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7614 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7616 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7617 if (N0.getOpcode() == ISD::FMUL &&
7618 (Aggressive || N0->hasOneUse())) {
7619 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7620 N0.getOperand(0), N0.getOperand(1),
7621 DAG.getNode(ISD::FNEG, SL, VT, N1));
7624 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7625 // Note: Commutes FSUB operands.
7626 if (N1.getOpcode() == ISD::FMUL &&
7627 (Aggressive || N1->hasOneUse()))
7628 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7629 DAG.getNode(ISD::FNEG, SL, VT,
7631 N1.getOperand(1), N0);
7633 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7634 if (N0.getOpcode() == ISD::FNEG &&
7635 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7636 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7637 SDValue N00 = N0.getOperand(0).getOperand(0);
7638 SDValue N01 = N0.getOperand(0).getOperand(1);
7639 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7640 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7641 DAG.getNode(ISD::FNEG, SL, VT, N1));
7644 // Look through FP_EXTEND nodes to do more combining.
7645 if (UnsafeFPMath && LookThroughFPExt) {
7646 // fold (fsub (fpext (fmul x, y)), z)
7647 // -> (fma (fpext x), (fpext y), (fneg z))
7648 if (N0.getOpcode() == ISD::FP_EXTEND) {
7649 SDValue N00 = N0.getOperand(0);
7650 if (N00.getOpcode() == ISD::FMUL)
7651 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7652 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7654 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7656 DAG.getNode(ISD::FNEG, SL, VT, N1));
7659 // fold (fsub x, (fpext (fmul y, z)))
7660 // -> (fma (fneg (fpext y)), (fpext z), x)
7661 // Note: Commutes FSUB operands.
7662 if (N1.getOpcode() == ISD::FP_EXTEND) {
7663 SDValue N10 = N1.getOperand(0);
7664 if (N10.getOpcode() == ISD::FMUL)
7665 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7666 DAG.getNode(ISD::FNEG, SL, VT,
7667 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7668 N10.getOperand(0))),
7669 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7674 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7675 // -> (fneg (fma (fpext x), (fpext y), z))
7676 // Note: This could be removed with appropriate canonicalization of the
7677 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7678 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7679 // from implementing the canonicalization in visitFSUB.
7680 if (N0.getOpcode() == ISD::FP_EXTEND) {
7681 SDValue N00 = N0.getOperand(0);
7682 if (N00.getOpcode() == ISD::FNEG) {
7683 SDValue N000 = N00.getOperand(0);
7684 if (N000.getOpcode() == ISD::FMUL) {
7685 return DAG.getNode(ISD::FNEG, SL, VT,
7686 DAG.getNode(PreferredFusedOpcode, SL, VT,
7687 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7688 N000.getOperand(0)),
7689 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7690 N000.getOperand(1)),
7696 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7697 // -> (fneg (fma (fpext x)), (fpext y), z)
7698 // Note: This could be removed with appropriate canonicalization of the
7699 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7700 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7701 // from implementing the canonicalization in visitFSUB.
7702 if (N0.getOpcode() == ISD::FNEG) {
7703 SDValue N00 = N0.getOperand(0);
7704 if (N00.getOpcode() == ISD::FP_EXTEND) {
7705 SDValue N000 = N00.getOperand(0);
7706 if (N000.getOpcode() == ISD::FMUL) {
7707 return DAG.getNode(ISD::FNEG, SL, VT,
7708 DAG.getNode(PreferredFusedOpcode, SL, VT,
7709 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7710 N000.getOperand(0)),
7711 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7712 N000.getOperand(1)),
7720 // More folding opportunities when target permits.
7721 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7722 // fold (fsub (fma x, y, (fmul u, v)), z)
7723 // -> (fma x, y (fma u, v, (fneg z)))
7724 if (N0.getOpcode() == PreferredFusedOpcode &&
7725 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7726 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7727 N0.getOperand(0), N0.getOperand(1),
7728 DAG.getNode(PreferredFusedOpcode, SL, VT,
7729 N0.getOperand(2).getOperand(0),
7730 N0.getOperand(2).getOperand(1),
7731 DAG.getNode(ISD::FNEG, SL, VT,
7735 // fold (fsub x, (fma y, z, (fmul u, v)))
7736 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7737 if (N1.getOpcode() == PreferredFusedOpcode &&
7738 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7739 SDValue N20 = N1.getOperand(2).getOperand(0);
7740 SDValue N21 = N1.getOperand(2).getOperand(1);
7741 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7742 DAG.getNode(ISD::FNEG, SL, VT,
7745 DAG.getNode(PreferredFusedOpcode, SL, VT,
7746 DAG.getNode(ISD::FNEG, SL, VT, N20),
7751 if (UnsafeFPMath && LookThroughFPExt) {
7752 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7753 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7754 if (N0.getOpcode() == PreferredFusedOpcode) {
7755 SDValue N02 = N0.getOperand(2);
7756 if (N02.getOpcode() == ISD::FP_EXTEND) {
7757 SDValue N020 = N02.getOperand(0);
7758 if (N020.getOpcode() == ISD::FMUL)
7759 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7760 N0.getOperand(0), N0.getOperand(1),
7761 DAG.getNode(PreferredFusedOpcode, SL, VT,
7762 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7763 N020.getOperand(0)),
7764 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7765 N020.getOperand(1)),
7766 DAG.getNode(ISD::FNEG, SL, VT,
7771 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7772 // -> (fma (fpext x), (fpext y),
7773 // (fma (fpext u), (fpext v), (fneg z)))
7774 // FIXME: This turns two single-precision and one double-precision
7775 // operation into two double-precision operations, which might not be
7776 // interesting for all targets, especially GPUs.
7777 if (N0.getOpcode() == ISD::FP_EXTEND) {
7778 SDValue N00 = N0.getOperand(0);
7779 if (N00.getOpcode() == PreferredFusedOpcode) {
7780 SDValue N002 = N00.getOperand(2);
7781 if (N002.getOpcode() == ISD::FMUL)
7782 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7783 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7785 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7787 DAG.getNode(PreferredFusedOpcode, SL, VT,
7788 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7789 N002.getOperand(0)),
7790 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7791 N002.getOperand(1)),
7792 DAG.getNode(ISD::FNEG, SL, VT,
7797 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7798 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7799 if (N1.getOpcode() == PreferredFusedOpcode &&
7800 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7801 SDValue N120 = N1.getOperand(2).getOperand(0);
7802 if (N120.getOpcode() == ISD::FMUL) {
7803 SDValue N1200 = N120.getOperand(0);
7804 SDValue N1201 = N120.getOperand(1);
7805 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7806 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7808 DAG.getNode(PreferredFusedOpcode, SL, VT,
7809 DAG.getNode(ISD::FNEG, SL, VT,
7810 DAG.getNode(ISD::FP_EXTEND, SL,
7812 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7818 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7819 // -> (fma (fneg (fpext y)), (fpext z),
7820 // (fma (fneg (fpext u)), (fpext v), x))
7821 // FIXME: This turns two single-precision and one double-precision
7822 // operation into two double-precision operations, which might not be
7823 // interesting for all targets, especially GPUs.
7824 if (N1.getOpcode() == ISD::FP_EXTEND &&
7825 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7826 SDValue N100 = N1.getOperand(0).getOperand(0);
7827 SDValue N101 = N1.getOperand(0).getOperand(1);
7828 SDValue N102 = N1.getOperand(0).getOperand(2);
7829 if (N102.getOpcode() == ISD::FMUL) {
7830 SDValue N1020 = N102.getOperand(0);
7831 SDValue N1021 = N102.getOperand(1);
7832 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7833 DAG.getNode(ISD::FNEG, SL, VT,
7834 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7836 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7837 DAG.getNode(PreferredFusedOpcode, SL, VT,
7838 DAG.getNode(ISD::FNEG, SL, VT,
7839 DAG.getNode(ISD::FP_EXTEND, SL,
7841 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7852 SDValue DAGCombiner::visitFADD(SDNode *N) {
7853 SDValue N0 = N->getOperand(0);
7854 SDValue N1 = N->getOperand(1);
7855 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7856 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7857 EVT VT = N->getValueType(0);
7859 const TargetOptions &Options = DAG.getTarget().Options;
7863 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7866 // fold (fadd c1, c2) -> c1 + c2
7868 return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7870 // canonicalize constant to RHS
7871 if (N0CFP && !N1CFP)
7872 return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7874 // fold (fadd A, (fneg B)) -> (fsub A, B)
7875 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7876 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7877 return DAG.getNode(ISD::FSUB, DL, VT, N0,
7878 GetNegatedExpression(N1, DAG, LegalOperations));
7880 // fold (fadd (fneg A), B) -> (fsub B, A)
7881 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7882 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7883 return DAG.getNode(ISD::FSUB, DL, VT, N1,
7884 GetNegatedExpression(N0, DAG, LegalOperations));
7886 // If 'unsafe math' is enabled, fold lots of things.
7887 if (Options.UnsafeFPMath) {
7888 // No FP constant should be created after legalization as Instruction
7889 // Selection pass has a hard time dealing with FP constants.
7890 bool AllowNewConst = (Level < AfterLegalizeDAG);
7892 // fold (fadd A, 0) -> A
7893 if (N1CFP && N1CFP->isZero())
7896 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7897 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7898 isa<ConstantFPSDNode>(N0.getOperand(1)))
7899 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7900 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7902 // If allowed, fold (fadd (fneg x), x) -> 0.0
7903 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7904 return DAG.getConstantFP(0.0, DL, VT);
7906 // If allowed, fold (fadd x, (fneg x)) -> 0.0
7907 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7908 return DAG.getConstantFP(0.0, DL, VT);
7910 // We can fold chains of FADD's of the same value into multiplications.
7911 // This transform is not safe in general because we are reducing the number
7912 // of rounding steps.
7913 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7914 if (N0.getOpcode() == ISD::FMUL) {
7915 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7916 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7918 // (fadd (fmul x, c), x) -> (fmul x, c+1)
7919 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7920 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7921 DAG.getConstantFP(1.0, DL, VT));
7922 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7925 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7926 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7927 N1.getOperand(0) == N1.getOperand(1) &&
7928 N0.getOperand(0) == N1.getOperand(0)) {
7929 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7930 DAG.getConstantFP(2.0, DL, VT));
7931 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
7935 if (N1.getOpcode() == ISD::FMUL) {
7936 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7937 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7939 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7940 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7941 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7942 DAG.getConstantFP(1.0, DL, VT));
7943 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
7946 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7947 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7948 N0.getOperand(0) == N0.getOperand(1) &&
7949 N1.getOperand(0) == N0.getOperand(0)) {
7950 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7951 DAG.getConstantFP(2.0, DL, VT));
7952 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
7956 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7957 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7958 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7959 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7960 (N0.getOperand(0) == N1)) {
7961 return DAG.getNode(ISD::FMUL, DL, VT,
7962 N1, DAG.getConstantFP(3.0, DL, VT));
7966 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7967 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7968 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7969 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7970 N1.getOperand(0) == N0) {
7971 return DAG.getNode(ISD::FMUL, DL, VT,
7972 N0, DAG.getConstantFP(3.0, DL, VT));
7976 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7977 if (AllowNewConst &&
7978 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7979 N0.getOperand(0) == N0.getOperand(1) &&
7980 N1.getOperand(0) == N1.getOperand(1) &&
7981 N0.getOperand(0) == N1.getOperand(0)) {
7982 return DAG.getNode(ISD::FMUL, DL, VT,
7983 N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
7986 } // enable-unsafe-fp-math
7988 // FADD -> FMA combines:
7989 SDValue Fused = visitFADDForFMACombine(N);
7991 AddToWorklist(Fused.getNode());
7998 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7999 SDValue N0 = N->getOperand(0);
8000 SDValue N1 = N->getOperand(1);
8001 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8002 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8003 EVT VT = N->getValueType(0);
8005 const TargetOptions &Options = DAG.getTarget().Options;
8009 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8012 // fold (fsub c1, c2) -> c1-c2
8014 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
8016 // fold (fsub A, (fneg B)) -> (fadd A, B)
8017 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8018 return DAG.getNode(ISD::FADD, dl, VT, N0,
8019 GetNegatedExpression(N1, DAG, LegalOperations));
8021 // If 'unsafe math' is enabled, fold lots of things.
8022 if (Options.UnsafeFPMath) {
8024 if (N1CFP && N1CFP->isZero())
8027 // (fsub 0, B) -> -B
8028 if (N0CFP && N0CFP->isZero()) {
8029 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8030 return GetNegatedExpression(N1, DAG, LegalOperations);
8031 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8032 return DAG.getNode(ISD::FNEG, dl, VT, N1);
8035 // (fsub x, x) -> 0.0
8037 return DAG.getConstantFP(0.0f, dl, VT);
8039 // (fsub x, (fadd x, y)) -> (fneg y)
8040 // (fsub x, (fadd y, x)) -> (fneg y)
8041 if (N1.getOpcode() == ISD::FADD) {
8042 SDValue N10 = N1->getOperand(0);
8043 SDValue N11 = N1->getOperand(1);
8045 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8046 return GetNegatedExpression(N11, DAG, LegalOperations);
8048 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8049 return GetNegatedExpression(N10, DAG, LegalOperations);
8053 // FSUB -> FMA combines:
8054 SDValue Fused = visitFSUBForFMACombine(N);
8056 AddToWorklist(Fused.getNode());
8063 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8064 SDValue N0 = N->getOperand(0);
8065 SDValue N1 = N->getOperand(1);
8066 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8067 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8068 EVT VT = N->getValueType(0);
8070 const TargetOptions &Options = DAG.getTarget().Options;
8073 if (VT.isVector()) {
8074 // This just handles C1 * C2 for vectors. Other vector folds are below.
8075 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8079 // fold (fmul c1, c2) -> c1*c2
8081 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
8083 // canonicalize constant to RHS
8084 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8085 !isConstantFPBuildVectorOrConstantFP(N1))
8086 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
8088 // fold (fmul A, 1.0) -> A
8089 if (N1CFP && N1CFP->isExactlyValue(1.0))
8092 if (Options.UnsafeFPMath) {
8093 // fold (fmul A, 0) -> 0
8094 if (N1CFP && N1CFP->isZero())
8097 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8098 if (N0.getOpcode() == ISD::FMUL) {
8099 // Fold scalars or any vector constants (not just splats).
8100 // This fold is done in general by InstCombine, but extra fmul insts
8101 // may have been generated during lowering.
8102 SDValue N00 = N0.getOperand(0);
8103 SDValue N01 = N0.getOperand(1);
8104 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8105 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8106 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8108 // Check 1: Make sure that the first operand of the inner multiply is NOT
8109 // a constant. Otherwise, we may induce infinite looping.
8110 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8111 // Check 2: Make sure that the second operand of the inner multiply and
8112 // the second operand of the outer multiply are constants.
8113 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8114 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8115 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8116 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
8121 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8122 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8123 // during an early run of DAGCombiner can prevent folding with fmuls
8124 // inserted during lowering.
8125 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
8126 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8127 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8128 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
8132 // fold (fmul X, 2.0) -> (fadd X, X)
8133 if (N1CFP && N1CFP->isExactlyValue(+2.0))
8134 return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
8136 // fold (fmul X, -1.0) -> (fneg X)
8137 if (N1CFP && N1CFP->isExactlyValue(-1.0))
8138 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8139 return DAG.getNode(ISD::FNEG, DL, VT, N0);
8141 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8142 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8143 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8144 // Both can be negated for free, check to see if at least one is cheaper
8146 if (LHSNeg == 2 || RHSNeg == 2)
8147 return DAG.getNode(ISD::FMUL, DL, VT,
8148 GetNegatedExpression(N0, DAG, LegalOperations),
8149 GetNegatedExpression(N1, DAG, LegalOperations));
8156 SDValue DAGCombiner::visitFMA(SDNode *N) {
8157 SDValue N0 = N->getOperand(0);
8158 SDValue N1 = N->getOperand(1);
8159 SDValue N2 = N->getOperand(2);
8160 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8161 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8162 EVT VT = N->getValueType(0);
8164 const TargetOptions &Options = DAG.getTarget().Options;
8166 // Constant fold FMA.
8167 if (isa<ConstantFPSDNode>(N0) &&
8168 isa<ConstantFPSDNode>(N1) &&
8169 isa<ConstantFPSDNode>(N2)) {
8170 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8173 if (Options.UnsafeFPMath) {
8174 if (N0CFP && N0CFP->isZero())
8176 if (N1CFP && N1CFP->isZero())
8179 if (N0CFP && N0CFP->isExactlyValue(1.0))
8180 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8181 if (N1CFP && N1CFP->isExactlyValue(1.0))
8182 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8184 // Canonicalize (fma c, x, y) -> (fma x, c, y)
8185 if (N0CFP && !N1CFP)
8186 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8188 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8189 if (Options.UnsafeFPMath && N1CFP &&
8190 N2.getOpcode() == ISD::FMUL &&
8191 N0 == N2.getOperand(0) &&
8192 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8193 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8194 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8198 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8199 if (Options.UnsafeFPMath &&
8200 N0.getOpcode() == ISD::FMUL && N1CFP &&
8201 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8202 return DAG.getNode(ISD::FMA, dl, VT,
8204 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8208 // (fma x, 1, y) -> (fadd x, y)
8209 // (fma x, -1, y) -> (fadd (fneg x), y)
8211 if (N1CFP->isExactlyValue(1.0))
8212 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8214 if (N1CFP->isExactlyValue(-1.0) &&
8215 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8216 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8217 AddToWorklist(RHSNeg.getNode());
8218 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8222 // (fma x, c, x) -> (fmul x, (c+1))
8223 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8224 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8225 DAG.getNode(ISD::FADD, dl, VT,
8226 N1, DAG.getConstantFP(1.0, dl, VT)));
8228 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8229 if (Options.UnsafeFPMath && N1CFP &&
8230 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8231 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8232 DAG.getNode(ISD::FADD, dl, VT,
8233 N1, DAG.getConstantFP(-1.0, dl, VT)));
8239 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8240 SDValue N0 = N->getOperand(0);
8241 SDValue N1 = N->getOperand(1);
8242 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8243 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8244 EVT VT = N->getValueType(0);
8246 const TargetOptions &Options = DAG.getTarget().Options;
8250 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8253 // fold (fdiv c1, c2) -> c1/c2
8255 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8257 if (Options.UnsafeFPMath) {
8258 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8260 // Compute the reciprocal 1.0 / c2.
8261 APFloat N1APF = N1CFP->getValueAPF();
8262 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8263 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8264 // Only do the transform if the reciprocal is a legal fp immediate that
8265 // isn't too nasty (eg NaN, denormal, ...).
8266 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8267 (!LegalOperations ||
8268 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8269 // backend)... we should handle this gracefully after Legalize.
8270 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8271 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8272 TLI.isFPImmLegal(Recip, VT)))
8273 return DAG.getNode(ISD::FMUL, DL, VT, N0,
8274 DAG.getConstantFP(Recip, DL, VT));
8277 // If this FDIV is part of a reciprocal square root, it may be folded
8278 // into a target-specific square root estimate instruction.
8279 if (N1.getOpcode() == ISD::FSQRT) {
8280 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8281 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8283 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8284 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8285 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8286 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8287 AddToWorklist(RV.getNode());
8288 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8290 } else if (N1.getOpcode() == ISD::FP_ROUND &&
8291 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8292 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8293 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8294 AddToWorklist(RV.getNode());
8295 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8297 } else if (N1.getOpcode() == ISD::FMUL) {
8298 // Look through an FMUL. Even though this won't remove the FDIV directly,
8299 // it's still worthwhile to get rid of the FSQRT if possible.
8302 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8303 SqrtOp = N1.getOperand(0);
8304 OtherOp = N1.getOperand(1);
8305 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8306 SqrtOp = N1.getOperand(1);
8307 OtherOp = N1.getOperand(0);
8309 if (SqrtOp.getNode()) {
8310 // We found a FSQRT, so try to make this fold:
8311 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8312 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8313 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8314 AddToWorklist(RV.getNode());
8315 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8320 // Fold into a reciprocal estimate and multiply instead of a real divide.
8321 if (SDValue RV = BuildReciprocalEstimate(N1)) {
8322 AddToWorklist(RV.getNode());
8323 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8327 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8328 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8329 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8330 // Both can be negated for free, check to see if at least one is cheaper
8332 if (LHSNeg == 2 || RHSNeg == 2)
8333 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8334 GetNegatedExpression(N0, DAG, LegalOperations),
8335 GetNegatedExpression(N1, DAG, LegalOperations));
8339 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8341 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8342 // Notice that this is not always beneficial. One reason is different target
8343 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8344 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8345 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8346 if (Options.UnsafeFPMath) {
8347 // Skip if current node is a reciprocal.
8348 if (N0CFP && N0CFP->isExactlyValue(1.0))
8351 SmallVector<SDNode *, 4> Users;
8352 // Find all FDIV users of the same divisor.
8353 for (auto *U : N1->uses()) {
8354 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8358 if (TLI.combineRepeatedFPDivisors(Users.size())) {
8359 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8360 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8362 // Dividend / Divisor -> Dividend * Reciprocal
8363 for (auto *U : Users) {
8364 SDValue Dividend = U->getOperand(0);
8365 if (Dividend != FPOne) {
8366 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8368 DAG.ReplaceAllUsesWith(U, NewNode.getNode());
8378 SDValue DAGCombiner::visitFREM(SDNode *N) {
8379 SDValue N0 = N->getOperand(0);
8380 SDValue N1 = N->getOperand(1);
8381 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8382 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8383 EVT VT = N->getValueType(0);
8385 // fold (frem c1, c2) -> fmod(c1,c2)
8387 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8392 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8393 if (DAG.getTarget().Options.UnsafeFPMath &&
8394 !TLI.isFsqrtCheap()) {
8395 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8396 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
8397 EVT VT = RV.getValueType();
8399 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8400 AddToWorklist(RV.getNode());
8402 // Unfortunately, RV is now NaN if the input was exactly 0.
8403 // Select out this case and force the answer to 0.
8404 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8406 DAG.getSetCC(DL, TLI.getSetCCResultType(*DAG.getContext(), VT),
8407 N->getOperand(0), Zero, ISD::SETEQ);
8408 AddToWorklist(ZeroCmp.getNode());
8409 AddToWorklist(RV.getNode());
8411 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8412 DL, VT, ZeroCmp, Zero, RV);
8419 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8420 SDValue N0 = N->getOperand(0);
8421 SDValue N1 = N->getOperand(1);
8422 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8423 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8424 EVT VT = N->getValueType(0);
8426 if (N0CFP && N1CFP) // Constant fold
8427 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8430 const APFloat& V = N1CFP->getValueAPF();
8431 // copysign(x, c1) -> fabs(x) iff ispos(c1)
8432 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8433 if (!V.isNegative()) {
8434 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8435 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8437 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8438 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8439 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8443 // copysign(fabs(x), y) -> copysign(x, y)
8444 // copysign(fneg(x), y) -> copysign(x, y)
8445 // copysign(copysign(x,z), y) -> copysign(x, y)
8446 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8447 N0.getOpcode() == ISD::FCOPYSIGN)
8448 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8449 N0.getOperand(0), N1);
8451 // copysign(x, abs(y)) -> abs(x)
8452 if (N1.getOpcode() == ISD::FABS)
8453 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8455 // copysign(x, copysign(y,z)) -> copysign(x, z)
8456 if (N1.getOpcode() == ISD::FCOPYSIGN)
8457 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8458 N0, N1.getOperand(1));
8460 // copysign(x, fp_extend(y)) -> copysign(x, y)
8461 // copysign(x, fp_round(y)) -> copysign(x, y)
8462 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8463 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8464 N0, N1.getOperand(0));
8469 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8470 SDValue N0 = N->getOperand(0);
8471 EVT VT = N->getValueType(0);
8472 EVT OpVT = N0.getValueType();
8474 // fold (sint_to_fp c1) -> c1fp
8475 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8476 // ...but only if the target supports immediate floating-point values
8477 (!LegalOperations ||
8478 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8479 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8481 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8482 // but UINT_TO_FP is legal on this target, try to convert.
8483 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8484 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8485 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8486 if (DAG.SignBitIsZero(N0))
8487 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8490 // The next optimizations are desirable only if SELECT_CC can be lowered.
8491 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8492 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8493 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8495 (!LegalOperations ||
8496 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8499 { N0.getOperand(0), N0.getOperand(1),
8500 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8502 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8505 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8506 // (select_cc x, y, 1.0, 0.0,, cc)
8507 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8508 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8509 (!LegalOperations ||
8510 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8513 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8514 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8515 N0.getOperand(0).getOperand(2) };
8516 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8523 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8524 SDValue N0 = N->getOperand(0);
8525 EVT VT = N->getValueType(0);
8526 EVT OpVT = N0.getValueType();
8528 // fold (uint_to_fp c1) -> c1fp
8529 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8530 // ...but only if the target supports immediate floating-point values
8531 (!LegalOperations ||
8532 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8533 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8535 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8536 // but SINT_TO_FP is legal on this target, try to convert.
8537 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8538 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8539 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8540 if (DAG.SignBitIsZero(N0))
8541 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8544 // The next optimizations are desirable only if SELECT_CC can be lowered.
8545 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8546 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8548 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8549 (!LegalOperations ||
8550 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8553 { N0.getOperand(0), N0.getOperand(1),
8554 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8556 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8563 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8564 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8565 SDValue N0 = N->getOperand(0);
8566 EVT VT = N->getValueType(0);
8568 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8571 SDValue Src = N0.getOperand(0);
8572 EVT SrcVT = Src.getValueType();
8573 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8574 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8576 // We can safely assume the conversion won't overflow the output range,
8577 // because (for example) (uint8_t)18293.f is undefined behavior.
8579 // Since we can assume the conversion won't overflow, our decision as to
8580 // whether the input will fit in the float should depend on the minimum
8581 // of the input range and output range.
8583 // This means this is also safe for a signed input and unsigned output, since
8584 // a negative input would lead to undefined behavior.
8585 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8586 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8587 unsigned ActualSize = std::min(InputSize, OutputSize);
8588 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8590 // We can only fold away the float conversion if the input range can be
8591 // represented exactly in the float range.
8592 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8593 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8594 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8596 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8598 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8599 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8602 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8607 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8608 SDValue N0 = N->getOperand(0);
8609 EVT VT = N->getValueType(0);
8611 // fold (fp_to_sint c1fp) -> c1
8612 if (isConstantFPBuildVectorOrConstantFP(N0))
8613 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8615 return FoldIntToFPToInt(N, DAG);
8618 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8619 SDValue N0 = N->getOperand(0);
8620 EVT VT = N->getValueType(0);
8622 // fold (fp_to_uint c1fp) -> c1
8623 if (isConstantFPBuildVectorOrConstantFP(N0))
8624 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8626 return FoldIntToFPToInt(N, DAG);
8629 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8630 SDValue N0 = N->getOperand(0);
8631 SDValue N1 = N->getOperand(1);
8632 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8633 EVT VT = N->getValueType(0);
8635 // fold (fp_round c1fp) -> c1fp
8637 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8639 // fold (fp_round (fp_extend x)) -> x
8640 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8641 return N0.getOperand(0);
8643 // fold (fp_round (fp_round x)) -> (fp_round x)
8644 if (N0.getOpcode() == ISD::FP_ROUND) {
8645 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8646 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8647 // If the first fp_round isn't a value preserving truncation, it might
8648 // introduce a tie in the second fp_round, that wouldn't occur in the
8649 // single-step fp_round we want to fold to.
8650 // In other words, double rounding isn't the same as rounding.
8651 // Also, this is a value preserving truncation iff both fp_round's are.
8652 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8654 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8655 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8659 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8660 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8661 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8662 N0.getOperand(0), N1);
8663 AddToWorklist(Tmp.getNode());
8664 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8665 Tmp, N0.getOperand(1));
8671 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8672 SDValue N0 = N->getOperand(0);
8673 EVT VT = N->getValueType(0);
8674 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8675 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8677 // fold (fp_round_inreg c1fp) -> c1fp
8678 if (N0CFP && isTypeLegal(EVT)) {
8680 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8681 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8687 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8688 SDValue N0 = N->getOperand(0);
8689 EVT VT = N->getValueType(0);
8691 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8692 if (N->hasOneUse() &&
8693 N->use_begin()->getOpcode() == ISD::FP_ROUND)
8696 // fold (fp_extend c1fp) -> c1fp
8697 if (isConstantFPBuildVectorOrConstantFP(N0))
8698 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8700 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8701 if (N0.getOpcode() == ISD::FP16_TO_FP &&
8702 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8703 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8705 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8707 if (N0.getOpcode() == ISD::FP_ROUND
8708 && N0.getNode()->getConstantOperandVal(1) == 1) {
8709 SDValue In = N0.getOperand(0);
8710 if (In.getValueType() == VT) return In;
8711 if (VT.bitsLT(In.getValueType()))
8712 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8713 In, N0.getOperand(1));
8714 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8717 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8718 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8719 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8720 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8721 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8723 LN0->getBasePtr(), N0.getValueType(),
8724 LN0->getMemOperand());
8725 CombineTo(N, ExtLoad);
8726 CombineTo(N0.getNode(),
8727 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8728 N0.getValueType(), ExtLoad,
8729 DAG.getIntPtrConstant(1, SDLoc(N0))),
8730 ExtLoad.getValue(1));
8731 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8737 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8738 SDValue N0 = N->getOperand(0);
8739 EVT VT = N->getValueType(0);
8741 // fold (fceil c1) -> fceil(c1)
8742 if (isConstantFPBuildVectorOrConstantFP(N0))
8743 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8748 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8749 SDValue N0 = N->getOperand(0);
8750 EVT VT = N->getValueType(0);
8752 // fold (ftrunc c1) -> ftrunc(c1)
8753 if (isConstantFPBuildVectorOrConstantFP(N0))
8754 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8759 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8760 SDValue N0 = N->getOperand(0);
8761 EVT VT = N->getValueType(0);
8763 // fold (ffloor c1) -> ffloor(c1)
8764 if (isConstantFPBuildVectorOrConstantFP(N0))
8765 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8770 // FIXME: FNEG and FABS have a lot in common; refactor.
8771 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8772 SDValue N0 = N->getOperand(0);
8773 EVT VT = N->getValueType(0);
8775 // Constant fold FNEG.
8776 if (isConstantFPBuildVectorOrConstantFP(N0))
8777 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8779 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8780 &DAG.getTarget().Options))
8781 return GetNegatedExpression(N0, DAG, LegalOperations);
8783 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8784 // constant pool values.
8785 if (!TLI.isFNegFree(VT) &&
8786 N0.getOpcode() == ISD::BITCAST &&
8787 N0.getNode()->hasOneUse()) {
8788 SDValue Int = N0.getOperand(0);
8789 EVT IntVT = Int.getValueType();
8790 if (IntVT.isInteger() && !IntVT.isVector()) {
8792 if (N0.getValueType().isVector()) {
8793 // For a vector, get a mask such as 0x80... per scalar element
8795 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8796 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8798 // For a scalar, just generate 0x80...
8799 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8802 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8803 DAG.getConstant(SignMask, DL0, IntVT));
8804 AddToWorklist(Int.getNode());
8805 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8809 // (fneg (fmul c, x)) -> (fmul -c, x)
8810 if (N0.getOpcode() == ISD::FMUL &&
8811 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
8812 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8814 APFloat CVal = CFP1->getValueAPF();
8816 if (Level >= AfterLegalizeDAG &&
8817 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8818 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8820 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8821 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8828 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8829 SDValue N0 = N->getOperand(0);
8830 SDValue N1 = N->getOperand(1);
8831 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8832 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8834 if (N0CFP && N1CFP) {
8835 const APFloat &C0 = N0CFP->getValueAPF();
8836 const APFloat &C1 = N1CFP->getValueAPF();
8837 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8841 EVT VT = N->getValueType(0);
8842 // Canonicalize to constant on RHS.
8843 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8849 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8850 SDValue N0 = N->getOperand(0);
8851 SDValue N1 = N->getOperand(1);
8852 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8853 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8855 if (N0CFP && N1CFP) {
8856 const APFloat &C0 = N0CFP->getValueAPF();
8857 const APFloat &C1 = N1CFP->getValueAPF();
8858 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8862 EVT VT = N->getValueType(0);
8863 // Canonicalize to constant on RHS.
8864 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8870 SDValue DAGCombiner::visitFABS(SDNode *N) {
8871 SDValue N0 = N->getOperand(0);
8872 EVT VT = N->getValueType(0);
8874 // fold (fabs c1) -> fabs(c1)
8875 if (isConstantFPBuildVectorOrConstantFP(N0))
8876 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8878 // fold (fabs (fabs x)) -> (fabs x)
8879 if (N0.getOpcode() == ISD::FABS)
8880 return N->getOperand(0);
8882 // fold (fabs (fneg x)) -> (fabs x)
8883 // fold (fabs (fcopysign x, y)) -> (fabs x)
8884 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8885 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8887 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8888 // constant pool values.
8889 if (!TLI.isFAbsFree(VT) &&
8890 N0.getOpcode() == ISD::BITCAST &&
8891 N0.getNode()->hasOneUse()) {
8892 SDValue Int = N0.getOperand(0);
8893 EVT IntVT = Int.getValueType();
8894 if (IntVT.isInteger() && !IntVT.isVector()) {
8896 if (N0.getValueType().isVector()) {
8897 // For a vector, get a mask such as 0x7f... per scalar element
8899 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8900 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8902 // For a scalar, just generate 0x7f...
8903 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8906 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8907 DAG.getConstant(SignMask, DL, IntVT));
8908 AddToWorklist(Int.getNode());
8909 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8916 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8917 SDValue Chain = N->getOperand(0);
8918 SDValue N1 = N->getOperand(1);
8919 SDValue N2 = N->getOperand(2);
8921 // If N is a constant we could fold this into a fallthrough or unconditional
8922 // branch. However that doesn't happen very often in normal code, because
8923 // Instcombine/SimplifyCFG should have handled the available opportunities.
8924 // If we did this folding here, it would be necessary to update the
8925 // MachineBasicBlock CFG, which is awkward.
8927 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8929 if (N1.getOpcode() == ISD::SETCC &&
8930 TLI.isOperationLegalOrCustom(ISD::BR_CC,
8931 N1.getOperand(0).getValueType())) {
8932 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8933 Chain, N1.getOperand(2),
8934 N1.getOperand(0), N1.getOperand(1), N2);
8937 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8938 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8939 (N1.getOperand(0).hasOneUse() &&
8940 N1.getOperand(0).getOpcode() == ISD::SRL))) {
8941 SDNode *Trunc = nullptr;
8942 if (N1.getOpcode() == ISD::TRUNCATE) {
8943 // Look pass the truncate.
8944 Trunc = N1.getNode();
8945 N1 = N1.getOperand(0);
8948 // Match this pattern so that we can generate simpler code:
8951 // %b = and i32 %a, 2
8952 // %c = srl i32 %b, 1
8953 // brcond i32 %c ...
8958 // %b = and i32 %a, 2
8959 // %c = setcc eq %b, 0
8962 // This applies only when the AND constant value has one bit set and the
8963 // SRL constant is equal to the log2 of the AND constant. The back-end is
8964 // smart enough to convert the result into a TEST/JMP sequence.
8965 SDValue Op0 = N1.getOperand(0);
8966 SDValue Op1 = N1.getOperand(1);
8968 if (Op0.getOpcode() == ISD::AND &&
8969 Op1.getOpcode() == ISD::Constant) {
8970 SDValue AndOp1 = Op0.getOperand(1);
8972 if (AndOp1.getOpcode() == ISD::Constant) {
8973 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8975 if (AndConst.isPowerOf2() &&
8976 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8980 getSetCCResultType(Op0.getValueType()),
8981 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
8984 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
8985 MVT::Other, Chain, SetCC, N2);
8986 // Don't add the new BRCond into the worklist or else SimplifySelectCC
8987 // will convert it back to (X & C1) >> C2.
8988 CombineTo(N, NewBRCond, false);
8989 // Truncate is dead.
8991 deleteAndRecombine(Trunc);
8992 // Replace the uses of SRL with SETCC
8993 WorklistRemover DeadNodes(*this);
8994 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8995 deleteAndRecombine(N1.getNode());
8996 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9002 // Restore N1 if the above transformation doesn't match.
9003 N1 = N->getOperand(1);
9006 // Transform br(xor(x, y)) -> br(x != y)
9007 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9008 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9009 SDNode *TheXor = N1.getNode();
9010 SDValue Op0 = TheXor->getOperand(0);
9011 SDValue Op1 = TheXor->getOperand(1);
9012 if (Op0.getOpcode() == Op1.getOpcode()) {
9013 // Avoid missing important xor optimizations.
9014 SDValue Tmp = visitXOR(TheXor);
9015 if (Tmp.getNode()) {
9016 if (Tmp.getNode() != TheXor) {
9017 DEBUG(dbgs() << "\nReplacing.8 ";
9019 dbgs() << "\nWith: ";
9020 Tmp.getNode()->dump(&DAG);
9022 WorklistRemover DeadNodes(*this);
9023 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9024 deleteAndRecombine(TheXor);
9025 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9026 MVT::Other, Chain, Tmp, N2);
9029 // visitXOR has changed XOR's operands or replaced the XOR completely,
9031 return SDValue(N, 0);
9035 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9037 if (isOneConstant(Op0) && Op0.hasOneUse() &&
9038 Op0.getOpcode() == ISD::XOR) {
9039 TheXor = Op0.getNode();
9043 EVT SetCCVT = N1.getValueType();
9045 SetCCVT = getSetCCResultType(SetCCVT);
9046 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9049 Equal ? ISD::SETEQ : ISD::SETNE);
9050 // Replace the uses of XOR with SETCC
9051 WorklistRemover DeadNodes(*this);
9052 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9053 deleteAndRecombine(N1.getNode());
9054 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9055 MVT::Other, Chain, SetCC, N2);
9062 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9064 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9065 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9066 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9068 // If N is a constant we could fold this into a fallthrough or unconditional
9069 // branch. However that doesn't happen very often in normal code, because
9070 // Instcombine/SimplifyCFG should have handled the available opportunities.
9071 // If we did this folding here, it would be necessary to update the
9072 // MachineBasicBlock CFG, which is awkward.
9074 // Use SimplifySetCC to simplify SETCC's.
9075 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9076 CondLHS, CondRHS, CC->get(), SDLoc(N),
9078 if (Simp.getNode()) AddToWorklist(Simp.getNode());
9080 // fold to a simpler setcc
9081 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9082 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9083 N->getOperand(0), Simp.getOperand(2),
9084 Simp.getOperand(0), Simp.getOperand(1),
9090 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9091 /// and that N may be folded in the load / store addressing mode.
9092 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9094 const TargetLowering &TLI) {
9098 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
9099 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9101 VT = LD->getMemoryVT();
9102 AS = LD->getAddressSpace();
9103 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
9104 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9106 VT = ST->getMemoryVT();
9107 AS = ST->getAddressSpace();
9111 TargetLowering::AddrMode AM;
9112 if (N->getOpcode() == ISD::ADD) {
9113 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9116 AM.BaseOffs = Offset->getSExtValue();
9120 } else if (N->getOpcode() == ISD::SUB) {
9121 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9124 AM.BaseOffs = -Offset->getSExtValue();
9131 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()), AS);
9134 /// Try turning a load/store into a pre-indexed load/store when the base
9135 /// pointer is an add or subtract and it has other uses besides the load/store.
9136 /// After the transformation, the new indexed load/store has effectively folded
9137 /// the add/subtract in and all of its other uses are redirected to the
9139 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9140 if (Level < AfterLegalizeDAG)
9146 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9147 if (LD->isIndexed())
9149 VT = LD->getMemoryVT();
9150 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9151 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9153 Ptr = LD->getBasePtr();
9154 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9155 if (ST->isIndexed())
9157 VT = ST->getMemoryVT();
9158 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9159 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9161 Ptr = ST->getBasePtr();
9167 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9168 // out. There is no reason to make this a preinc/predec.
9169 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9170 Ptr.getNode()->hasOneUse())
9173 // Ask the target to do addressing mode selection.
9176 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9177 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9180 // Backends without true r+i pre-indexed forms may need to pass a
9181 // constant base with a variable offset so that constant coercion
9182 // will work with the patterns in canonical form.
9183 bool Swapped = false;
9184 if (isa<ConstantSDNode>(BasePtr)) {
9185 std::swap(BasePtr, Offset);
9189 // Don't create a indexed load / store with zero offset.
9190 if (isNullConstant(Offset))
9193 // Try turning it into a pre-indexed load / store except when:
9194 // 1) The new base ptr is a frame index.
9195 // 2) If N is a store and the new base ptr is either the same as or is a
9196 // predecessor of the value being stored.
9197 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9198 // that would create a cycle.
9199 // 4) All uses are load / store ops that use it as old base ptr.
9201 // Check #1. Preinc'ing a frame index would require copying the stack pointer
9202 // (plus the implicit offset) to a register to preinc anyway.
9203 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9208 SDValue Val = cast<StoreSDNode>(N)->getValue();
9209 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9213 // If the offset is a constant, there may be other adds of constants that
9214 // can be folded with this one. We should do this to avoid having to keep
9215 // a copy of the original base pointer.
9216 SmallVector<SDNode *, 16> OtherUses;
9217 if (isa<ConstantSDNode>(Offset))
9218 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9219 UE = BasePtr.getNode()->use_end();
9221 SDUse &Use = UI.getUse();
9222 // Skip the use that is Ptr and uses of other results from BasePtr's
9223 // node (important for nodes that return multiple results).
9224 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9227 if (Use.getUser()->isPredecessorOf(N))
9230 if (Use.getUser()->getOpcode() != ISD::ADD &&
9231 Use.getUser()->getOpcode() != ISD::SUB) {
9236 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9237 if (!isa<ConstantSDNode>(Op1)) {
9242 // FIXME: In some cases, we can be smarter about this.
9243 if (Op1.getValueType() != Offset.getValueType()) {
9248 OtherUses.push_back(Use.getUser());
9252 std::swap(BasePtr, Offset);
9254 // Now check for #3 and #4.
9255 bool RealUse = false;
9257 // Caches for hasPredecessorHelper
9258 SmallPtrSet<const SDNode *, 32> Visited;
9259 SmallVector<const SDNode *, 16> Worklist;
9261 for (SDNode *Use : Ptr.getNode()->uses()) {
9264 if (N->hasPredecessorHelper(Use, Visited, Worklist))
9267 // If Ptr may be folded in addressing mode of other use, then it's
9268 // not profitable to do this transformation.
9269 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9278 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9279 BasePtr, Offset, AM);
9281 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9282 BasePtr, Offset, AM);
9285 DEBUG(dbgs() << "\nReplacing.4 ";
9287 dbgs() << "\nWith: ";
9288 Result.getNode()->dump(&DAG);
9290 WorklistRemover DeadNodes(*this);
9292 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9293 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9295 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9298 // Finally, since the node is now dead, remove it from the graph.
9299 deleteAndRecombine(N);
9302 std::swap(BasePtr, Offset);
9304 // Replace other uses of BasePtr that can be updated to use Ptr
9305 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9306 unsigned OffsetIdx = 1;
9307 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9309 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9310 BasePtr.getNode() && "Expected BasePtr operand");
9312 // We need to replace ptr0 in the following expression:
9313 // x0 * offset0 + y0 * ptr0 = t0
9315 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9317 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9318 // indexed load/store and the expresion that needs to be re-written.
9320 // Therefore, we have:
9321 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9323 ConstantSDNode *CN =
9324 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9326 APInt Offset0 = CN->getAPIntValue();
9327 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9329 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9330 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9331 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9332 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9334 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9336 APInt CNV = Offset0;
9337 if (X0 < 0) CNV = -CNV;
9338 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9339 else CNV = CNV - Offset1;
9341 SDLoc DL(OtherUses[i]);
9343 // We can now generate the new expression.
9344 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9345 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9347 SDValue NewUse = DAG.getNode(Opcode,
9349 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9350 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9351 deleteAndRecombine(OtherUses[i]);
9354 // Replace the uses of Ptr with uses of the updated base value.
9355 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9356 deleteAndRecombine(Ptr.getNode());
9361 /// Try to combine a load/store with a add/sub of the base pointer node into a
9362 /// post-indexed load/store. The transformation folded the add/subtract into the
9363 /// new indexed load/store effectively and all of its uses are redirected to the
9365 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9366 if (Level < AfterLegalizeDAG)
9372 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9373 if (LD->isIndexed())
9375 VT = LD->getMemoryVT();
9376 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9377 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9379 Ptr = LD->getBasePtr();
9380 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9381 if (ST->isIndexed())
9383 VT = ST->getMemoryVT();
9384 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9385 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9387 Ptr = ST->getBasePtr();
9393 if (Ptr.getNode()->hasOneUse())
9396 for (SDNode *Op : Ptr.getNode()->uses()) {
9398 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9403 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9404 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9405 // Don't create a indexed load / store with zero offset.
9406 if (isNullConstant(Offset))
9409 // Try turning it into a post-indexed load / store except when
9410 // 1) All uses are load / store ops that use it as base ptr (and
9411 // it may be folded as addressing mmode).
9412 // 2) Op must be independent of N, i.e. Op is neither a predecessor
9413 // nor a successor of N. Otherwise, if Op is folded that would
9416 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9420 bool TryNext = false;
9421 for (SDNode *Use : BasePtr.getNode()->uses()) {
9422 if (Use == Ptr.getNode())
9425 // If all the uses are load / store addresses, then don't do the
9427 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9428 bool RealUse = false;
9429 for (SDNode *UseUse : Use->uses()) {
9430 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9445 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9446 SDValue Result = isLoad
9447 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9448 BasePtr, Offset, AM)
9449 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9450 BasePtr, Offset, AM);
9453 DEBUG(dbgs() << "\nReplacing.5 ";
9455 dbgs() << "\nWith: ";
9456 Result.getNode()->dump(&DAG);
9458 WorklistRemover DeadNodes(*this);
9460 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9461 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9463 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9466 // Finally, since the node is now dead, remove it from the graph.
9467 deleteAndRecombine(N);
9469 // Replace the uses of Use with uses of the updated base value.
9470 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9471 Result.getValue(isLoad ? 1 : 0));
9472 deleteAndRecombine(Op);
9481 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9482 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9483 ISD::MemIndexedMode AM = LD->getAddressingMode();
9484 assert(AM != ISD::UNINDEXED);
9485 SDValue BP = LD->getOperand(1);
9486 SDValue Inc = LD->getOperand(2);
9488 // Some backends use TargetConstants for load offsets, but don't expect
9489 // TargetConstants in general ADD nodes. We can convert these constants into
9490 // regular Constants (if the constant is not opaque).
9491 assert((Inc.getOpcode() != ISD::TargetConstant ||
9492 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9493 "Cannot split out indexing using opaque target constants");
9494 if (Inc.getOpcode() == ISD::TargetConstant) {
9495 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9496 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9497 ConstInc->getValueType(0));
9501 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9502 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9505 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9506 LoadSDNode *LD = cast<LoadSDNode>(N);
9507 SDValue Chain = LD->getChain();
9508 SDValue Ptr = LD->getBasePtr();
9510 // If load is not volatile and there are no uses of the loaded value (and
9511 // the updated indexed value in case of indexed loads), change uses of the
9512 // chain value into uses of the chain input (i.e. delete the dead load).
9513 if (!LD->isVolatile()) {
9514 if (N->getValueType(1) == MVT::Other) {
9516 if (!N->hasAnyUseOfValue(0)) {
9517 // It's not safe to use the two value CombineTo variant here. e.g.
9518 // v1, chain2 = load chain1, loc
9519 // v2, chain3 = load chain2, loc
9521 // Now we replace use of chain2 with chain1. This makes the second load
9522 // isomorphic to the one we are deleting, and thus makes this load live.
9523 DEBUG(dbgs() << "\nReplacing.6 ";
9525 dbgs() << "\nWith chain: ";
9526 Chain.getNode()->dump(&DAG);
9528 WorklistRemover DeadNodes(*this);
9529 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9532 deleteAndRecombine(N);
9534 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9538 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9540 // If this load has an opaque TargetConstant offset, then we cannot split
9541 // the indexing into an add/sub directly (that TargetConstant may not be
9542 // valid for a different type of node, and we cannot convert an opaque
9543 // target constant into a regular constant).
9544 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9545 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9547 if (!N->hasAnyUseOfValue(0) &&
9548 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9549 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9551 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9552 Index = SplitIndexingFromLoad(LD);
9553 // Try to fold the base pointer arithmetic into subsequent loads and
9555 AddUsersToWorklist(N);
9557 Index = DAG.getUNDEF(N->getValueType(1));
9558 DEBUG(dbgs() << "\nReplacing.7 ";
9560 dbgs() << "\nWith: ";
9561 Undef.getNode()->dump(&DAG);
9562 dbgs() << " and 2 other values\n");
9563 WorklistRemover DeadNodes(*this);
9564 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9565 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9566 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9567 deleteAndRecombine(N);
9568 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9573 // If this load is directly stored, replace the load value with the stored
9575 // TODO: Handle store large -> read small portion.
9576 // TODO: Handle TRUNCSTORE/LOADEXT
9577 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9578 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9579 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9580 if (PrevST->getBasePtr() == Ptr &&
9581 PrevST->getValue().getValueType() == N->getValueType(0))
9582 return CombineTo(N, Chain.getOperand(1), Chain);
9586 // Try to infer better alignment information than the load already has.
9587 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9588 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9589 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9591 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9592 LD->getValueType(0),
9593 Chain, Ptr, LD->getPointerInfo(),
9595 LD->isVolatile(), LD->isNonTemporal(),
9596 LD->isInvariant(), Align, LD->getAAInfo());
9597 if (NewLoad.getNode() != N)
9598 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9603 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9604 : DAG.getSubtarget().useAA();
9606 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9607 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9610 if (UseAA && LD->isUnindexed()) {
9611 // Walk up chain skipping non-aliasing memory nodes.
9612 SDValue BetterChain = FindBetterChain(N, Chain);
9614 // If there is a better chain.
9615 if (Chain != BetterChain) {
9618 // Replace the chain to void dependency.
9619 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9620 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9621 BetterChain, Ptr, LD->getMemOperand());
9623 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9624 LD->getValueType(0),
9625 BetterChain, Ptr, LD->getMemoryVT(),
9626 LD->getMemOperand());
9629 // Create token factor to keep old chain connected.
9630 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9631 MVT::Other, Chain, ReplLoad.getValue(1));
9633 // Make sure the new and old chains are cleaned up.
9634 AddToWorklist(Token.getNode());
9636 // Replace uses with load result and token factor. Don't add users
9638 return CombineTo(N, ReplLoad.getValue(0), Token, false);
9642 // Try transforming N to an indexed load.
9643 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9644 return SDValue(N, 0);
9646 // Try to slice up N to more direct loads if the slices are mapped to
9647 // different register banks or pairing can take place.
9649 return SDValue(N, 0);
9655 /// \brief Helper structure used to slice a load in smaller loads.
9656 /// Basically a slice is obtained from the following sequence:
9657 /// Origin = load Ty1, Base
9658 /// Shift = srl Ty1 Origin, CstTy Amount
9659 /// Inst = trunc Shift to Ty2
9661 /// Then, it will be rewriten into:
9662 /// Slice = load SliceTy, Base + SliceOffset
9663 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9665 /// SliceTy is deduced from the number of bits that are actually used to
9667 struct LoadedSlice {
9668 /// \brief Helper structure used to compute the cost of a slice.
9670 /// Are we optimizing for code size.
9675 unsigned CrossRegisterBanksCopies;
9679 Cost(bool ForCodeSize = false)
9680 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9681 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9683 /// \brief Get the cost of one isolated slice.
9684 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9685 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9686 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9687 EVT TruncType = LS.Inst->getValueType(0);
9688 EVT LoadedType = LS.getLoadedType();
9689 if (TruncType != LoadedType &&
9690 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9694 /// \brief Account for slicing gain in the current cost.
9695 /// Slicing provide a few gains like removing a shift or a
9696 /// truncate. This method allows to grow the cost of the original
9697 /// load with the gain from this slice.
9698 void addSliceGain(const LoadedSlice &LS) {
9699 // Each slice saves a truncate.
9700 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9701 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9702 LS.Inst->getOperand(0).getValueType()))
9704 // If there is a shift amount, this slice gets rid of it.
9707 // If this slice can merge a cross register bank copy, account for it.
9708 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9709 ++CrossRegisterBanksCopies;
9712 Cost &operator+=(const Cost &RHS) {
9714 Truncates += RHS.Truncates;
9715 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9721 bool operator==(const Cost &RHS) const {
9722 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9723 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9724 ZExts == RHS.ZExts && Shift == RHS.Shift;
9727 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9729 bool operator<(const Cost &RHS) const {
9730 // Assume cross register banks copies are as expensive as loads.
9731 // FIXME: Do we want some more target hooks?
9732 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9733 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9734 // Unless we are optimizing for code size, consider the
9735 // expensive operation first.
9736 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9737 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9738 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9739 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9742 bool operator>(const Cost &RHS) const { return RHS < *this; }
9744 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9746 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9748 // The last instruction that represent the slice. This should be a
9749 // truncate instruction.
9751 // The original load instruction.
9753 // The right shift amount in bits from the original load.
9755 // The DAG from which Origin came from.
9756 // This is used to get some contextual information about legal types, etc.
9759 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9760 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9761 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9763 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9764 /// \return Result is \p BitWidth and has used bits set to 1 and
9765 /// not used bits set to 0.
9766 APInt getUsedBits() const {
9767 // Reproduce the trunc(lshr) sequence:
9768 // - Start from the truncated value.
9769 // - Zero extend to the desired bit width.
9771 assert(Origin && "No original load to compare against.");
9772 unsigned BitWidth = Origin->getValueSizeInBits(0);
9773 assert(Inst && "This slice is not bound to an instruction");
9774 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9775 "Extracted slice is bigger than the whole type!");
9776 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9777 UsedBits.setAllBits();
9778 UsedBits = UsedBits.zext(BitWidth);
9783 /// \brief Get the size of the slice to be loaded in bytes.
9784 unsigned getLoadedSize() const {
9785 unsigned SliceSize = getUsedBits().countPopulation();
9786 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9787 return SliceSize / 8;
9790 /// \brief Get the type that will be loaded for this slice.
9791 /// Note: This may not be the final type for the slice.
9792 EVT getLoadedType() const {
9793 assert(DAG && "Missing context");
9794 LLVMContext &Ctxt = *DAG->getContext();
9795 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9798 /// \brief Get the alignment of the load used for this slice.
9799 unsigned getAlignment() const {
9800 unsigned Alignment = Origin->getAlignment();
9801 unsigned Offset = getOffsetFromBase();
9803 Alignment = MinAlign(Alignment, Alignment + Offset);
9807 /// \brief Check if this slice can be rewritten with legal operations.
9808 bool isLegal() const {
9809 // An invalid slice is not legal.
9810 if (!Origin || !Inst || !DAG)
9813 // Offsets are for indexed load only, we do not handle that.
9814 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9817 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9819 // Check that the type is legal.
9820 EVT SliceType = getLoadedType();
9821 if (!TLI.isTypeLegal(SliceType))
9824 // Check that the load is legal for this type.
9825 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9828 // Check that the offset can be computed.
9829 // 1. Check its type.
9830 EVT PtrType = Origin->getBasePtr().getValueType();
9831 if (PtrType == MVT::Untyped || PtrType.isExtended())
9834 // 2. Check that it fits in the immediate.
9835 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9838 // 3. Check that the computation is legal.
9839 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9842 // Check that the zext is legal if it needs one.
9843 EVT TruncateType = Inst->getValueType(0);
9844 if (TruncateType != SliceType &&
9845 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9851 /// \brief Get the offset in bytes of this slice in the original chunk of
9853 /// \pre DAG != nullptr.
9854 uint64_t getOffsetFromBase() const {
9855 assert(DAG && "Missing context.");
9857 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9858 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9859 uint64_t Offset = Shift / 8;
9860 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9861 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9862 "The size of the original loaded type is not a multiple of a"
9864 // If Offset is bigger than TySizeInBytes, it means we are loading all
9865 // zeros. This should have been optimized before in the process.
9866 assert(TySizeInBytes > Offset &&
9867 "Invalid shift amount for given loaded size");
9869 Offset = TySizeInBytes - Offset - getLoadedSize();
9873 /// \brief Generate the sequence of instructions to load the slice
9874 /// represented by this object and redirect the uses of this slice to
9875 /// this new sequence of instructions.
9876 /// \pre this->Inst && this->Origin are valid Instructions and this
9877 /// object passed the legal check: LoadedSlice::isLegal returned true.
9878 /// \return The last instruction of the sequence used to load the slice.
9879 SDValue loadSlice() const {
9880 assert(Inst && Origin && "Unable to replace a non-existing slice.");
9881 const SDValue &OldBaseAddr = Origin->getBasePtr();
9882 SDValue BaseAddr = OldBaseAddr;
9883 // Get the offset in that chunk of bytes w.r.t. the endianess.
9884 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9885 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9887 // BaseAddr = BaseAddr + Offset.
9888 EVT ArithType = BaseAddr.getValueType();
9890 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9891 DAG->getConstant(Offset, DL, ArithType));
9894 // Create the type of the loaded slice according to its size.
9895 EVT SliceType = getLoadedType();
9897 // Create the load for the slice.
9898 SDValue LastInst = DAG->getLoad(
9899 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9900 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9901 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9902 // If the final type is not the same as the loaded type, this means that
9903 // we have to pad with zero. Create a zero extend for that.
9904 EVT FinalType = Inst->getValueType(0);
9905 if (SliceType != FinalType)
9907 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9911 /// \brief Check if this slice can be merged with an expensive cross register
9912 /// bank copy. E.g.,
9914 /// f = bitcast i32 i to float
9915 bool canMergeExpensiveCrossRegisterBankCopy() const {
9916 if (!Inst || !Inst->hasOneUse())
9918 SDNode *Use = *Inst->use_begin();
9919 if (Use->getOpcode() != ISD::BITCAST)
9921 assert(DAG && "Missing context");
9922 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9923 EVT ResVT = Use->getValueType(0);
9924 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9925 const TargetRegisterClass *ArgRC =
9926 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9927 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9930 // At this point, we know that we perform a cross-register-bank copy.
9931 // Check if it is expensive.
9932 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9933 // Assume bitcasts are cheap, unless both register classes do not
9934 // explicitly share a common sub class.
9935 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9938 // Check if it will be merged with the load.
9939 // 1. Check the alignment constraint.
9940 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9941 ResVT.getTypeForEVT(*DAG->getContext()));
9943 if (RequiredAlignment > getAlignment())
9946 // 2. Check that the load is a legal operation for that type.
9947 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9950 // 3. Check that we do not have a zext in the way.
9951 if (Inst->getValueType(0) != getLoadedType())
9959 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9960 /// \p UsedBits looks like 0..0 1..1 0..0.
9961 static bool areUsedBitsDense(const APInt &UsedBits) {
9962 // If all the bits are one, this is dense!
9963 if (UsedBits.isAllOnesValue())
9966 // Get rid of the unused bits on the right.
9967 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9968 // Get rid of the unused bits on the left.
9969 if (NarrowedUsedBits.countLeadingZeros())
9970 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9971 // Check that the chunk of bits is completely used.
9972 return NarrowedUsedBits.isAllOnesValue();
9975 /// \brief Check whether or not \p First and \p Second are next to each other
9976 /// in memory. This means that there is no hole between the bits loaded
9977 /// by \p First and the bits loaded by \p Second.
9978 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9979 const LoadedSlice &Second) {
9980 assert(First.Origin == Second.Origin && First.Origin &&
9981 "Unable to match different memory origins.");
9982 APInt UsedBits = First.getUsedBits();
9983 assert((UsedBits & Second.getUsedBits()) == 0 &&
9984 "Slices are not supposed to overlap.");
9985 UsedBits |= Second.getUsedBits();
9986 return areUsedBitsDense(UsedBits);
9989 /// \brief Adjust the \p GlobalLSCost according to the target
9990 /// paring capabilities and the layout of the slices.
9991 /// \pre \p GlobalLSCost should account for at least as many loads as
9992 /// there is in the slices in \p LoadedSlices.
9993 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9994 LoadedSlice::Cost &GlobalLSCost) {
9995 unsigned NumberOfSlices = LoadedSlices.size();
9996 // If there is less than 2 elements, no pairing is possible.
9997 if (NumberOfSlices < 2)
10000 // Sort the slices so that elements that are likely to be next to each
10001 // other in memory are next to each other in the list.
10002 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10003 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10004 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10005 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10007 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10008 // First (resp. Second) is the first (resp. Second) potentially candidate
10009 // to be placed in a paired load.
10010 const LoadedSlice *First = nullptr;
10011 const LoadedSlice *Second = nullptr;
10012 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10013 // Set the beginning of the pair.
10016 Second = &LoadedSlices[CurrSlice];
10018 // If First is NULL, it means we start a new pair.
10019 // Get to the next slice.
10023 EVT LoadedType = First->getLoadedType();
10025 // If the types of the slices are different, we cannot pair them.
10026 if (LoadedType != Second->getLoadedType())
10029 // Check if the target supplies paired loads for this type.
10030 unsigned RequiredAlignment = 0;
10031 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10032 // move to the next pair, this type is hopeless.
10036 // Check if we meet the alignment requirement.
10037 if (RequiredAlignment > First->getAlignment())
10040 // Check that both loads are next to each other in memory.
10041 if (!areSlicesNextToEachOther(*First, *Second))
10044 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10045 --GlobalLSCost.Loads;
10046 // Move to the next pair.
10051 /// \brief Check the profitability of all involved LoadedSlice.
10052 /// Currently, it is considered profitable if there is exactly two
10053 /// involved slices (1) which are (2) next to each other in memory, and
10054 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10056 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10057 /// the elements themselves.
10059 /// FIXME: When the cost model will be mature enough, we can relax
10060 /// constraints (1) and (2).
10061 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10062 const APInt &UsedBits, bool ForCodeSize) {
10063 unsigned NumberOfSlices = LoadedSlices.size();
10064 if (StressLoadSlicing)
10065 return NumberOfSlices > 1;
10068 if (NumberOfSlices != 2)
10072 if (!areUsedBitsDense(UsedBits))
10076 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10077 // The original code has one big load.
10078 OrigCost.Loads = 1;
10079 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10080 const LoadedSlice &LS = LoadedSlices[CurrSlice];
10081 // Accumulate the cost of all the slices.
10082 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10083 GlobalSlicingCost += SliceCost;
10085 // Account as cost in the original configuration the gain obtained
10086 // with the current slices.
10087 OrigCost.addSliceGain(LS);
10090 // If the target supports paired load, adjust the cost accordingly.
10091 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10092 return OrigCost > GlobalSlicingCost;
10095 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10096 /// operations, split it in the various pieces being extracted.
10098 /// This sort of thing is introduced by SROA.
10099 /// This slicing takes care not to insert overlapping loads.
10100 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10101 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10102 if (Level < AfterLegalizeDAG)
10105 LoadSDNode *LD = cast<LoadSDNode>(N);
10106 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10107 !LD->getValueType(0).isInteger())
10110 // Keep track of already used bits to detect overlapping values.
10111 // In that case, we will just abort the transformation.
10112 APInt UsedBits(LD->getValueSizeInBits(0), 0);
10114 SmallVector<LoadedSlice, 4> LoadedSlices;
10116 // Check if this load is used as several smaller chunks of bits.
10117 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10118 // of computation for each trunc.
10119 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10120 UI != UIEnd; ++UI) {
10121 // Skip the uses of the chain.
10122 if (UI.getUse().getResNo() != 0)
10125 SDNode *User = *UI;
10126 unsigned Shift = 0;
10128 // Check if this is a trunc(lshr).
10129 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10130 isa<ConstantSDNode>(User->getOperand(1))) {
10131 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10132 User = *User->use_begin();
10135 // At this point, User is a Truncate, iff we encountered, trunc or
10137 if (User->getOpcode() != ISD::TRUNCATE)
10140 // The width of the type must be a power of 2 and greater than 8-bits.
10141 // Otherwise the load cannot be represented in LLVM IR.
10142 // Moreover, if we shifted with a non-8-bits multiple, the slice
10143 // will be across several bytes. We do not support that.
10144 unsigned Width = User->getValueSizeInBits(0);
10145 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10148 // Build the slice for this chain of computations.
10149 LoadedSlice LS(User, LD, Shift, &DAG);
10150 APInt CurrentUsedBits = LS.getUsedBits();
10152 // Check if this slice overlaps with another.
10153 if ((CurrentUsedBits & UsedBits) != 0)
10155 // Update the bits used globally.
10156 UsedBits |= CurrentUsedBits;
10158 // Check if the new slice would be legal.
10162 // Record the slice.
10163 LoadedSlices.push_back(LS);
10166 // Abort slicing if it does not seem to be profitable.
10167 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10172 // Rewrite each chain to use an independent load.
10173 // By construction, each chain can be represented by a unique load.
10175 // Prepare the argument for the new token factor for all the slices.
10176 SmallVector<SDValue, 8> ArgChains;
10177 for (SmallVectorImpl<LoadedSlice>::const_iterator
10178 LSIt = LoadedSlices.begin(),
10179 LSItEnd = LoadedSlices.end();
10180 LSIt != LSItEnd; ++LSIt) {
10181 SDValue SliceInst = LSIt->loadSlice();
10182 CombineTo(LSIt->Inst, SliceInst, true);
10183 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10184 SliceInst = SliceInst.getOperand(0);
10185 assert(SliceInst->getOpcode() == ISD::LOAD &&
10186 "It takes more than a zext to get to the loaded slice!!");
10187 ArgChains.push_back(SliceInst.getValue(1));
10190 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10192 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10196 /// Check to see if V is (and load (ptr), imm), where the load is having
10197 /// specific bytes cleared out. If so, return the byte size being masked out
10198 /// and the shift amount.
10199 static std::pair<unsigned, unsigned>
10200 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10201 std::pair<unsigned, unsigned> Result(0, 0);
10203 // Check for the structure we're looking for.
10204 if (V->getOpcode() != ISD::AND ||
10205 !isa<ConstantSDNode>(V->getOperand(1)) ||
10206 !ISD::isNormalLoad(V->getOperand(0).getNode()))
10209 // Check the chain and pointer.
10210 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10211 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
10213 // The store should be chained directly to the load or be an operand of a
10215 if (LD == Chain.getNode())
10217 else if (Chain->getOpcode() != ISD::TokenFactor)
10218 return Result; // Fail.
10221 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
10222 if (Chain->getOperand(i).getNode() == LD) {
10226 if (!isOk) return Result;
10229 // This only handles simple types.
10230 if (V.getValueType() != MVT::i16 &&
10231 V.getValueType() != MVT::i32 &&
10232 V.getValueType() != MVT::i64)
10235 // Check the constant mask. Invert it so that the bits being masked out are
10236 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
10237 // follow the sign bit for uniformity.
10238 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10239 unsigned NotMaskLZ = countLeadingZeros(NotMask);
10240 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
10241 unsigned NotMaskTZ = countTrailingZeros(NotMask);
10242 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
10243 if (NotMaskLZ == 64) return Result; // All zero mask.
10245 // See if we have a continuous run of bits. If so, we have 0*1+0*
10246 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10249 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10250 if (V.getValueType() != MVT::i64 && NotMaskLZ)
10251 NotMaskLZ -= 64-V.getValueSizeInBits();
10253 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10254 switch (MaskedBytes) {
10258 default: return Result; // All one mask, or 5-byte mask.
10261 // Verify that the first bit starts at a multiple of mask so that the access
10262 // is aligned the same as the access width.
10263 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10265 Result.first = MaskedBytes;
10266 Result.second = NotMaskTZ/8;
10271 /// Check to see if IVal is something that provides a value as specified by
10272 /// MaskInfo. If so, replace the specified store with a narrower store of
10273 /// truncated IVal.
10275 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10276 SDValue IVal, StoreSDNode *St,
10278 unsigned NumBytes = MaskInfo.first;
10279 unsigned ByteShift = MaskInfo.second;
10280 SelectionDAG &DAG = DC->getDAG();
10282 // Check to see if IVal is all zeros in the part being masked in by the 'or'
10283 // that uses this. If not, this is not a replacement.
10284 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10285 ByteShift*8, (ByteShift+NumBytes)*8);
10286 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10288 // Check that it is legal on the target to do this. It is legal if the new
10289 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10291 MVT VT = MVT::getIntegerVT(NumBytes*8);
10292 if (!DC->isTypeLegal(VT))
10295 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
10296 // shifted by ByteShift and truncated down to NumBytes.
10299 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10300 DAG.getConstant(ByteShift*8, DL,
10301 DC->getShiftAmountTy(IVal.getValueType())));
10304 // Figure out the offset for the store and the alignment of the access.
10306 unsigned NewAlign = St->getAlignment();
10308 if (DAG.getTargetLoweringInfo().isLittleEndian())
10309 StOffset = ByteShift;
10311 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10313 SDValue Ptr = St->getBasePtr();
10316 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10317 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10318 NewAlign = MinAlign(NewAlign, StOffset);
10321 // Truncate down to the new size.
10322 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10325 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10326 St->getPointerInfo().getWithOffset(StOffset),
10327 false, false, NewAlign).getNode();
10331 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10332 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10333 /// narrowing the load and store if it would end up being a win for performance
10335 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10336 StoreSDNode *ST = cast<StoreSDNode>(N);
10337 if (ST->isVolatile())
10340 SDValue Chain = ST->getChain();
10341 SDValue Value = ST->getValue();
10342 SDValue Ptr = ST->getBasePtr();
10343 EVT VT = Value.getValueType();
10345 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10348 unsigned Opc = Value.getOpcode();
10350 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10351 // is a byte mask indicating a consecutive number of bytes, check to see if
10352 // Y is known to provide just those bytes. If so, we try to replace the
10353 // load + replace + store sequence with a single (narrower) store, which makes
10355 if (Opc == ISD::OR) {
10356 std::pair<unsigned, unsigned> MaskedLoad;
10357 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10358 if (MaskedLoad.first)
10359 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10360 Value.getOperand(1), ST,this))
10361 return SDValue(NewST, 0);
10363 // Or is commutative, so try swapping X and Y.
10364 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10365 if (MaskedLoad.first)
10366 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10367 Value.getOperand(0), ST,this))
10368 return SDValue(NewST, 0);
10371 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10372 Value.getOperand(1).getOpcode() != ISD::Constant)
10375 SDValue N0 = Value.getOperand(0);
10376 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10377 Chain == SDValue(N0.getNode(), 1)) {
10378 LoadSDNode *LD = cast<LoadSDNode>(N0);
10379 if (LD->getBasePtr() != Ptr ||
10380 LD->getPointerInfo().getAddrSpace() !=
10381 ST->getPointerInfo().getAddrSpace())
10384 // Find the type to narrow it the load / op / store to.
10385 SDValue N1 = Value.getOperand(1);
10386 unsigned BitWidth = N1.getValueSizeInBits();
10387 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10388 if (Opc == ISD::AND)
10389 Imm ^= APInt::getAllOnesValue(BitWidth);
10390 if (Imm == 0 || Imm.isAllOnesValue())
10392 unsigned ShAmt = Imm.countTrailingZeros();
10393 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10394 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10395 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10396 // The narrowing should be profitable, the load/store operation should be
10397 // legal (or custom) and the store size should be equal to the NewVT width.
10398 while (NewBW < BitWidth &&
10399 (NewVT.getStoreSizeInBits() != NewBW ||
10400 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10401 !TLI.isNarrowingProfitable(VT, NewVT))) {
10402 NewBW = NextPowerOf2(NewBW);
10403 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10405 if (NewBW >= BitWidth)
10408 // If the lsb changed does not start at the type bitwidth boundary,
10409 // start at the previous one.
10411 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10412 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10413 std::min(BitWidth, ShAmt + NewBW));
10414 if ((Imm & Mask) == Imm) {
10415 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10416 if (Opc == ISD::AND)
10417 NewImm ^= APInt::getAllOnesValue(NewBW);
10418 uint64_t PtrOff = ShAmt / 8;
10419 // For big endian targets, we need to adjust the offset to the pointer to
10420 // load the correct bytes.
10421 if (TLI.isBigEndian())
10422 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10424 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10425 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10426 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
10429 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10430 Ptr.getValueType(), Ptr,
10431 DAG.getConstant(PtrOff, SDLoc(LD),
10432 Ptr.getValueType()));
10433 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10434 LD->getChain(), NewPtr,
10435 LD->getPointerInfo().getWithOffset(PtrOff),
10436 LD->isVolatile(), LD->isNonTemporal(),
10437 LD->isInvariant(), NewAlign,
10439 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10440 DAG.getConstant(NewImm, SDLoc(Value),
10442 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10444 ST->getPointerInfo().getWithOffset(PtrOff),
10445 false, false, NewAlign);
10447 AddToWorklist(NewPtr.getNode());
10448 AddToWorklist(NewLD.getNode());
10449 AddToWorklist(NewVal.getNode());
10450 WorklistRemover DeadNodes(*this);
10451 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10460 /// For a given floating point load / store pair, if the load value isn't used
10461 /// by any other operations, then consider transforming the pair to integer
10462 /// load / store operations if the target deems the transformation profitable.
10463 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10464 StoreSDNode *ST = cast<StoreSDNode>(N);
10465 SDValue Chain = ST->getChain();
10466 SDValue Value = ST->getValue();
10467 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10468 Value.hasOneUse() &&
10469 Chain == SDValue(Value.getNode(), 1)) {
10470 LoadSDNode *LD = cast<LoadSDNode>(Value);
10471 EVT VT = LD->getMemoryVT();
10472 if (!VT.isFloatingPoint() ||
10473 VT != ST->getMemoryVT() ||
10474 LD->isNonTemporal() ||
10475 ST->isNonTemporal() ||
10476 LD->getPointerInfo().getAddrSpace() != 0 ||
10477 ST->getPointerInfo().getAddrSpace() != 0)
10480 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10481 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10482 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10483 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10484 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10487 unsigned LDAlign = LD->getAlignment();
10488 unsigned STAlign = ST->getAlignment();
10489 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10490 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
10491 if (LDAlign < ABIAlign || STAlign < ABIAlign)
10494 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10495 LD->getChain(), LD->getBasePtr(),
10496 LD->getPointerInfo(),
10497 false, false, false, LDAlign);
10499 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10500 NewLD, ST->getBasePtr(),
10501 ST->getPointerInfo(),
10502 false, false, STAlign);
10504 AddToWorklist(NewLD.getNode());
10505 AddToWorklist(NewST.getNode());
10506 WorklistRemover DeadNodes(*this);
10507 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10516 /// Helper struct to parse and store a memory address as base + index + offset.
10517 /// We ignore sign extensions when it is safe to do so.
10518 /// The following two expressions are not equivalent. To differentiate we need
10519 /// to store whether there was a sign extension involved in the index
10521 /// (load (i64 add (i64 copyfromreg %c)
10522 /// (i64 signextend (add (i8 load %index)
10526 /// (load (i64 add (i64 copyfromreg %c)
10527 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
10529 struct BaseIndexOffset {
10533 bool IsIndexSignExt;
10535 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10537 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10538 bool IsIndexSignExt) :
10539 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10541 bool equalBaseIndex(const BaseIndexOffset &Other) {
10542 return Other.Base == Base && Other.Index == Index &&
10543 Other.IsIndexSignExt == IsIndexSignExt;
10546 /// Parses tree in Ptr for base, index, offset addresses.
10547 static BaseIndexOffset match(SDValue Ptr) {
10548 bool IsIndexSignExt = false;
10550 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10551 // instruction, then it could be just the BASE or everything else we don't
10552 // know how to handle. Just use Ptr as BASE and give up.
10553 if (Ptr->getOpcode() != ISD::ADD)
10554 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10556 // We know that we have at least an ADD instruction. Try to pattern match
10557 // the simple case of BASE + OFFSET.
10558 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10559 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10560 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10564 // Inside a loop the current BASE pointer is calculated using an ADD and a
10565 // MUL instruction. In this case Ptr is the actual BASE pointer.
10566 // (i64 add (i64 %array_ptr)
10567 // (i64 mul (i64 %induction_var)
10568 // (i64 %element_size)))
10569 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10570 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10572 // Look at Base + Index + Offset cases.
10573 SDValue Base = Ptr->getOperand(0);
10574 SDValue IndexOffset = Ptr->getOperand(1);
10576 // Skip signextends.
10577 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10578 IndexOffset = IndexOffset->getOperand(0);
10579 IsIndexSignExt = true;
10582 // Either the case of Base + Index (no offset) or something else.
10583 if (IndexOffset->getOpcode() != ISD::ADD)
10584 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10586 // Now we have the case of Base + Index + offset.
10587 SDValue Index = IndexOffset->getOperand(0);
10588 SDValue Offset = IndexOffset->getOperand(1);
10590 if (!isa<ConstantSDNode>(Offset))
10591 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10593 // Ignore signextends.
10594 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10595 Index = Index->getOperand(0);
10596 IsIndexSignExt = true;
10597 } else IsIndexSignExt = false;
10599 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10600 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10605 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10607 ArrayRef<MemOpLink> Stores,
10609 SmallVector<SDValue, 8> BuildVector;
10611 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I)
10612 BuildVector.push_back(cast<StoreSDNode>(Stores[I].MemNode)->getValue());
10614 return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10617 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10618 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10619 unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10620 // Make sure we have something to merge.
10624 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10625 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10626 unsigned LatestNodeUsed = 0;
10628 for (unsigned i=0; i < NumElem; ++i) {
10629 // Find a chain for the new wide-store operand. Notice that some
10630 // of the store nodes that we found may not be selected for inclusion
10631 // in the wide store. The chain we use needs to be the chain of the
10632 // latest store node which is *used* and replaced by the wide store.
10633 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10634 LatestNodeUsed = i;
10637 // The latest Node in the DAG.
10638 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10639 SDLoc DL(StoreNodes[0].MemNode);
10643 // Find a legal type for the vector store.
10644 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10645 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10646 if (IsConstantSrc) {
10647 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Ty);
10649 SmallVector<SDValue, 8> Ops;
10650 for (unsigned i = 0; i < NumElem ; ++i) {
10651 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10652 SDValue Val = St->getValue();
10653 // All of the operands of a BUILD_VECTOR must have the same type.
10654 if (Val.getValueType() != MemVT)
10656 Ops.push_back(Val);
10659 // Build the extracted vector elements back into a vector.
10660 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10663 // We should always use a vector store when merging extracted vector
10664 // elements, so this path implies a store of constants.
10665 assert(IsConstantSrc && "Merged vector elements should use vector store");
10667 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
10668 APInt StoreInt(SizeInBits, 0);
10670 // Construct a single integer constant which is made of the smaller
10671 // constant inputs.
10672 bool IsLE = TLI.isLittleEndian();
10673 for (unsigned i = 0; i < NumElem ; ++i) {
10674 unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10675 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10676 SDValue Val = St->getValue();
10677 StoreInt <<= ElementSizeBytes * 8;
10678 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10679 StoreInt |= C->getAPIntValue().zext(SizeInBits);
10680 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10681 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
10683 llvm_unreachable("Invalid constant element type");
10687 // Create the new Load and Store operations.
10688 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
10689 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10692 SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10693 FirstInChain->getBasePtr(),
10694 FirstInChain->getPointerInfo(),
10696 FirstInChain->getAlignment());
10698 // Replace the last store with the new store
10699 CombineTo(LatestOp, NewStore);
10700 // Erase all other stores.
10701 for (unsigned i = 0; i < NumElem ; ++i) {
10702 if (StoreNodes[i].MemNode == LatestOp)
10704 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10705 // ReplaceAllUsesWith will replace all uses that existed when it was
10706 // called, but graph optimizations may cause new ones to appear. For
10707 // example, the case in pr14333 looks like
10709 // St's chain -> St -> another store -> X
10711 // And the only difference from St to the other store is the chain.
10712 // When we change it's chain to be St's chain they become identical,
10713 // get CSEed and the net result is that X is now a use of St.
10714 // Since we know that St is redundant, just iterate.
10715 while (!St->use_empty())
10716 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10717 deleteAndRecombine(St);
10723 static bool allowableAlignment(const SelectionDAG &DAG,
10724 const TargetLowering &TLI, EVT EVTTy,
10725 unsigned AS, unsigned Align) {
10726 if (TLI.allowsMisalignedMemoryAccesses(EVTTy, AS, Align))
10729 Type *Ty = EVTTy.getTypeForEVT(*DAG.getContext());
10730 unsigned ABIAlignment = TLI.getDataLayout()->getPrefTypeAlignment(Ty);
10731 return (Align >= ABIAlignment);
10734 void DAGCombiner::getStoreMergeAndAliasCandidates(
10735 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
10736 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
10737 // This holds the base pointer, index, and the offset in bytes from the base
10739 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10741 // We must have a base and an offset.
10742 if (!BasePtr.Base.getNode())
10745 // Do not handle stores to undef base pointers.
10746 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10749 // Walk up the chain and look for nodes with offsets from the same
10750 // base pointer. Stop when reaching an instruction with a different kind
10751 // or instruction which has a different base pointer.
10752 EVT MemVT = St->getMemoryVT();
10754 StoreSDNode *Index = St;
10756 // If the chain has more than one use, then we can't reorder the mem ops.
10757 if (Index != St && !SDValue(Index, 0)->hasOneUse())
10760 // Find the base pointer and offset for this memory node.
10761 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10763 // Check that the base pointer is the same as the original one.
10764 if (!Ptr.equalBaseIndex(BasePtr))
10767 // The memory operands must not be volatile.
10768 if (Index->isVolatile() || Index->isIndexed())
10772 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10773 if (St->isTruncatingStore())
10776 // The stored memory type must be the same.
10777 if (Index->getMemoryVT() != MemVT)
10780 // We found a potential memory operand to merge.
10781 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10783 // Find the next memory operand in the chain. If the next operand in the
10784 // chain is a store then move up and continue the scan with the next
10785 // memory operand. If the next operand is a load save it and use alias
10786 // information to check if it interferes with anything.
10787 SDNode *NextInChain = Index->getChain().getNode();
10789 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10790 // We found a store node. Use it for the next iteration.
10793 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10794 if (Ldn->isVolatile()) {
10799 // Save the load node for later. Continue the scan.
10800 AliasLoadNodes.push_back(Ldn);
10801 NextInChain = Ldn->getChain().getNode();
10811 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10812 if (OptLevel == CodeGenOpt::None)
10815 EVT MemVT = St->getMemoryVT();
10816 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10817 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10818 Attribute::NoImplicitFloat);
10820 // This function cannot currently deal with non-byte-sized memory sizes.
10821 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10824 // Don't merge vectors into wider inputs.
10825 if (MemVT.isVector() || !MemVT.isSimple())
10828 // Perform an early exit check. Do not bother looking at stored values that
10829 // are not constants, loads, or extracted vector elements.
10830 SDValue StoredVal = St->getValue();
10831 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10832 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10833 isa<ConstantFPSDNode>(StoredVal);
10834 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10836 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10839 // Only look at ends of store sequences.
10840 SDValue Chain = SDValue(St, 0);
10841 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10844 // Save the LoadSDNodes that we find in the chain.
10845 // We need to make sure that these nodes do not interfere with
10846 // any of the store nodes.
10847 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10849 // Save the StoreSDNodes that we find in the chain.
10850 SmallVector<MemOpLink, 8> StoreNodes;
10852 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
10854 // Check if there is anything to merge.
10855 if (StoreNodes.size() < 2)
10858 // Sort the memory operands according to their distance from the base pointer.
10859 std::sort(StoreNodes.begin(), StoreNodes.end(),
10860 [](MemOpLink LHS, MemOpLink RHS) {
10861 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10862 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10863 LHS.SequenceNum > RHS.SequenceNum);
10866 // Scan the memory operations on the chain and find the first non-consecutive
10867 // store memory address.
10868 unsigned LastConsecutiveStore = 0;
10869 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10870 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10872 // Check that the addresses are consecutive starting from the second
10873 // element in the list of stores.
10875 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10876 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10880 bool Alias = false;
10881 // Check if this store interferes with any of the loads that we found.
10882 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10883 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10887 // We found a load that alias with this store. Stop the sequence.
10891 // Mark this node as useful.
10892 LastConsecutiveStore = i;
10895 // The node with the lowest store address.
10896 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10897 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
10898 unsigned FirstStoreAlign = FirstInChain->getAlignment();
10900 // Store the constants into memory as one consecutive store.
10901 if (IsConstantSrc) {
10902 unsigned LastLegalType = 0;
10903 unsigned LastLegalVectorType = 0;
10904 bool NonZero = false;
10905 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10906 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10907 SDValue StoredVal = St->getValue();
10909 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10910 NonZero |= !C->isNullValue();
10911 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10912 NonZero |= !C->getConstantFPValue()->isNullValue();
10918 // Find a legal type for the constant store.
10919 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
10920 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
10921 if (TLI.isTypeLegal(StoreTy) &&
10922 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS,
10923 FirstStoreAlign)) {
10924 LastLegalType = i+1;
10925 // Or check whether a truncstore is legal.
10926 } else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10927 TargetLowering::TypePromoteInteger) {
10928 EVT LegalizedStoredValueTy =
10929 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10930 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10931 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
10932 FirstStoreAlign)) {
10933 LastLegalType = i + 1;
10937 // Find a legal type for the vector store.
10938 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10939 if (TLI.isTypeLegal(Ty) &&
10940 allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign)) {
10941 LastLegalVectorType = i + 1;
10946 // We only use vectors if the constant is known to be zero or the target
10947 // allows it and the function is not marked with the noimplicitfloat
10950 LastLegalVectorType = 0;
10951 } else if (NonZero && !TLI.storeOfVectorConstantIsCheap(MemVT,
10952 LastLegalVectorType,
10954 LastLegalVectorType = 0;
10957 // Check if we found a legal integer type to store.
10958 if (LastLegalType == 0 && LastLegalVectorType == 0)
10961 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10962 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10964 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10968 // When extracting multiple vector elements, try to store them
10969 // in one vector store rather than a sequence of scalar stores.
10970 if (IsExtractVecEltSrc) {
10971 unsigned NumElem = 0;
10972 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10973 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10974 SDValue StoredVal = St->getValue();
10975 // This restriction could be loosened.
10976 // Bail out if any stored values are not elements extracted from a vector.
10977 // It should be possible to handle mixed sources, but load sources need
10978 // more careful handling (see the block of code below that handles
10979 // consecutive loads).
10980 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10983 // Find a legal type for the vector store.
10984 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10985 if (TLI.isTypeLegal(Ty) &&
10986 allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign))
10990 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10994 // Below we handle the case of multiple consecutive stores that
10995 // come from multiple consecutive loads. We merge them into a single
10996 // wide load and a single wide store.
10998 // Look for load nodes which are used by the stored values.
10999 SmallVector<MemOpLink, 8> LoadNodes;
11001 // Find acceptable loads. Loads need to have the same chain (token factor),
11002 // must not be zext, volatile, indexed, and they must be consecutive.
11003 BaseIndexOffset LdBasePtr;
11004 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11005 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11006 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11009 // Loads must only have one use.
11010 if (!Ld->hasNUsesOfValue(1, 0))
11013 // The memory operands must not be volatile.
11014 if (Ld->isVolatile() || Ld->isIndexed())
11017 // We do not accept ext loads.
11018 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11021 // The stored memory type must be the same.
11022 if (Ld->getMemoryVT() != MemVT)
11025 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11026 // If this is not the first ptr that we check.
11027 if (LdBasePtr.Base.getNode()) {
11028 // The base ptr must be the same.
11029 if (!LdPtr.equalBaseIndex(LdBasePtr))
11032 // Check that all other base pointers are the same as this one.
11036 // We found a potential memory operand to merge.
11037 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11040 if (LoadNodes.size() < 2)
11043 // If we have load/store pair instructions and we only have two values,
11045 unsigned RequiredAlignment;
11046 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11047 St->getAlignment() >= RequiredAlignment)
11050 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11051 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11052 unsigned FirstLoadAlign = FirstLoad->getAlignment();
11054 // Scan the memory operations on the chain and find the first non-consecutive
11055 // load memory address. These variables hold the index in the store node
11057 unsigned LastConsecutiveLoad = 0;
11058 // This variable refers to the size and not index in the array.
11059 unsigned LastLegalVectorType = 0;
11060 unsigned LastLegalIntegerType = 0;
11061 StartAddress = LoadNodes[0].OffsetFromBase;
11062 SDValue FirstChain = FirstLoad->getChain();
11063 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11064 // All loads much share the same chain.
11065 if (LoadNodes[i].MemNode->getChain() != FirstChain)
11068 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11069 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11071 LastConsecutiveLoad = i;
11073 // Find a legal type for the vector store.
11074 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
11075 if (TLI.isTypeLegal(StoreTy) &&
11076 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
11077 allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign)) {
11078 LastLegalVectorType = i + 1;
11081 // Find a legal type for the integer store.
11082 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11083 StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11084 if (TLI.isTypeLegal(StoreTy) &&
11085 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
11086 allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign))
11087 LastLegalIntegerType = i + 1;
11088 // Or check whether a truncstore and extload is legal.
11089 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
11090 TargetLowering::TypePromoteInteger) {
11091 EVT LegalizedStoredValueTy =
11092 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
11093 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11094 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11095 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11096 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11097 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
11098 FirstStoreAlign) &&
11099 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstLoadAS,
11101 LastLegalIntegerType = i+1;
11105 // Only use vector types if the vector type is larger than the integer type.
11106 // If they are the same, use integers.
11107 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11108 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11110 // We add +1 here because the LastXXX variables refer to location while
11111 // the NumElem refers to array/index size.
11112 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11113 NumElem = std::min(LastLegalType, NumElem);
11118 // The latest Node in the DAG.
11119 unsigned LatestNodeUsed = 0;
11120 for (unsigned i=1; i<NumElem; ++i) {
11121 // Find a chain for the new wide-store operand. Notice that some
11122 // of the store nodes that we found may not be selected for inclusion
11123 // in the wide store. The chain we use needs to be the chain of the
11124 // latest store node which is *used* and replaced by the wide store.
11125 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11126 LatestNodeUsed = i;
11129 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11131 // Find if it is better to use vectors or integers to load and store
11135 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
11137 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11138 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11141 SDLoc LoadDL(LoadNodes[0].MemNode);
11142 SDLoc StoreDL(StoreNodes[0].MemNode);
11144 SDValue NewLoad = DAG.getLoad(
11145 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11146 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11148 SDValue NewStore = DAG.getStore(
11149 LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11150 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11152 // Replace one of the loads with the new load.
11153 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11154 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11155 SDValue(NewLoad.getNode(), 1));
11157 // Remove the rest of the load chains.
11158 for (unsigned i = 1; i < NumElem ; ++i) {
11159 // Replace all chain users of the old load nodes with the chain of the new
11161 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11162 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11165 // Replace the last store with the new store.
11166 CombineTo(LatestOp, NewStore);
11167 // Erase all other stores.
11168 for (unsigned i = 0; i < NumElem ; ++i) {
11169 // Remove all Store nodes.
11170 if (StoreNodes[i].MemNode == LatestOp)
11172 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11173 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11174 deleteAndRecombine(St);
11180 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11181 StoreSDNode *ST = cast<StoreSDNode>(N);
11182 SDValue Chain = ST->getChain();
11183 SDValue Value = ST->getValue();
11184 SDValue Ptr = ST->getBasePtr();
11186 // If this is a store of a bit convert, store the input value if the
11187 // resultant store does not need a higher alignment than the original.
11188 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11189 ST->isUnindexed()) {
11190 unsigned OrigAlign = ST->getAlignment();
11191 EVT SVT = Value.getOperand(0).getValueType();
11192 unsigned Align = TLI.getDataLayout()->
11193 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
11194 if (Align <= OrigAlign &&
11195 ((!LegalOperations && !ST->isVolatile()) ||
11196 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11197 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11198 Ptr, ST->getPointerInfo(), ST->isVolatile(),
11199 ST->isNonTemporal(), OrigAlign,
11203 // Turn 'store undef, Ptr' -> nothing.
11204 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11207 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11208 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11209 // NOTE: If the original store is volatile, this transform must not increase
11210 // the number of stores. For example, on x86-32 an f64 can be stored in one
11211 // processor operation but an i64 (which is not legal) requires two. So the
11212 // transform should not be done in this case.
11213 if (Value.getOpcode() != ISD::TargetConstantFP) {
11215 switch (CFP->getSimpleValueType(0).SimpleTy) {
11216 default: llvm_unreachable("Unknown FP type");
11217 case MVT::f16: // We don't do this for these yet.
11223 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11224 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11226 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11227 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11229 return DAG.getStore(Chain, SDLoc(N), Tmp,
11230 Ptr, ST->getMemOperand());
11234 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11235 !ST->isVolatile()) ||
11236 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11238 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11239 getZExtValue(), SDLoc(CFP), MVT::i64);
11240 return DAG.getStore(Chain, SDLoc(N), Tmp,
11241 Ptr, ST->getMemOperand());
11244 if (!ST->isVolatile() &&
11245 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11246 // Many FP stores are not made apparent until after legalize, e.g. for
11247 // argument passing. Since this is so common, custom legalize the
11248 // 64-bit integer store into two 32-bit stores.
11249 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11250 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11251 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11252 if (TLI.isBigEndian()) std::swap(Lo, Hi);
11254 unsigned Alignment = ST->getAlignment();
11255 bool isVolatile = ST->isVolatile();
11256 bool isNonTemporal = ST->isNonTemporal();
11257 AAMDNodes AAInfo = ST->getAAInfo();
11261 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11262 Ptr, ST->getPointerInfo(),
11263 isVolatile, isNonTemporal,
11264 ST->getAlignment(), AAInfo);
11265 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11266 DAG.getConstant(4, DL, Ptr.getValueType()));
11267 Alignment = MinAlign(Alignment, 4U);
11268 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11269 Ptr, ST->getPointerInfo().getWithOffset(4),
11270 isVolatile, isNonTemporal,
11271 Alignment, AAInfo);
11272 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11281 // Try to infer better alignment information than the store already has.
11282 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11283 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11284 if (Align > ST->getAlignment()) {
11286 DAG.getTruncStore(Chain, SDLoc(N), Value,
11287 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11288 ST->isVolatile(), ST->isNonTemporal(), Align,
11290 if (NewStore.getNode() != N)
11291 return CombineTo(ST, NewStore, true);
11296 // Try transforming a pair floating point load / store ops to integer
11297 // load / store ops.
11298 SDValue NewST = TransformFPLoadStorePair(N);
11299 if (NewST.getNode())
11302 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11303 : DAG.getSubtarget().useAA();
11305 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11306 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11309 if (UseAA && ST->isUnindexed()) {
11310 // Walk up chain skipping non-aliasing memory nodes.
11311 SDValue BetterChain = FindBetterChain(N, Chain);
11313 // If there is a better chain.
11314 if (Chain != BetterChain) {
11317 // Replace the chain to avoid dependency.
11318 if (ST->isTruncatingStore()) {
11319 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11320 ST->getMemoryVT(), ST->getMemOperand());
11322 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11323 ST->getMemOperand());
11326 // Create token to keep both nodes around.
11327 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11328 MVT::Other, Chain, ReplStore);
11330 // Make sure the new and old chains are cleaned up.
11331 AddToWorklist(Token.getNode());
11333 // Don't add users to work list.
11334 return CombineTo(N, Token, false);
11338 // Try transforming N to an indexed store.
11339 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11340 return SDValue(N, 0);
11342 // FIXME: is there such a thing as a truncating indexed store?
11343 if (ST->isTruncatingStore() && ST->isUnindexed() &&
11344 Value.getValueType().isInteger()) {
11345 // See if we can simplify the input to this truncstore with knowledge that
11346 // only the low bits are being used. For example:
11347 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
11349 GetDemandedBits(Value,
11350 APInt::getLowBitsSet(
11351 Value.getValueType().getScalarType().getSizeInBits(),
11352 ST->getMemoryVT().getScalarType().getSizeInBits()));
11353 AddToWorklist(Value.getNode());
11354 if (Shorter.getNode())
11355 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11356 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11358 // Otherwise, see if we can simplify the operation with
11359 // SimplifyDemandedBits, which only works if the value has a single use.
11360 if (SimplifyDemandedBits(Value,
11361 APInt::getLowBitsSet(
11362 Value.getValueType().getScalarType().getSizeInBits(),
11363 ST->getMemoryVT().getScalarType().getSizeInBits())))
11364 return SDValue(N, 0);
11367 // If this is a load followed by a store to the same location, then the store
11369 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11370 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11371 ST->isUnindexed() && !ST->isVolatile() &&
11372 // There can't be any side effects between the load and store, such as
11373 // a call or store.
11374 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11375 // The store is dead, remove it.
11380 // If this is a store followed by a store with the same value to the same
11381 // location, then the store is dead/noop.
11382 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11383 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11384 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11385 ST1->isUnindexed() && !ST1->isVolatile()) {
11386 // The store is dead, remove it.
11391 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11392 // truncating store. We can do this even if this is already a truncstore.
11393 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11394 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11395 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11396 ST->getMemoryVT())) {
11397 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11398 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11401 // Only perform this optimization before the types are legal, because we
11402 // don't want to perform this optimization on every DAGCombine invocation.
11404 bool EverChanged = false;
11407 // There can be multiple store sequences on the same chain.
11408 // Keep trying to merge store sequences until we are unable to do so
11409 // or until we merge the last store on the chain.
11410 bool Changed = MergeConsecutiveStores(ST);
11411 EverChanged |= Changed;
11412 if (!Changed) break;
11413 } while (ST->getOpcode() != ISD::DELETED_NODE);
11416 return SDValue(N, 0);
11419 return ReduceLoadOpStoreWidth(N);
11422 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11423 SDValue InVec = N->getOperand(0);
11424 SDValue InVal = N->getOperand(1);
11425 SDValue EltNo = N->getOperand(2);
11428 // If the inserted element is an UNDEF, just use the input vector.
11429 if (InVal.getOpcode() == ISD::UNDEF)
11432 EVT VT = InVec.getValueType();
11434 // If we can't generate a legal BUILD_VECTOR, exit
11435 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11438 // Check that we know which element is being inserted
11439 if (!isa<ConstantSDNode>(EltNo))
11441 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11443 // Canonicalize insert_vector_elt dag nodes.
11445 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11446 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11448 // Do this only if the child insert_vector node has one use; also
11449 // do this only if indices are both constants and Idx1 < Idx0.
11450 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11451 && isa<ConstantSDNode>(InVec.getOperand(2))) {
11452 unsigned OtherElt =
11453 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11454 if (Elt < OtherElt) {
11456 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11457 InVec.getOperand(0), InVal, EltNo);
11458 AddToWorklist(NewOp.getNode());
11459 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11460 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11464 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11465 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
11466 // vector elements.
11467 SmallVector<SDValue, 8> Ops;
11468 // Do not combine these two vectors if the output vector will not replace
11469 // the input vector.
11470 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11471 Ops.append(InVec.getNode()->op_begin(),
11472 InVec.getNode()->op_end());
11473 } else if (InVec.getOpcode() == ISD::UNDEF) {
11474 unsigned NElts = VT.getVectorNumElements();
11475 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11480 // Insert the element
11481 if (Elt < Ops.size()) {
11482 // All the operands of BUILD_VECTOR must have the same type;
11483 // we enforce that here.
11484 EVT OpVT = Ops[0].getValueType();
11485 if (InVal.getValueType() != OpVT)
11486 InVal = OpVT.bitsGT(InVal.getValueType()) ?
11487 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11488 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11492 // Return the new vector
11493 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11496 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11497 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11498 EVT ResultVT = EVE->getValueType(0);
11499 EVT VecEltVT = InVecVT.getVectorElementType();
11500 unsigned Align = OriginalLoad->getAlignment();
11501 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11502 VecEltVT.getTypeForEVT(*DAG.getContext()));
11504 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11509 SDValue NewPtr = OriginalLoad->getBasePtr();
11511 EVT PtrType = NewPtr.getValueType();
11512 MachinePointerInfo MPI;
11514 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11515 int Elt = ConstEltNo->getZExtValue();
11516 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11517 Offset = DAG.getConstant(PtrOff, DL, PtrType);
11518 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11520 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11521 Offset = DAG.getNode(
11522 ISD::MUL, DL, PtrType, Offset,
11523 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11524 MPI = OriginalLoad->getPointerInfo();
11526 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11528 // The replacement we need to do here is a little tricky: we need to
11529 // replace an extractelement of a load with a load.
11530 // Use ReplaceAllUsesOfValuesWith to do the replacement.
11531 // Note that this replacement assumes that the extractvalue is the only
11532 // use of the load; that's okay because we don't want to perform this
11533 // transformation in other cases anyway.
11536 if (ResultVT.bitsGT(VecEltVT)) {
11537 // If the result type of vextract is wider than the load, then issue an
11538 // extending load instead.
11539 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11543 Load = DAG.getExtLoad(
11544 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11545 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11546 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11547 Chain = Load.getValue(1);
11549 Load = DAG.getLoad(
11550 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11551 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11552 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11553 Chain = Load.getValue(1);
11554 if (ResultVT.bitsLT(VecEltVT))
11555 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11557 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11559 WorklistRemover DeadNodes(*this);
11560 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11561 SDValue To[] = { Load, Chain };
11562 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11563 // Since we're explicitly calling ReplaceAllUses, add the new node to the
11564 // worklist explicitly as well.
11565 AddToWorklist(Load.getNode());
11566 AddUsersToWorklist(Load.getNode()); // Add users too
11567 // Make sure to revisit this node to clean it up; it will usually be dead.
11568 AddToWorklist(EVE);
11570 return SDValue(EVE, 0);
11573 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11574 // (vextract (scalar_to_vector val, 0) -> val
11575 SDValue InVec = N->getOperand(0);
11576 EVT VT = InVec.getValueType();
11577 EVT NVT = N->getValueType(0);
11579 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11580 // Check if the result type doesn't match the inserted element type. A
11581 // SCALAR_TO_VECTOR may truncate the inserted element and the
11582 // EXTRACT_VECTOR_ELT may widen the extracted vector.
11583 SDValue InOp = InVec.getOperand(0);
11584 if (InOp.getValueType() != NVT) {
11585 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11586 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11591 SDValue EltNo = N->getOperand(1);
11592 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11594 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11595 // We only perform this optimization before the op legalization phase because
11596 // we may introduce new vector instructions which are not backed by TD
11597 // patterns. For example on AVX, extracting elements from a wide vector
11598 // without using extract_subvector. However, if we can find an underlying
11599 // scalar value, then we can always use that.
11600 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11602 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11603 int NumElem = VT.getVectorNumElements();
11604 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11605 // Find the new index to extract from.
11606 int OrigElt = SVOp->getMaskElt(Elt);
11608 // Extracting an undef index is undef.
11610 return DAG.getUNDEF(NVT);
11612 // Select the right vector half to extract from.
11614 if (OrigElt < NumElem) {
11615 SVInVec = InVec->getOperand(0);
11617 SVInVec = InVec->getOperand(1);
11618 OrigElt -= NumElem;
11621 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11622 SDValue InOp = SVInVec.getOperand(OrigElt);
11623 if (InOp.getValueType() != NVT) {
11624 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11625 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11631 // FIXME: We should handle recursing on other vector shuffles and
11632 // scalar_to_vector here as well.
11634 if (!LegalOperations) {
11635 EVT IndexTy = TLI.getVectorIdxTy();
11636 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11637 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11641 bool BCNumEltsChanged = false;
11642 EVT ExtVT = VT.getVectorElementType();
11645 // If the result of load has to be truncated, then it's not necessarily
11647 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11650 if (InVec.getOpcode() == ISD::BITCAST) {
11651 // Don't duplicate a load with other uses.
11652 if (!InVec.hasOneUse())
11655 EVT BCVT = InVec.getOperand(0).getValueType();
11656 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11658 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11659 BCNumEltsChanged = true;
11660 InVec = InVec.getOperand(0);
11661 ExtVT = BCVT.getVectorElementType();
11664 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11665 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11666 ISD::isNormalLoad(InVec.getNode()) &&
11667 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11668 SDValue Index = N->getOperand(1);
11669 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11670 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11674 // Perform only after legalization to ensure build_vector / vector_shuffle
11675 // optimizations have already been done.
11676 if (!LegalOperations) return SDValue();
11678 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11679 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11680 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11683 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11685 LoadSDNode *LN0 = nullptr;
11686 const ShuffleVectorSDNode *SVN = nullptr;
11687 if (ISD::isNormalLoad(InVec.getNode())) {
11688 LN0 = cast<LoadSDNode>(InVec);
11689 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11690 InVec.getOperand(0).getValueType() == ExtVT &&
11691 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11692 // Don't duplicate a load with other uses.
11693 if (!InVec.hasOneUse())
11696 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11697 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11698 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11700 // (load $addr+1*size)
11702 // Don't duplicate a load with other uses.
11703 if (!InVec.hasOneUse())
11706 // If the bit convert changed the number of elements, it is unsafe
11707 // to examine the mask.
11708 if (BCNumEltsChanged)
11711 // Select the input vector, guarding against out of range extract vector.
11712 unsigned NumElems = VT.getVectorNumElements();
11713 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11714 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11716 if (InVec.getOpcode() == ISD::BITCAST) {
11717 // Don't duplicate a load with other uses.
11718 if (!InVec.hasOneUse())
11721 InVec = InVec.getOperand(0);
11723 if (ISD::isNormalLoad(InVec.getNode())) {
11724 LN0 = cast<LoadSDNode>(InVec);
11725 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11726 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11730 // Make sure we found a non-volatile load and the extractelement is
11732 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11735 // If Idx was -1 above, Elt is going to be -1, so just return undef.
11737 return DAG.getUNDEF(LVT);
11739 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11745 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11746 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11747 // We perform this optimization post type-legalization because
11748 // the type-legalizer often scalarizes integer-promoted vectors.
11749 // Performing this optimization before may create bit-casts which
11750 // will be type-legalized to complex code sequences.
11751 // We perform this optimization only before the operation legalizer because we
11752 // may introduce illegal operations.
11753 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11756 unsigned NumInScalars = N->getNumOperands();
11758 EVT VT = N->getValueType(0);
11760 // Check to see if this is a BUILD_VECTOR of a bunch of values
11761 // which come from any_extend or zero_extend nodes. If so, we can create
11762 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11763 // optimizations. We do not handle sign-extend because we can't fill the sign
11765 EVT SourceType = MVT::Other;
11766 bool AllAnyExt = true;
11768 for (unsigned i = 0; i != NumInScalars; ++i) {
11769 SDValue In = N->getOperand(i);
11770 // Ignore undef inputs.
11771 if (In.getOpcode() == ISD::UNDEF) continue;
11773 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
11774 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11776 // Abort if the element is not an extension.
11777 if (!ZeroExt && !AnyExt) {
11778 SourceType = MVT::Other;
11782 // The input is a ZeroExt or AnyExt. Check the original type.
11783 EVT InTy = In.getOperand(0).getValueType();
11785 // Check that all of the widened source types are the same.
11786 if (SourceType == MVT::Other)
11789 else if (InTy != SourceType) {
11790 // Multiple income types. Abort.
11791 SourceType = MVT::Other;
11795 // Check if all of the extends are ANY_EXTENDs.
11796 AllAnyExt &= AnyExt;
11799 // In order to have valid types, all of the inputs must be extended from the
11800 // same source type and all of the inputs must be any or zero extend.
11801 // Scalar sizes must be a power of two.
11802 EVT OutScalarTy = VT.getScalarType();
11803 bool ValidTypes = SourceType != MVT::Other &&
11804 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11805 isPowerOf2_32(SourceType.getSizeInBits());
11807 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11808 // turn into a single shuffle instruction.
11812 bool isLE = TLI.isLittleEndian();
11813 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11814 assert(ElemRatio > 1 && "Invalid element size ratio");
11815 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11816 DAG.getConstant(0, SDLoc(N), SourceType);
11818 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11819 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11821 // Populate the new build_vector
11822 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11823 SDValue Cast = N->getOperand(i);
11824 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11825 Cast.getOpcode() == ISD::ZERO_EXTEND ||
11826 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11828 if (Cast.getOpcode() == ISD::UNDEF)
11829 In = DAG.getUNDEF(SourceType);
11831 In = Cast->getOperand(0);
11832 unsigned Index = isLE ? (i * ElemRatio) :
11833 (i * ElemRatio + (ElemRatio - 1));
11835 assert(Index < Ops.size() && "Invalid index");
11839 // The type of the new BUILD_VECTOR node.
11840 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11841 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11842 "Invalid vector size");
11843 // Check if the new vector type is legal.
11844 if (!isTypeLegal(VecVT)) return SDValue();
11846 // Make the new BUILD_VECTOR.
11847 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11849 // The new BUILD_VECTOR node has the potential to be further optimized.
11850 AddToWorklist(BV.getNode());
11851 // Bitcast to the desired type.
11852 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11855 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11856 EVT VT = N->getValueType(0);
11858 unsigned NumInScalars = N->getNumOperands();
11861 EVT SrcVT = MVT::Other;
11862 unsigned Opcode = ISD::DELETED_NODE;
11863 unsigned NumDefs = 0;
11865 for (unsigned i = 0; i != NumInScalars; ++i) {
11866 SDValue In = N->getOperand(i);
11867 unsigned Opc = In.getOpcode();
11869 if (Opc == ISD::UNDEF)
11872 // If all scalar values are floats and converted from integers.
11873 if (Opcode == ISD::DELETED_NODE &&
11874 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11881 EVT InVT = In.getOperand(0).getValueType();
11883 // If all scalar values are typed differently, bail out. It's chosen to
11884 // simplify BUILD_VECTOR of integer types.
11885 if (SrcVT == MVT::Other)
11892 // If the vector has just one element defined, it's not worth to fold it into
11893 // a vectorized one.
11897 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11898 && "Should only handle conversion from integer to float.");
11899 assert(SrcVT != MVT::Other && "Cannot determine source type!");
11901 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11903 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11906 // Just because the floating-point vector type is legal does not necessarily
11907 // mean that the corresponding integer vector type is.
11908 if (!isTypeLegal(NVT))
11911 SmallVector<SDValue, 8> Opnds;
11912 for (unsigned i = 0; i != NumInScalars; ++i) {
11913 SDValue In = N->getOperand(i);
11915 if (In.getOpcode() == ISD::UNDEF)
11916 Opnds.push_back(DAG.getUNDEF(SrcVT));
11918 Opnds.push_back(In.getOperand(0));
11920 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11921 AddToWorklist(BV.getNode());
11923 return DAG.getNode(Opcode, dl, VT, BV);
11926 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11927 unsigned NumInScalars = N->getNumOperands();
11929 EVT VT = N->getValueType(0);
11931 // A vector built entirely of undefs is undef.
11932 if (ISD::allOperandsUndef(N))
11933 return DAG.getUNDEF(VT);
11935 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11938 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11941 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11942 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11943 // at most two distinct vectors, turn this into a shuffle node.
11945 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11946 if (!isTypeLegal(VT))
11949 // May only combine to shuffle after legalize if shuffle is legal.
11950 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11953 SDValue VecIn1, VecIn2;
11954 bool UsesZeroVector = false;
11955 for (unsigned i = 0; i != NumInScalars; ++i) {
11956 SDValue Op = N->getOperand(i);
11957 // Ignore undef inputs.
11958 if (Op.getOpcode() == ISD::UNDEF) continue;
11960 // See if we can combine this build_vector into a blend with a zero vector.
11961 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
11962 UsesZeroVector = true;
11966 // If this input is something other than a EXTRACT_VECTOR_ELT with a
11967 // constant index, bail out.
11968 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11969 !isa<ConstantSDNode>(Op.getOperand(1))) {
11970 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11974 // We allow up to two distinct input vectors.
11975 SDValue ExtractedFromVec = Op.getOperand(0);
11976 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11979 if (!VecIn1.getNode()) {
11980 VecIn1 = ExtractedFromVec;
11981 } else if (!VecIn2.getNode() && !UsesZeroVector) {
11982 VecIn2 = ExtractedFromVec;
11984 // Too many inputs.
11985 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11990 // If everything is good, we can make a shuffle operation.
11991 if (VecIn1.getNode()) {
11992 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11993 SmallVector<int, 8> Mask;
11994 for (unsigned i = 0; i != NumInScalars; ++i) {
11995 unsigned Opcode = N->getOperand(i).getOpcode();
11996 if (Opcode == ISD::UNDEF) {
11997 Mask.push_back(-1);
12001 // Operands can also be zero.
12002 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12003 assert(UsesZeroVector &&
12004 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12005 "Unexpected node found!");
12006 Mask.push_back(NumInScalars+i);
12010 // If extracting from the first vector, just use the index directly.
12011 SDValue Extract = N->getOperand(i);
12012 SDValue ExtVal = Extract.getOperand(1);
12013 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12014 if (Extract.getOperand(0) == VecIn1) {
12015 Mask.push_back(ExtIndex);
12019 // Otherwise, use InIdx + InputVecSize
12020 Mask.push_back(InNumElements + ExtIndex);
12023 // Avoid introducing illegal shuffles with zero.
12024 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12027 // We can't generate a shuffle node with mismatched input and output types.
12028 // Attempt to transform a single input vector to the correct type.
12029 if ((VT != VecIn1.getValueType())) {
12030 // If the input vector type has a different base type to the output
12031 // vector type, bail out.
12032 EVT VTElemType = VT.getVectorElementType();
12033 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12034 (VecIn2.getNode() &&
12035 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12038 // If the input vector is too small, widen it.
12039 // We only support widening of vectors which are half the size of the
12040 // output registers. For example XMM->YMM widening on X86 with AVX.
12041 EVT VecInT = VecIn1.getValueType();
12042 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12043 // If we only have one small input, widen it by adding undef values.
12044 if (!VecIn2.getNode())
12045 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12046 DAG.getUNDEF(VecIn1.getValueType()));
12047 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12048 // If we have two small inputs of the same type, try to concat them.
12049 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12050 VecIn2 = SDValue(nullptr, 0);
12053 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12054 // If the input vector is too large, try to split it.
12055 // We don't support having two input vectors that are too large.
12056 // If the zero vector was used, we can not split the vector,
12057 // since we'd need 3 inputs.
12058 if (UsesZeroVector || VecIn2.getNode())
12061 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12064 // Try to replace VecIn1 with two extract_subvectors
12065 // No need to update the masks, they should still be correct.
12066 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12067 DAG.getConstant(VT.getVectorNumElements(), dl, TLI.getVectorIdxTy()));
12068 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12069 DAG.getConstant(0, dl, TLI.getVectorIdxTy()));
12074 if (UsesZeroVector)
12075 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12076 DAG.getConstantFP(0.0, dl, VT);
12078 // If VecIn2 is unused then change it to undef.
12079 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12081 // Check that we were able to transform all incoming values to the same
12083 if (VecIn2.getValueType() != VecIn1.getValueType() ||
12084 VecIn1.getValueType() != VT)
12087 // Return the new VECTOR_SHUFFLE node.
12091 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12097 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12098 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12099 EVT OpVT = N->getOperand(0).getValueType();
12101 // If the operands are legal vectors, leave them alone.
12102 if (TLI.isTypeLegal(OpVT))
12106 EVT VT = N->getValueType(0);
12107 SmallVector<SDValue, 8> Ops;
12109 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12110 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12112 // Keep track of what we encounter.
12113 bool AnyInteger = false;
12114 bool AnyFP = false;
12115 for (const SDValue &Op : N->ops()) {
12116 if (ISD::BITCAST == Op.getOpcode() &&
12117 !Op.getOperand(0).getValueType().isVector())
12118 Ops.push_back(Op.getOperand(0));
12119 else if (ISD::UNDEF == Op.getOpcode())
12120 Ops.push_back(ScalarUndef);
12124 // Note whether we encounter an integer or floating point scalar.
12125 // If it's neither, bail out, it could be something weird like x86mmx.
12126 EVT LastOpVT = Ops.back().getValueType();
12127 if (LastOpVT.isFloatingPoint())
12129 else if (LastOpVT.isInteger())
12135 // If any of the operands is a floating point scalar bitcast to a vector,
12136 // use floating point types throughout, and bitcast everything.
12137 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12139 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12140 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12142 for (SDValue &Op : Ops) {
12143 if (Op.getValueType() == SVT)
12145 if (Op.getOpcode() == ISD::UNDEF)
12148 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12153 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12154 VT.getSizeInBits() / SVT.getSizeInBits());
12155 return DAG.getNode(ISD::BITCAST, DL, VT,
12156 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12159 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12160 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
12161 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
12162 // inputs come from at most two distinct vectors, turn this into a shuffle
12165 // If we only have one input vector, we don't need to do any concatenation.
12166 if (N->getNumOperands() == 1)
12167 return N->getOperand(0);
12169 // Check if all of the operands are undefs.
12170 EVT VT = N->getValueType(0);
12171 if (ISD::allOperandsUndef(N))
12172 return DAG.getUNDEF(VT);
12174 // Optimize concat_vectors where all but the first of the vectors are undef.
12175 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12176 return Op.getOpcode() == ISD::UNDEF;
12178 SDValue In = N->getOperand(0);
12179 assert(In.getValueType().isVector() && "Must concat vectors");
12181 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12182 if (In->getOpcode() == ISD::BITCAST &&
12183 !In->getOperand(0)->getValueType(0).isVector()) {
12184 SDValue Scalar = In->getOperand(0);
12186 // If the bitcast type isn't legal, it might be a trunc of a legal type;
12187 // look through the trunc so we can still do the transform:
12188 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12189 if (Scalar->getOpcode() == ISD::TRUNCATE &&
12190 !TLI.isTypeLegal(Scalar.getValueType()) &&
12191 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12192 Scalar = Scalar->getOperand(0);
12194 EVT SclTy = Scalar->getValueType(0);
12196 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12199 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12200 VT.getSizeInBits() / SclTy.getSizeInBits());
12201 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12204 SDLoc dl = SDLoc(N);
12205 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12206 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12210 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12211 // We have already tested above for an UNDEF only concatenation.
12212 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12213 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12214 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12215 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12217 bool AllBuildVectorsOrUndefs =
12218 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12219 if (AllBuildVectorsOrUndefs) {
12220 SmallVector<SDValue, 8> Opnds;
12221 EVT SVT = VT.getScalarType();
12224 if (!SVT.isFloatingPoint()) {
12225 // If BUILD_VECTOR are from built from integer, they may have different
12226 // operand types. Get the smallest type and truncate all operands to it.
12227 bool FoundMinVT = false;
12228 for (const SDValue &Op : N->ops())
12229 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12230 EVT OpSVT = Op.getOperand(0)->getValueType(0);
12231 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12234 assert(FoundMinVT && "Concat vector type mismatch");
12237 for (const SDValue &Op : N->ops()) {
12238 EVT OpVT = Op.getValueType();
12239 unsigned NumElts = OpVT.getVectorNumElements();
12241 if (ISD::UNDEF == Op.getOpcode())
12242 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12244 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12245 if (SVT.isFloatingPoint()) {
12246 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12247 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12249 for (unsigned i = 0; i != NumElts; ++i)
12251 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12256 assert(VT.getVectorNumElements() == Opnds.size() &&
12257 "Concat vector type mismatch");
12258 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12261 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12262 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12265 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12266 // nodes often generate nop CONCAT_VECTOR nodes.
12267 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12268 // place the incoming vectors at the exact same location.
12269 SDValue SingleSource = SDValue();
12270 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12272 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12273 SDValue Op = N->getOperand(i);
12275 if (Op.getOpcode() == ISD::UNDEF)
12278 // Check if this is the identity extract:
12279 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12282 // Find the single incoming vector for the extract_subvector.
12283 if (SingleSource.getNode()) {
12284 if (Op.getOperand(0) != SingleSource)
12287 SingleSource = Op.getOperand(0);
12289 // Check the source type is the same as the type of the result.
12290 // If not, this concat may extend the vector, so we can not
12291 // optimize it away.
12292 if (SingleSource.getValueType() != N->getValueType(0))
12296 unsigned IdentityIndex = i * PartNumElem;
12297 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12298 // The extract index must be constant.
12302 // Check that we are reading from the identity index.
12303 if (CS->getZExtValue() != IdentityIndex)
12307 if (SingleSource.getNode())
12308 return SingleSource;
12313 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12314 EVT NVT = N->getValueType(0);
12315 SDValue V = N->getOperand(0);
12317 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12319 // (extract_subvec (concat V1, V2, ...), i)
12322 // Only operand 0 is checked as 'concat' assumes all inputs of the same
12324 if (V->getOperand(0).getValueType() != NVT)
12326 unsigned Idx = N->getConstantOperandVal(1);
12327 unsigned NumElems = NVT.getVectorNumElements();
12328 assert((Idx % NumElems) == 0 &&
12329 "IDX in concat is not a multiple of the result vector length.");
12330 return V->getOperand(Idx / NumElems);
12334 if (V->getOpcode() == ISD::BITCAST)
12335 V = V.getOperand(0);
12337 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12339 // Handle only simple case where vector being inserted and vector
12340 // being extracted are of same type, and are half size of larger vectors.
12341 EVT BigVT = V->getOperand(0).getValueType();
12342 EVT SmallVT = V->getOperand(1).getValueType();
12343 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12346 // Only handle cases where both indexes are constants with the same type.
12347 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12348 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12350 if (InsIdx && ExtIdx &&
12351 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12352 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12354 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12356 // indices are equal or bit offsets are equal => V1
12357 // otherwise => (extract_subvec V1, ExtIdx)
12358 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12359 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12360 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12361 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12362 DAG.getNode(ISD::BITCAST, dl,
12363 N->getOperand(0).getValueType(),
12364 V->getOperand(0)), N->getOperand(1));
12371 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12372 SDValue V, SelectionDAG &DAG) {
12374 EVT VT = V.getValueType();
12376 switch (V.getOpcode()) {
12380 case ISD::CONCAT_VECTORS: {
12381 EVT OpVT = V->getOperand(0).getValueType();
12382 int OpSize = OpVT.getVectorNumElements();
12383 SmallBitVector OpUsedElements(OpSize, false);
12384 bool FoundSimplification = false;
12385 SmallVector<SDValue, 4> NewOps;
12386 NewOps.reserve(V->getNumOperands());
12387 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12388 SDValue Op = V->getOperand(i);
12389 bool OpUsed = false;
12390 for (int j = 0; j < OpSize; ++j)
12391 if (UsedElements[i * OpSize + j]) {
12392 OpUsedElements[j] = true;
12396 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12397 : DAG.getUNDEF(OpVT));
12398 FoundSimplification |= Op == NewOps.back();
12399 OpUsedElements.reset();
12401 if (FoundSimplification)
12402 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12406 case ISD::INSERT_SUBVECTOR: {
12407 SDValue BaseV = V->getOperand(0);
12408 SDValue SubV = V->getOperand(1);
12409 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12413 int SubSize = SubV.getValueType().getVectorNumElements();
12414 int Idx = IdxN->getZExtValue();
12415 bool SubVectorUsed = false;
12416 SmallBitVector SubUsedElements(SubSize, false);
12417 for (int i = 0; i < SubSize; ++i)
12418 if (UsedElements[i + Idx]) {
12419 SubVectorUsed = true;
12420 SubUsedElements[i] = true;
12421 UsedElements[i + Idx] = false;
12424 // Now recurse on both the base and sub vectors.
12425 SDValue SimplifiedSubV =
12427 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12428 : DAG.getUNDEF(SubV.getValueType());
12429 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12430 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12431 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12432 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12438 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12439 SDValue N1, SelectionDAG &DAG) {
12440 EVT VT = SVN->getValueType(0);
12441 int NumElts = VT.getVectorNumElements();
12442 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12443 for (int M : SVN->getMask())
12444 if (M >= 0 && M < NumElts)
12445 N0UsedElements[M] = true;
12446 else if (M >= NumElts)
12447 N1UsedElements[M - NumElts] = true;
12449 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12450 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12451 if (S0 == N0 && S1 == N1)
12454 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12457 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12458 // or turn a shuffle of a single concat into simpler shuffle then concat.
12459 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12460 EVT VT = N->getValueType(0);
12461 unsigned NumElts = VT.getVectorNumElements();
12463 SDValue N0 = N->getOperand(0);
12464 SDValue N1 = N->getOperand(1);
12465 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12467 SmallVector<SDValue, 4> Ops;
12468 EVT ConcatVT = N0.getOperand(0).getValueType();
12469 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12470 unsigned NumConcats = NumElts / NumElemsPerConcat;
12472 // Special case: shuffle(concat(A,B)) can be more efficiently represented
12473 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12474 // half vector elements.
12475 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12476 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12477 SVN->getMask().end(), [](int i) { return i == -1; })) {
12478 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12479 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12480 N1 = DAG.getUNDEF(ConcatVT);
12481 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12484 // Look at every vector that's inserted. We're looking for exact
12485 // subvector-sized copies from a concatenated vector
12486 for (unsigned I = 0; I != NumConcats; ++I) {
12487 // Make sure we're dealing with a copy.
12488 unsigned Begin = I * NumElemsPerConcat;
12489 bool AllUndef = true, NoUndef = true;
12490 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12491 if (SVN->getMaskElt(J) >= 0)
12498 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12501 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12502 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12505 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12506 if (FirstElt < N0.getNumOperands())
12507 Ops.push_back(N0.getOperand(FirstElt));
12509 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12511 } else if (AllUndef) {
12512 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12513 } else { // Mixed with general masks and undefs, can't do optimization.
12518 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12521 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12522 EVT VT = N->getValueType(0);
12523 unsigned NumElts = VT.getVectorNumElements();
12525 SDValue N0 = N->getOperand(0);
12526 SDValue N1 = N->getOperand(1);
12528 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12530 // Canonicalize shuffle undef, undef -> undef
12531 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12532 return DAG.getUNDEF(VT);
12534 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12536 // Canonicalize shuffle v, v -> v, undef
12538 SmallVector<int, 8> NewMask;
12539 for (unsigned i = 0; i != NumElts; ++i) {
12540 int Idx = SVN->getMaskElt(i);
12541 if (Idx >= (int)NumElts) Idx -= NumElts;
12542 NewMask.push_back(Idx);
12544 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12548 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
12549 if (N0.getOpcode() == ISD::UNDEF) {
12550 SmallVector<int, 8> NewMask;
12551 for (unsigned i = 0; i != NumElts; ++i) {
12552 int Idx = SVN->getMaskElt(i);
12554 if (Idx >= (int)NumElts)
12557 Idx = -1; // remove reference to lhs
12559 NewMask.push_back(Idx);
12561 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12565 // Remove references to rhs if it is undef
12566 if (N1.getOpcode() == ISD::UNDEF) {
12567 bool Changed = false;
12568 SmallVector<int, 8> NewMask;
12569 for (unsigned i = 0; i != NumElts; ++i) {
12570 int Idx = SVN->getMaskElt(i);
12571 if (Idx >= (int)NumElts) {
12575 NewMask.push_back(Idx);
12578 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12581 // If it is a splat, check if the argument vector is another splat or a
12583 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12584 SDNode *V = N0.getNode();
12586 // If this is a bit convert that changes the element type of the vector but
12587 // not the number of vector elements, look through it. Be careful not to
12588 // look though conversions that change things like v4f32 to v2f64.
12589 if (V->getOpcode() == ISD::BITCAST) {
12590 SDValue ConvInput = V->getOperand(0);
12591 if (ConvInput.getValueType().isVector() &&
12592 ConvInput.getValueType().getVectorNumElements() == NumElts)
12593 V = ConvInput.getNode();
12596 if (V->getOpcode() == ISD::BUILD_VECTOR) {
12597 assert(V->getNumOperands() == NumElts &&
12598 "BUILD_VECTOR has wrong number of operands");
12600 bool AllSame = true;
12601 for (unsigned i = 0; i != NumElts; ++i) {
12602 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12603 Base = V->getOperand(i);
12607 // Splat of <u, u, u, u>, return <u, u, u, u>
12608 if (!Base.getNode())
12610 for (unsigned i = 0; i != NumElts; ++i) {
12611 if (V->getOperand(i) != Base) {
12616 // Splat of <x, x, x, x>, return <x, x, x, x>
12620 // Canonicalize any other splat as a build_vector.
12621 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12622 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12623 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12624 V->getValueType(0), Ops);
12626 // We may have jumped through bitcasts, so the type of the
12627 // BUILD_VECTOR may not match the type of the shuffle.
12628 if (V->getValueType(0) != VT)
12629 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12634 // There are various patterns used to build up a vector from smaller vectors,
12635 // subvectors, or elements. Scan chains of these and replace unused insertions
12636 // or components with undef.
12637 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12640 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12641 Level < AfterLegalizeVectorOps &&
12642 (N1.getOpcode() == ISD::UNDEF ||
12643 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12644 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12645 SDValue V = partitionShuffleOfConcats(N, DAG);
12651 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12652 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12653 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12654 SmallVector<SDValue, 8> Ops;
12655 for (int M : SVN->getMask()) {
12656 SDValue Op = DAG.getUNDEF(VT.getScalarType());
12658 int Idx = M % NumElts;
12659 SDValue &S = (M < (int)NumElts ? N0 : N1);
12660 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12661 Op = S.getOperand(Idx);
12662 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12664 Op = S.getOperand(0);
12666 // Operand can't be combined - bail out.
12672 if (Ops.size() == VT.getVectorNumElements()) {
12673 // BUILD_VECTOR requires all inputs to be of the same type, find the
12674 // maximum type and extend them all.
12675 EVT SVT = VT.getScalarType();
12676 if (SVT.isInteger())
12677 for (SDValue &Op : Ops)
12678 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12679 if (SVT != VT.getScalarType())
12680 for (SDValue &Op : Ops)
12681 Op = TLI.isZExtFree(Op.getValueType(), SVT)
12682 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12683 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12684 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12688 // If this shuffle only has a single input that is a bitcasted shuffle,
12689 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12690 // back to their original types.
12691 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12692 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12693 TLI.isTypeLegal(VT)) {
12695 // Peek through the bitcast only if there is one user.
12697 while (BC0.getOpcode() == ISD::BITCAST) {
12698 if (!BC0.hasOneUse())
12700 BC0 = BC0.getOperand(0);
12703 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12705 return SmallVector<int, 8>(Mask.begin(), Mask.end());
12707 SmallVector<int, 8> NewMask;
12709 for (int s = 0; s != Scale; ++s)
12710 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12714 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12715 EVT SVT = VT.getScalarType();
12716 EVT InnerVT = BC0->getValueType(0);
12717 EVT InnerSVT = InnerVT.getScalarType();
12719 // Determine which shuffle works with the smaller scalar type.
12720 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12721 EVT ScaleSVT = ScaleVT.getScalarType();
12723 if (TLI.isTypeLegal(ScaleVT) &&
12724 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12725 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12727 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12728 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12730 // Scale the shuffle masks to the smaller scalar type.
12731 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12732 SmallVector<int, 8> InnerMask =
12733 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12734 SmallVector<int, 8> OuterMask =
12735 ScaleShuffleMask(SVN->getMask(), OuterScale);
12737 // Merge the shuffle masks.
12738 SmallVector<int, 8> NewMask;
12739 for (int M : OuterMask)
12740 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12742 // Test for shuffle mask legality over both commutations.
12743 SDValue SV0 = BC0->getOperand(0);
12744 SDValue SV1 = BC0->getOperand(1);
12745 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12747 std::swap(SV0, SV1);
12748 ShuffleVectorSDNode::commuteMask(NewMask);
12749 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12753 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12754 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12755 return DAG.getNode(
12756 ISD::BITCAST, SDLoc(N), VT,
12757 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12763 // Canonicalize shuffles according to rules:
12764 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12765 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12766 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12767 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12768 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12769 TLI.isTypeLegal(VT)) {
12770 // The incoming shuffle must be of the same type as the result of the
12771 // current shuffle.
12772 assert(N1->getOperand(0).getValueType() == VT &&
12773 "Shuffle types don't match");
12775 SDValue SV0 = N1->getOperand(0);
12776 SDValue SV1 = N1->getOperand(1);
12777 bool HasSameOp0 = N0 == SV0;
12778 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12779 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12780 // Commute the operands of this shuffle so that next rule
12782 return DAG.getCommutedVectorShuffle(*SVN);
12785 // Try to fold according to rules:
12786 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12787 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12788 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12789 // Don't try to fold shuffles with illegal type.
12790 // Only fold if this shuffle is the only user of the other shuffle.
12791 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12792 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12793 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12795 // The incoming shuffle must be of the same type as the result of the
12796 // current shuffle.
12797 assert(OtherSV->getOperand(0).getValueType() == VT &&
12798 "Shuffle types don't match");
12801 SmallVector<int, 4> Mask;
12802 // Compute the combined shuffle mask for a shuffle with SV0 as the first
12803 // operand, and SV1 as the second operand.
12804 for (unsigned i = 0; i != NumElts; ++i) {
12805 int Idx = SVN->getMaskElt(i);
12807 // Propagate Undef.
12808 Mask.push_back(Idx);
12812 SDValue CurrentVec;
12813 if (Idx < (int)NumElts) {
12814 // This shuffle index refers to the inner shuffle N0. Lookup the inner
12815 // shuffle mask to identify which vector is actually referenced.
12816 Idx = OtherSV->getMaskElt(Idx);
12818 // Propagate Undef.
12819 Mask.push_back(Idx);
12823 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12824 : OtherSV->getOperand(1);
12826 // This shuffle index references an element within N1.
12830 // Simple case where 'CurrentVec' is UNDEF.
12831 if (CurrentVec.getOpcode() == ISD::UNDEF) {
12832 Mask.push_back(-1);
12836 // Canonicalize the shuffle index. We don't know yet if CurrentVec
12837 // will be the first or second operand of the combined shuffle.
12838 Idx = Idx % NumElts;
12839 if (!SV0.getNode() || SV0 == CurrentVec) {
12840 // Ok. CurrentVec is the left hand side.
12841 // Update the mask accordingly.
12843 Mask.push_back(Idx);
12847 // Bail out if we cannot convert the shuffle pair into a single shuffle.
12848 if (SV1.getNode() && SV1 != CurrentVec)
12851 // Ok. CurrentVec is the right hand side.
12852 // Update the mask accordingly.
12854 Mask.push_back(Idx + NumElts);
12857 // Check if all indices in Mask are Undef. In case, propagate Undef.
12858 bool isUndefMask = true;
12859 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12860 isUndefMask &= Mask[i] < 0;
12863 return DAG.getUNDEF(VT);
12865 if (!SV0.getNode())
12866 SV0 = DAG.getUNDEF(VT);
12867 if (!SV1.getNode())
12868 SV1 = DAG.getUNDEF(VT);
12870 // Avoid introducing shuffles with illegal mask.
12871 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12872 ShuffleVectorSDNode::commuteMask(Mask);
12874 if (!TLI.isShuffleMaskLegal(Mask, VT))
12877 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12878 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12879 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12880 std::swap(SV0, SV1);
12883 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12884 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12885 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12886 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12892 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12893 SDValue InVal = N->getOperand(0);
12894 EVT VT = N->getValueType(0);
12896 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12897 // with a VECTOR_SHUFFLE.
12898 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12899 SDValue InVec = InVal->getOperand(0);
12900 SDValue EltNo = InVal->getOperand(1);
12902 // FIXME: We could support implicit truncation if the shuffle can be
12903 // scaled to a smaller vector scalar type.
12904 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12905 if (C0 && VT == InVec.getValueType() &&
12906 VT.getScalarType() == InVal.getValueType()) {
12907 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12908 int Elt = C0->getZExtValue();
12911 if (TLI.isShuffleMaskLegal(NewMask, VT))
12912 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12920 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12921 SDValue N0 = N->getOperand(0);
12922 SDValue N2 = N->getOperand(2);
12924 // If the input vector is a concatenation, and the insert replaces
12925 // one of the halves, we can optimize into a single concat_vectors.
12926 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12927 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12928 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12929 EVT VT = N->getValueType(0);
12931 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12932 // (concat_vectors Z, Y)
12934 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12935 N->getOperand(1), N0.getOperand(1));
12937 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12938 // (concat_vectors X, Z)
12939 if (InsIdx == VT.getVectorNumElements()/2)
12940 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12941 N0.getOperand(0), N->getOperand(1));
12947 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12948 SDValue N0 = N->getOperand(0);
12950 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12951 if (N0->getOpcode() == ISD::FP16_TO_FP)
12952 return N0->getOperand(0);
12957 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12958 /// with the destination vector and a zero vector.
12959 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12960 /// vector_shuffle V, Zero, <0, 4, 2, 4>
12961 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12962 EVT VT = N->getValueType(0);
12963 SDValue LHS = N->getOperand(0);
12964 SDValue RHS = N->getOperand(1);
12967 // Make sure we're not running after operation legalization where it
12968 // may have custom lowered the vector shuffles.
12969 if (LegalOperations)
12972 if (N->getOpcode() != ISD::AND)
12975 if (RHS.getOpcode() == ISD::BITCAST)
12976 RHS = RHS.getOperand(0);
12978 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12979 SmallVector<int, 8> Indices;
12980 unsigned NumElts = RHS.getNumOperands();
12982 for (unsigned i = 0; i != NumElts; ++i) {
12983 SDValue Elt = RHS.getOperand(i);
12984 if (isAllOnesConstant(Elt))
12985 Indices.push_back(i);
12986 else if (isNullConstant(Elt))
12987 Indices.push_back(NumElts+i);
12992 // Let's see if the target supports this vector_shuffle.
12993 EVT RVT = RHS.getValueType();
12994 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12997 // Return the new VECTOR_SHUFFLE node.
12998 EVT EltVT = RVT.getVectorElementType();
12999 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
13000 DAG.getConstant(0, dl, EltVT));
13001 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps);
13002 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
13003 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
13004 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
13010 /// Visit a binary vector operation, like ADD.
13011 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13012 assert(N->getValueType(0).isVector() &&
13013 "SimplifyVBinOp only works on vectors!");
13015 SDValue LHS = N->getOperand(0);
13016 SDValue RHS = N->getOperand(1);
13018 if (SDValue Shuffle = XformToShuffleWithZero(N))
13021 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
13023 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
13024 RHS.getOpcode() == ISD::BUILD_VECTOR) {
13025 // Check if both vectors are constants. If not bail out.
13026 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
13027 cast<BuildVectorSDNode>(RHS)->isConstant()))
13030 SmallVector<SDValue, 8> Ops;
13031 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
13032 SDValue LHSOp = LHS.getOperand(i);
13033 SDValue RHSOp = RHS.getOperand(i);
13035 // Can't fold divide by zero.
13036 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
13037 N->getOpcode() == ISD::FDIV) {
13038 if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP &&
13039 cast<ConstantFPSDNode>(RHSOp.getNode())->isZero()))
13043 EVT VT = LHSOp.getValueType();
13044 EVT RVT = RHSOp.getValueType();
13046 // Integer BUILD_VECTOR operands may have types larger than the element
13047 // size (e.g., when the element type is not legal). Prior to type
13048 // legalization, the types may not match between the two BUILD_VECTORS.
13049 // Truncate one of the operands to make them match.
13050 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
13051 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
13053 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
13057 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
13059 if (FoldOp.getOpcode() != ISD::UNDEF &&
13060 FoldOp.getOpcode() != ISD::Constant &&
13061 FoldOp.getOpcode() != ISD::ConstantFP)
13063 Ops.push_back(FoldOp);
13064 AddToWorklist(FoldOp.getNode());
13067 if (Ops.size() == LHS.getNumOperands())
13068 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
13071 // Type legalization might introduce new shuffles in the DAG.
13072 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13073 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
13074 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13075 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13076 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13077 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13078 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13079 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13081 if (SVN0->getMask().equals(SVN1->getMask())) {
13082 EVT VT = N->getValueType(0);
13083 SDValue UndefVector = LHS.getOperand(1);
13084 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13085 LHS.getOperand(0), RHS.getOperand(0));
13086 AddUsersToWorklist(N);
13087 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13088 &SVN0->getMask()[0]);
13095 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13096 SDValue N1, SDValue N2){
13097 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13099 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13100 cast<CondCodeSDNode>(N0.getOperand(2))->get());
13102 // If we got a simplified select_cc node back from SimplifySelectCC, then
13103 // break it down into a new SETCC node, and a new SELECT node, and then return
13104 // the SELECT node, since we were called with a SELECT node.
13105 if (SCC.getNode()) {
13106 // Check to see if we got a select_cc back (to turn into setcc/select).
13107 // Otherwise, just return whatever node we got back, like fabs.
13108 if (SCC.getOpcode() == ISD::SELECT_CC) {
13109 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13111 SCC.getOperand(0), SCC.getOperand(1),
13112 SCC.getOperand(4));
13113 AddToWorklist(SETCC.getNode());
13114 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13115 SCC.getOperand(2), SCC.getOperand(3));
13123 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13124 /// being selected between, see if we can simplify the select. Callers of this
13125 /// should assume that TheSelect is deleted if this returns true. As such, they
13126 /// should return the appropriate thing (e.g. the node) back to the top-level of
13127 /// the DAG combiner loop to avoid it being looked at.
13128 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13131 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13132 // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13133 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13134 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13135 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13136 SDValue Sqrt = RHS;
13139 const ConstantFPSDNode *NegZero = nullptr;
13141 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13142 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13143 CmpLHS = TheSelect->getOperand(0);
13144 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13146 // SELECT or VSELECT
13147 SDValue Cmp = TheSelect->getOperand(0);
13148 if (Cmp.getOpcode() == ISD::SETCC) {
13149 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13150 CmpLHS = Cmp.getOperand(0);
13151 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13154 if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13155 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13156 CC == ISD::SETULT || CC == ISD::SETLT)) {
13157 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13158 CombineTo(TheSelect, Sqrt);
13163 // Cannot simplify select with vector condition
13164 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13166 // If this is a select from two identical things, try to pull the operation
13167 // through the select.
13168 if (LHS.getOpcode() != RHS.getOpcode() ||
13169 !LHS.hasOneUse() || !RHS.hasOneUse())
13172 // If this is a load and the token chain is identical, replace the select
13173 // of two loads with a load through a select of the address to load from.
13174 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13175 // constants have been dropped into the constant pool.
13176 if (LHS.getOpcode() == ISD::LOAD) {
13177 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13178 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13180 // Token chains must be identical.
13181 if (LHS.getOperand(0) != RHS.getOperand(0) ||
13182 // Do not let this transformation reduce the number of volatile loads.
13183 LLD->isVolatile() || RLD->isVolatile() ||
13184 // FIXME: If either is a pre/post inc/dec load,
13185 // we'd need to split out the address adjustment.
13186 LLD->isIndexed() || RLD->isIndexed() ||
13187 // If this is an EXTLOAD, the VT's must match.
13188 LLD->getMemoryVT() != RLD->getMemoryVT() ||
13189 // If this is an EXTLOAD, the kind of extension must match.
13190 (LLD->getExtensionType() != RLD->getExtensionType() &&
13191 // The only exception is if one of the extensions is anyext.
13192 LLD->getExtensionType() != ISD::EXTLOAD &&
13193 RLD->getExtensionType() != ISD::EXTLOAD) ||
13194 // FIXME: this discards src value information. This is
13195 // over-conservative. It would be beneficial to be able to remember
13196 // both potential memory locations. Since we are discarding
13197 // src value info, don't do the transformation if the memory
13198 // locations are not in the default address space.
13199 LLD->getPointerInfo().getAddrSpace() != 0 ||
13200 RLD->getPointerInfo().getAddrSpace() != 0 ||
13201 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13202 LLD->getBasePtr().getValueType()))
13205 // Check that the select condition doesn't reach either load. If so,
13206 // folding this will induce a cycle into the DAG. If not, this is safe to
13207 // xform, so create a select of the addresses.
13209 if (TheSelect->getOpcode() == ISD::SELECT) {
13210 SDNode *CondNode = TheSelect->getOperand(0).getNode();
13211 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13212 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13214 // The loads must not depend on one another.
13215 if (LLD->isPredecessorOf(RLD) ||
13216 RLD->isPredecessorOf(LLD))
13218 Addr = DAG.getSelect(SDLoc(TheSelect),
13219 LLD->getBasePtr().getValueType(),
13220 TheSelect->getOperand(0), LLD->getBasePtr(),
13221 RLD->getBasePtr());
13222 } else { // Otherwise SELECT_CC
13223 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13224 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13226 if ((LLD->hasAnyUseOfValue(1) &&
13227 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13228 (RLD->hasAnyUseOfValue(1) &&
13229 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13232 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13233 LLD->getBasePtr().getValueType(),
13234 TheSelect->getOperand(0),
13235 TheSelect->getOperand(1),
13236 LLD->getBasePtr(), RLD->getBasePtr(),
13237 TheSelect->getOperand(4));
13241 // It is safe to replace the two loads if they have different alignments,
13242 // but the new load must be the minimum (most restrictive) alignment of the
13244 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13245 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13246 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13247 Load = DAG.getLoad(TheSelect->getValueType(0),
13249 // FIXME: Discards pointer and AA info.
13250 LLD->getChain(), Addr, MachinePointerInfo(),
13251 LLD->isVolatile(), LLD->isNonTemporal(),
13252 isInvariant, Alignment);
13254 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13255 RLD->getExtensionType() : LLD->getExtensionType(),
13257 TheSelect->getValueType(0),
13258 // FIXME: Discards pointer and AA info.
13259 LLD->getChain(), Addr, MachinePointerInfo(),
13260 LLD->getMemoryVT(), LLD->isVolatile(),
13261 LLD->isNonTemporal(), isInvariant, Alignment);
13264 // Users of the select now use the result of the load.
13265 CombineTo(TheSelect, Load);
13267 // Users of the old loads now use the new load's chain. We know the
13268 // old-load value is dead now.
13269 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13270 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13277 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13278 /// where 'cond' is the comparison specified by CC.
13279 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13280 SDValue N2, SDValue N3,
13281 ISD::CondCode CC, bool NotExtCompare) {
13282 // (x ? y : y) -> y.
13283 if (N2 == N3) return N2;
13285 EVT VT = N2.getValueType();
13286 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13287 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13289 // Determine if the condition we're dealing with is constant
13290 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13291 N0, N1, CC, DL, false);
13292 if (SCC.getNode()) AddToWorklist(SCC.getNode());
13294 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13295 // fold select_cc true, x, y -> x
13296 // fold select_cc false, x, y -> y
13297 return !SCCC->isNullValue() ? N2 : N3;
13300 // Check to see if we can simplify the select into an fabs node
13301 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13302 // Allow either -0.0 or 0.0
13303 if (CFP->isZero()) {
13304 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13305 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13306 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13307 N2 == N3.getOperand(0))
13308 return DAG.getNode(ISD::FABS, DL, VT, N0);
13310 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13311 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13312 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13313 N2.getOperand(0) == N3)
13314 return DAG.getNode(ISD::FABS, DL, VT, N3);
13318 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13319 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13320 // in it. This is a win when the constant is not otherwise available because
13321 // it replaces two constant pool loads with one. We only do this if the FP
13322 // type is known to be legal, because if it isn't, then we are before legalize
13323 // types an we want the other legalization to happen first (e.g. to avoid
13324 // messing with soft float) and if the ConstantFP is not legal, because if
13325 // it is legal, we may not need to store the FP constant in a constant pool.
13326 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13327 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13328 if (TLI.isTypeLegal(N2.getValueType()) &&
13329 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13330 TargetLowering::Legal &&
13331 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13332 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13333 // If both constants have multiple uses, then we won't need to do an
13334 // extra load, they are likely around in registers for other users.
13335 (TV->hasOneUse() || FV->hasOneUse())) {
13336 Constant *Elts[] = {
13337 const_cast<ConstantFP*>(FV->getConstantFPValue()),
13338 const_cast<ConstantFP*>(TV->getConstantFPValue())
13340 Type *FPTy = Elts[0]->getType();
13341 const DataLayout &TD = *TLI.getDataLayout();
13343 // Create a ConstantArray of the two constants.
13344 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13345 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
13346 TD.getPrefTypeAlignment(FPTy));
13347 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13349 // Get the offsets to the 0 and 1 element of the array so that we can
13350 // select between them.
13351 SDValue Zero = DAG.getIntPtrConstant(0, DL);
13352 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13353 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13355 SDValue Cond = DAG.getSetCC(DL,
13356 getSetCCResultType(N0.getValueType()),
13358 AddToWorklist(Cond.getNode());
13359 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13361 AddToWorklist(CstOffset.getNode());
13362 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13364 AddToWorklist(CPIdx.getNode());
13365 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13366 MachinePointerInfo::getConstantPool(), false,
13367 false, false, Alignment);
13371 // Check to see if we can perform the "gzip trick", transforming
13372 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13373 if (isNullConstant(N3) && CC == ISD::SETLT &&
13374 (isNullConstant(N1) || // (a < 0) ? b : 0
13375 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0
13376 EVT XType = N0.getValueType();
13377 EVT AType = N2.getValueType();
13378 if (XType.bitsGE(AType)) {
13379 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13380 // single-bit constant.
13381 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13382 unsigned ShCtV = N2C->getAPIntValue().logBase2();
13383 ShCtV = XType.getSizeInBits() - ShCtV - 1;
13384 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13385 getShiftAmountTy(N0.getValueType()));
13386 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13388 AddToWorklist(Shift.getNode());
13390 if (XType.bitsGT(AType)) {
13391 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13392 AddToWorklist(Shift.getNode());
13395 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13398 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13400 DAG.getConstant(XType.getSizeInBits() - 1,
13402 getShiftAmountTy(N0.getValueType())));
13403 AddToWorklist(Shift.getNode());
13405 if (XType.bitsGT(AType)) {
13406 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13407 AddToWorklist(Shift.getNode());
13410 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13414 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13415 // where y is has a single bit set.
13416 // A plaintext description would be, we can turn the SELECT_CC into an AND
13417 // when the condition can be materialized as an all-ones register. Any
13418 // single bit-test can be materialized as an all-ones register with
13419 // shift-left and shift-right-arith.
13420 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13421 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13422 SDValue AndLHS = N0->getOperand(0);
13423 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13424 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13425 // Shift the tested bit over the sign bit.
13426 APInt AndMask = ConstAndRHS->getAPIntValue();
13428 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13429 getShiftAmountTy(AndLHS.getValueType()));
13430 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13432 // Now arithmetic right shift it all the way over, so the result is either
13433 // all-ones, or zero.
13435 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13436 getShiftAmountTy(Shl.getValueType()));
13437 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13439 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13443 // fold select C, 16, 0 -> shl C, 4
13444 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13445 TLI.getBooleanContents(N0.getValueType()) ==
13446 TargetLowering::ZeroOrOneBooleanContent) {
13448 // If the caller doesn't want us to simplify this into a zext of a compare,
13450 if (NotExtCompare && N2C->isOne())
13453 // Get a SetCC of the condition
13454 // NOTE: Don't create a SETCC if it's not legal on this target.
13455 if (!LegalOperations ||
13456 TLI.isOperationLegal(ISD::SETCC,
13457 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13459 // cast from setcc result type to select result type
13461 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13463 if (N2.getValueType().bitsLT(SCC.getValueType()))
13464 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13465 N2.getValueType());
13467 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13468 N2.getValueType(), SCC);
13470 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13471 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13472 N2.getValueType(), SCC);
13475 AddToWorklist(SCC.getNode());
13476 AddToWorklist(Temp.getNode());
13481 // shl setcc result by log2 n2c
13482 return DAG.getNode(
13483 ISD::SHL, DL, N2.getValueType(), Temp,
13484 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13485 getShiftAmountTy(Temp.getValueType())));
13489 // Check to see if this is the equivalent of setcc
13490 // FIXME: Turn all of these into setcc if setcc if setcc is legal
13491 // otherwise, go ahead with the folds.
13492 if (0 && isNullConstant(N3) && isOneConstant(N2)) {
13493 EVT XType = N0.getValueType();
13494 if (!LegalOperations ||
13495 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13496 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13497 if (Res.getValueType() != VT)
13498 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13502 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13503 if (isNullConstant(N1) && CC == ISD::SETEQ &&
13504 (!LegalOperations ||
13505 TLI.isOperationLegal(ISD::CTLZ, XType))) {
13506 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13507 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13508 DAG.getConstant(Log2_32(XType.getSizeInBits()),
13510 getShiftAmountTy(Ctlz.getValueType())));
13512 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13513 if (isNullConstant(N1) && CC == ISD::SETGT) {
13515 SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13516 XType, DAG.getConstant(0, DL, XType), N0);
13517 SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13518 return DAG.getNode(ISD::SRL, DL, XType,
13519 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13520 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13521 getShiftAmountTy(XType)));
13523 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13524 if (isAllOnesConstant(N1) && CC == ISD::SETGT) {
13526 SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13527 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13528 getShiftAmountTy(N0.getValueType())));
13529 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13534 // Check to see if this is an integer abs.
13535 // select_cc setg[te] X, 0, X, -X ->
13536 // select_cc setgt X, -1, X, -X ->
13537 // select_cc setl[te] X, 0, -X, X ->
13538 // select_cc setlt X, 1, -X, X ->
13539 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13541 ConstantSDNode *SubC = nullptr;
13542 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13543 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13544 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13545 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13546 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13547 (N1C->isOne() && CC == ISD::SETLT)) &&
13548 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13549 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13551 EVT XType = N0.getValueType();
13552 if (SubC && SubC->isNullValue() && XType.isInteger()) {
13554 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13556 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13557 getShiftAmountTy(N0.getValueType())));
13558 SDValue Add = DAG.getNode(ISD::ADD, DL,
13560 AddToWorklist(Shift.getNode());
13561 AddToWorklist(Add.getNode());
13562 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13569 /// This is a stub for TargetLowering::SimplifySetCC.
13570 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13571 SDValue N1, ISD::CondCode Cond,
13572 SDLoc DL, bool foldBooleans) {
13573 TargetLowering::DAGCombinerInfo
13574 DagCombineInfo(DAG, Level, false, this);
13575 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13578 /// Given an ISD::SDIV node expressing a divide by constant, return
13579 /// a DAG expression to select that will generate the same value by multiplying
13580 /// by a magic number.
13581 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13582 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13583 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13587 // Avoid division by zero.
13588 if (C->isNullValue())
13591 std::vector<SDNode*> Built;
13593 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13595 for (SDNode *N : Built)
13600 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13601 /// DAG expression that will generate the same value by right shifting.
13602 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13603 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13607 // Avoid division by zero.
13608 if (C->isNullValue())
13611 std::vector<SDNode *> Built;
13612 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13614 for (SDNode *N : Built)
13619 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13620 /// expression that will generate the same value by multiplying by a magic
13622 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13623 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13624 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13628 // Avoid division by zero.
13629 if (C->isNullValue())
13632 std::vector<SDNode*> Built;
13634 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13636 for (SDNode *N : Built)
13641 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13642 if (Level >= AfterLegalizeDAG)
13645 // Expose the DAG combiner to the target combiner implementations.
13646 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13648 unsigned Iterations = 0;
13649 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13651 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13652 // For the reciprocal, we need to find the zero of the function:
13653 // F(X) = A X - 1 [which has a zero at X = 1/A]
13655 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13656 // does not require additional intermediate precision]
13657 EVT VT = Op.getValueType();
13659 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13661 AddToWorklist(Est.getNode());
13663 // Newton iterations: Est = Est + Est (1 - Arg * Est)
13664 for (unsigned i = 0; i < Iterations; ++i) {
13665 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13666 AddToWorklist(NewEst.getNode());
13668 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13669 AddToWorklist(NewEst.getNode());
13671 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13672 AddToWorklist(NewEst.getNode());
13674 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13675 AddToWorklist(Est.getNode());
13684 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13685 /// For the reciprocal sqrt, we need to find the zero of the function:
13686 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13688 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13689 /// As a result, we precompute A/2 prior to the iteration loop.
13690 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13691 unsigned Iterations) {
13692 EVT VT = Arg.getValueType();
13694 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13696 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13697 // this entire sequence requires only one FP constant.
13698 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13699 AddToWorklist(HalfArg.getNode());
13701 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13702 AddToWorklist(HalfArg.getNode());
13704 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13705 for (unsigned i = 0; i < Iterations; ++i) {
13706 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13707 AddToWorklist(NewEst.getNode());
13709 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13710 AddToWorklist(NewEst.getNode());
13712 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13713 AddToWorklist(NewEst.getNode());
13715 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13716 AddToWorklist(Est.getNode());
13721 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13722 /// For the reciprocal sqrt, we need to find the zero of the function:
13723 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13725 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13726 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13727 unsigned Iterations) {
13728 EVT VT = Arg.getValueType();
13730 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13731 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13733 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13734 for (unsigned i = 0; i < Iterations; ++i) {
13735 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13736 AddToWorklist(HalfEst.getNode());
13738 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13739 AddToWorklist(Est.getNode());
13741 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13742 AddToWorklist(Est.getNode());
13744 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13745 AddToWorklist(Est.getNode());
13747 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13748 AddToWorklist(Est.getNode());
13753 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13754 if (Level >= AfterLegalizeDAG)
13757 // Expose the DAG combiner to the target combiner implementations.
13758 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13759 unsigned Iterations = 0;
13760 bool UseOneConstNR = false;
13761 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13762 AddToWorklist(Est.getNode());
13764 Est = UseOneConstNR ?
13765 BuildRsqrtNROneConst(Op, Est, Iterations) :
13766 BuildRsqrtNRTwoConst(Op, Est, Iterations);
13774 /// Return true if base is a frame index, which is known not to alias with
13775 /// anything but itself. Provides base object and offset as results.
13776 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13777 const GlobalValue *&GV, const void *&CV) {
13778 // Assume it is a primitive operation.
13779 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13781 // If it's an adding a simple constant then integrate the offset.
13782 if (Base.getOpcode() == ISD::ADD) {
13783 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13784 Base = Base.getOperand(0);
13785 Offset += C->getZExtValue();
13789 // Return the underlying GlobalValue, and update the Offset. Return false
13790 // for GlobalAddressSDNode since the same GlobalAddress may be represented
13791 // by multiple nodes with different offsets.
13792 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13793 GV = G->getGlobal();
13794 Offset += G->getOffset();
13798 // Return the underlying Constant value, and update the Offset. Return false
13799 // for ConstantSDNodes since the same constant pool entry may be represented
13800 // by multiple nodes with different offsets.
13801 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13802 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13803 : (const void *)C->getConstVal();
13804 Offset += C->getOffset();
13807 // If it's any of the following then it can't alias with anything but itself.
13808 return isa<FrameIndexSDNode>(Base);
13811 /// Return true if there is any possibility that the two addresses overlap.
13812 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13813 // If they are the same then they must be aliases.
13814 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13816 // If they are both volatile then they cannot be reordered.
13817 if (Op0->isVolatile() && Op1->isVolatile()) return true;
13819 // Gather base node and offset information.
13820 SDValue Base1, Base2;
13821 int64_t Offset1, Offset2;
13822 const GlobalValue *GV1, *GV2;
13823 const void *CV1, *CV2;
13824 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13825 Base1, Offset1, GV1, CV1);
13826 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13827 Base2, Offset2, GV2, CV2);
13829 // If they have a same base address then check to see if they overlap.
13830 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13831 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13832 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13834 // It is possible for different frame indices to alias each other, mostly
13835 // when tail call optimization reuses return address slots for arguments.
13836 // To catch this case, look up the actual index of frame indices to compute
13837 // the real alias relationship.
13838 if (isFrameIndex1 && isFrameIndex2) {
13839 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13840 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13841 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13842 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13843 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13846 // Otherwise, if we know what the bases are, and they aren't identical, then
13847 // we know they cannot alias.
13848 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13851 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13852 // compared to the size and offset of the access, we may be able to prove they
13853 // do not alias. This check is conservative for now to catch cases created by
13854 // splitting vector types.
13855 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13856 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13857 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13858 Op1->getMemoryVT().getSizeInBits() >> 3) &&
13859 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13860 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13861 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13863 // There is no overlap between these relatively aligned accesses of similar
13864 // size, return no alias.
13865 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13866 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13870 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13872 : DAG.getSubtarget().useAA();
13874 if (CombinerAAOnlyFunc.getNumOccurrences() &&
13875 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13879 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13880 // Use alias analysis information.
13881 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13882 Op1->getSrcValueOffset());
13883 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13884 Op0->getSrcValueOffset() - MinOffset;
13885 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13886 Op1->getSrcValueOffset() - MinOffset;
13887 AliasResult AAResult =
13888 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
13889 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13890 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
13891 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13892 if (AAResult == NoAlias)
13896 // Otherwise we have to assume they alias.
13900 /// Walk up chain skipping non-aliasing memory nodes,
13901 /// looking for aliasing nodes and adding them to the Aliases vector.
13902 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13903 SmallVectorImpl<SDValue> &Aliases) {
13904 SmallVector<SDValue, 8> Chains; // List of chains to visit.
13905 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
13907 // Get alias information for node.
13908 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13911 Chains.push_back(OriginalChain);
13912 unsigned Depth = 0;
13914 // Look at each chain and determine if it is an alias. If so, add it to the
13915 // aliases list. If not, then continue up the chain looking for the next
13917 while (!Chains.empty()) {
13918 SDValue Chain = Chains.back();
13921 // For TokenFactor nodes, look at each operand and only continue up the
13922 // chain until we find two aliases. If we've seen two aliases, assume we'll
13923 // find more and revert to original chain since the xform is unlikely to be
13926 // FIXME: The depth check could be made to return the last non-aliasing
13927 // chain we found before we hit a tokenfactor rather than the original
13929 if (Depth > 6 || Aliases.size() == 2) {
13931 Aliases.push_back(OriginalChain);
13935 // Don't bother if we've been before.
13936 if (!Visited.insert(Chain.getNode()).second)
13939 switch (Chain.getOpcode()) {
13940 case ISD::EntryToken:
13941 // Entry token is ideal chain operand, but handled in FindBetterChain.
13946 // Get alias information for Chain.
13947 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13948 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13950 // If chain is alias then stop here.
13951 if (!(IsLoad && IsOpLoad) &&
13952 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13953 Aliases.push_back(Chain);
13955 // Look further up the chain.
13956 Chains.push_back(Chain.getOperand(0));
13962 case ISD::TokenFactor:
13963 // We have to check each of the operands of the token factor for "small"
13964 // token factors, so we queue them up. Adding the operands to the queue
13965 // (stack) in reverse order maintains the original order and increases the
13966 // likelihood that getNode will find a matching token factor (CSE.)
13967 if (Chain.getNumOperands() > 16) {
13968 Aliases.push_back(Chain);
13971 for (unsigned n = Chain.getNumOperands(); n;)
13972 Chains.push_back(Chain.getOperand(--n));
13977 // For all other instructions we will just have to take what we can get.
13978 Aliases.push_back(Chain);
13983 // We need to be careful here to also search for aliases through the
13984 // value operand of a store, etc. Consider the following situation:
13986 // L1 = load Token1, %52
13987 // S1 = store Token1, L1, %51
13988 // L2 = load Token1, %52+8
13989 // S2 = store Token1, L2, %51+8
13990 // Token2 = Token(S1, S2)
13991 // L3 = load Token2, %53
13992 // S3 = store Token2, L3, %52
13993 // L4 = load Token2, %53+8
13994 // S4 = store Token2, L4, %52+8
13995 // If we search for aliases of S3 (which loads address %52), and we look
13996 // only through the chain, then we'll miss the trivial dependence on L1
13997 // (which also loads from %52). We then might change all loads and
13998 // stores to use Token1 as their chain operand, which could result in
13999 // copying %53 into %52 before copying %52 into %51 (which should
14002 // The problem is, however, that searching for such data dependencies
14003 // can become expensive, and the cost is not directly related to the
14004 // chain depth. Instead, we'll rule out such configurations here by
14005 // insisting that we've visited all chain users (except for users
14006 // of the original chain, which is not necessary). When doing this,
14007 // we need to look through nodes we don't care about (otherwise, things
14008 // like register copies will interfere with trivial cases).
14010 SmallVector<const SDNode *, 16> Worklist;
14011 for (const SDNode *N : Visited)
14012 if (N != OriginalChain.getNode())
14013 Worklist.push_back(N);
14015 while (!Worklist.empty()) {
14016 const SDNode *M = Worklist.pop_back_val();
14018 // We have already visited M, and want to make sure we've visited any uses
14019 // of M that we care about. For uses that we've not visisted, and don't
14020 // care about, queue them to the worklist.
14022 for (SDNode::use_iterator UI = M->use_begin(),
14023 UIE = M->use_end(); UI != UIE; ++UI)
14024 if (UI.getUse().getValueType() == MVT::Other &&
14025 Visited.insert(*UI).second) {
14026 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
14027 // We've not visited this use, and we care about it (it could have an
14028 // ordering dependency with the original node).
14030 Aliases.push_back(OriginalChain);
14034 // We've not visited this use, but we don't care about it. Mark it as
14035 // visited and enqueue it to the worklist.
14036 Worklist.push_back(*UI);
14041 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14042 /// (aliasing node.)
14043 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14044 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
14046 // Accumulate all the aliases to this node.
14047 GatherAllAliases(N, OldChain, Aliases);
14049 // If no operands then chain to entry token.
14050 if (Aliases.size() == 0)
14051 return DAG.getEntryNode();
14053 // If a single operand then chain to it. We don't need to revisit it.
14054 if (Aliases.size() == 1)
14057 // Construct a custom tailored token factor.
14058 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14061 /// This is the entry point for the file.
14062 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14063 CodeGenOpt::Level OptLevel) {
14064 /// This is the main entry point to this class.
14065 DAGCombiner(*this, AA, OptLevel).Run(Level);