1 //===- LegalizeVectorOps.cpp - Implement SelectionDAG::LegalizeVectors ----===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the SelectionDAG::LegalizeVectors method.
11 // The vector legalizer looks for vector operations which might need to be
12 // scalarized and legalizes them. This is a separate step from Legalize because
13 // scalarizing can introduce illegal types. For example, suppose we have an
14 // ISD::SDIV of type v2i64 on x86-32. The type is legal (for example, addition
15 // on a v2i64 is legal), but ISD::SDIV isn't legal, so we have to unroll the
16 // operation, which introduces nodes with the illegal type i64 which must be
17 // expanded. Similarly, suppose we have an ISD::SRA of type v16i8 on PowerPC;
18 // the operation must be unrolled, which introduces nodes with the illegal
19 // type i8 which must be promoted.
21 // This does not legalize vector manipulations like ISD::BUILD_VECTOR,
22 // or operations that happen to take a vector which are custom-lowered;
23 // the legalization for such operations never produces nodes
24 // with illegal types, so it's okay to put off legalizing them until
25 // SelectionDAG::Legalize runs.
27 //===----------------------------------------------------------------------===//
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/CodeGen/ISDOpcodes.h"
32 #include "llvm/CodeGen/SelectionDAG.h"
33 #include "llvm/CodeGen/SelectionDAGNodes.h"
34 #include "llvm/CodeGen/TargetLowering.h"
35 #include "llvm/CodeGen/ValueTypes.h"
36 #include "llvm/IR/DataLayout.h"
37 #include "llvm/Support/Casting.h"
38 #include "llvm/Support/Compiler.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/MachineValueType.h"
49 #define DEBUG_TYPE "legalizevectorops"
53 class VectorLegalizer {
55 const TargetLowering &TLI;
56 bool Changed = false; // Keep track of whether anything changed
58 /// For nodes that are of legal width, and that have more than one use, this
59 /// map indicates what regularized operand to use. This allows us to avoid
60 /// legalizing the same thing more than once.
61 SmallDenseMap<SDValue, SDValue, 64> LegalizedNodes;
63 /// Adds a node to the translation cache.
64 void AddLegalizedOperand(SDValue From, SDValue To) {
65 LegalizedNodes.insert(std::make_pair(From, To));
66 // If someone requests legalization of the new node, return itself.
68 LegalizedNodes.insert(std::make_pair(To, To));
71 /// Legalizes the given node.
72 SDValue LegalizeOp(SDValue Op);
74 /// Assuming the node is legal, "legalize" the results.
75 SDValue TranslateLegalizeResults(SDValue Op, SDNode *Result);
77 /// Make sure Results are legal and update the translation cache.
78 SDValue RecursivelyLegalizeResults(SDValue Op,
79 MutableArrayRef<SDValue> Results);
81 /// Wrapper to interface LowerOperation with a vector of Results.
82 /// Returns false if the target wants to use default expansion. Otherwise
83 /// returns true. If return is true and the Results are empty, then the
84 /// target wants to keep the input node as is.
85 bool LowerOperationWrapper(SDNode *N, SmallVectorImpl<SDValue> &Results);
87 /// Implements unrolling a VSETCC.
88 SDValue UnrollVSETCC(SDNode *Node);
90 /// Implement expand-based legalization of vector operations.
92 /// This is just a high-level routine to dispatch to specific code paths for
93 /// operations to legalize them.
94 void Expand(SDNode *Node, SmallVectorImpl<SDValue> &Results);
96 /// Implements expansion for FP_TO_UINT; falls back to UnrollVectorOp if
97 /// FP_TO_SINT isn't legal.
98 void ExpandFP_TO_UINT(SDNode *Node, SmallVectorImpl<SDValue> &Results);
100 /// Implements expansion for UINT_TO_FLOAT; falls back to UnrollVectorOp if
101 /// SINT_TO_FLOAT and SHR on vectors isn't legal.
102 void ExpandUINT_TO_FLOAT(SDNode *Node, SmallVectorImpl<SDValue> &Results);
104 /// Implement expansion for SIGN_EXTEND_INREG using SRL and SRA.
105 SDValue ExpandSEXTINREG(SDNode *Node);
107 /// Implement expansion for ANY_EXTEND_VECTOR_INREG.
109 /// Shuffles the low lanes of the operand into place and bitcasts to the proper
110 /// type. The contents of the bits in the extended part of each element are
112 SDValue ExpandANY_EXTEND_VECTOR_INREG(SDNode *Node);
114 /// Implement expansion for SIGN_EXTEND_VECTOR_INREG.
116 /// Shuffles the low lanes of the operand into place, bitcasts to the proper
117 /// type, then shifts left and arithmetic shifts right to introduce a sign
119 SDValue ExpandSIGN_EXTEND_VECTOR_INREG(SDNode *Node);
121 /// Implement expansion for ZERO_EXTEND_VECTOR_INREG.
123 /// Shuffles the low lanes of the operand into place and blends zeros into
124 /// the remaining lanes, finally bitcasting to the proper type.
125 SDValue ExpandZERO_EXTEND_VECTOR_INREG(SDNode *Node);
127 /// Expand bswap of vectors into a shuffle if legal.
128 SDValue ExpandBSWAP(SDNode *Node);
130 /// Implement vselect in terms of XOR, AND, OR when blend is not
131 /// supported by the target.
132 SDValue ExpandVSELECT(SDNode *Node);
133 SDValue ExpandVP_SELECT(SDNode *Node);
134 SDValue ExpandVP_MERGE(SDNode *Node);
135 SDValue ExpandSELECT(SDNode *Node);
136 std::pair<SDValue, SDValue> ExpandLoad(SDNode *N);
137 SDValue ExpandStore(SDNode *N);
138 SDValue ExpandFNEG(SDNode *Node);
139 void ExpandFSUB(SDNode *Node, SmallVectorImpl<SDValue> &Results);
140 void ExpandSETCC(SDNode *Node, SmallVectorImpl<SDValue> &Results);
141 void ExpandBITREVERSE(SDNode *Node, SmallVectorImpl<SDValue> &Results);
142 void ExpandUADDSUBO(SDNode *Node, SmallVectorImpl<SDValue> &Results);
143 void ExpandSADDSUBO(SDNode *Node, SmallVectorImpl<SDValue> &Results);
144 void ExpandMULO(SDNode *Node, SmallVectorImpl<SDValue> &Results);
145 void ExpandFixedPointDiv(SDNode *Node, SmallVectorImpl<SDValue> &Results);
146 void ExpandStrictFPOp(SDNode *Node, SmallVectorImpl<SDValue> &Results);
147 void ExpandREM(SDNode *Node, SmallVectorImpl<SDValue> &Results);
149 void UnrollStrictFPOp(SDNode *Node, SmallVectorImpl<SDValue> &Results);
151 /// Implements vector promotion.
153 /// This is essentially just bitcasting the operands to a different type and
154 /// bitcasting the result back to the original type.
155 void Promote(SDNode *Node, SmallVectorImpl<SDValue> &Results);
157 /// Implements [SU]INT_TO_FP vector promotion.
159 /// This is a [zs]ext of the input operand to a larger integer type.
160 void PromoteINT_TO_FP(SDNode *Node, SmallVectorImpl<SDValue> &Results);
162 /// Implements FP_TO_[SU]INT vector promotion of the result type.
164 /// It is promoted to a larger integer type. The result is then
165 /// truncated back to the original type.
166 void PromoteFP_TO_INT(SDNode *Node, SmallVectorImpl<SDValue> &Results);
169 VectorLegalizer(SelectionDAG& dag) :
170 DAG(dag), TLI(dag.getTargetLoweringInfo()) {}
172 /// Begin legalizer the vector operations in the DAG.
176 } // end anonymous namespace
178 bool VectorLegalizer::Run() {
179 // Before we start legalizing vector nodes, check if there are any vectors.
180 bool HasVectors = false;
181 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
182 E = std::prev(DAG.allnodes_end()); I != std::next(E); ++I) {
183 // Check if the values of the nodes contain vectors. We don't need to check
184 // the operands because we are going to check their values at some point.
185 HasVectors = llvm::any_of(I->values(), [](EVT T) { return T.isVector(); });
187 // If we found a vector node we can start the legalization.
192 // If this basic block has no vectors then no need to legalize vectors.
196 // The legalize process is inherently a bottom-up recursive process (users
197 // legalize their uses before themselves). Given infinite stack space, we
198 // could just start legalizing on the root and traverse the whole graph. In
199 // practice however, this causes us to run out of stack space on large basic
200 // blocks. To avoid this problem, compute an ordering of the nodes where each
201 // node is only legalized after all of its operands are legalized.
202 DAG.AssignTopologicalOrder();
203 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
204 E = std::prev(DAG.allnodes_end()); I != std::next(E); ++I)
205 LegalizeOp(SDValue(&*I, 0));
207 // Finally, it's possible the root changed. Get the new root.
208 SDValue OldRoot = DAG.getRoot();
209 assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
210 DAG.setRoot(LegalizedNodes[OldRoot]);
212 LegalizedNodes.clear();
214 // Remove dead nodes now.
215 DAG.RemoveDeadNodes();
220 SDValue VectorLegalizer::TranslateLegalizeResults(SDValue Op, SDNode *Result) {
221 assert(Op->getNumValues() == Result->getNumValues() &&
222 "Unexpected number of results");
223 // Generic legalization: just pass the operand through.
224 for (unsigned i = 0, e = Op->getNumValues(); i != e; ++i)
225 AddLegalizedOperand(Op.getValue(i), SDValue(Result, i));
226 return SDValue(Result, Op.getResNo());
230 VectorLegalizer::RecursivelyLegalizeResults(SDValue Op,
231 MutableArrayRef<SDValue> Results) {
232 assert(Results.size() == Op->getNumValues() &&
233 "Unexpected number of results");
234 // Make sure that the generated code is itself legal.
235 for (unsigned i = 0, e = Results.size(); i != e; ++i) {
236 Results[i] = LegalizeOp(Results[i]);
237 AddLegalizedOperand(Op.getValue(i), Results[i]);
240 return Results[Op.getResNo()];
243 SDValue VectorLegalizer::LegalizeOp(SDValue Op) {
244 // Note that LegalizeOp may be reentered even from single-use nodes, which
245 // means that we always must cache transformed nodes.
246 DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
247 if (I != LegalizedNodes.end()) return I->second;
249 // Legalize the operands
250 SmallVector<SDValue, 8> Ops;
251 for (const SDValue &Oper : Op->op_values())
252 Ops.push_back(LegalizeOp(Oper));
254 SDNode *Node = DAG.UpdateNodeOperands(Op.getNode(), Ops);
256 bool HasVectorValueOrOp =
257 llvm::any_of(Node->values(), [](EVT T) { return T.isVector(); }) ||
258 llvm::any_of(Node->op_values(),
259 [](SDValue O) { return O.getValueType().isVector(); });
260 if (!HasVectorValueOrOp)
261 return TranslateLegalizeResults(Op, Node);
263 TargetLowering::LegalizeAction Action = TargetLowering::Legal;
265 switch (Op.getOpcode()) {
267 return TranslateLegalizeResults(Op, Node);
269 LoadSDNode *LD = cast<LoadSDNode>(Node);
270 ISD::LoadExtType ExtType = LD->getExtensionType();
271 EVT LoadedVT = LD->getMemoryVT();
272 if (LoadedVT.isVector() && ExtType != ISD::NON_EXTLOAD)
273 Action = TLI.getLoadExtAction(ExtType, LD->getValueType(0), LoadedVT);
277 StoreSDNode *ST = cast<StoreSDNode>(Node);
278 EVT StVT = ST->getMemoryVT();
279 MVT ValVT = ST->getValue().getSimpleValueType();
280 if (StVT.isVector() && ST->isTruncatingStore())
281 Action = TLI.getTruncStoreAction(ValVT, StVT);
284 case ISD::MERGE_VALUES:
285 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
286 // This operation lies about being legal: when it claims to be legal,
287 // it should actually be expanded.
288 if (Action == TargetLowering::Legal)
289 Action = TargetLowering::Expand;
291 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
292 case ISD::STRICT_##DAGN:
293 #include "llvm/IR/ConstrainedOps.def"
294 ValVT = Node->getValueType(0);
295 if (Op.getOpcode() == ISD::STRICT_SINT_TO_FP ||
296 Op.getOpcode() == ISD::STRICT_UINT_TO_FP)
297 ValVT = Node->getOperand(1).getValueType();
298 Action = TLI.getOperationAction(Node->getOpcode(), ValVT);
299 // If we're asked to expand a strict vector floating-point operation,
300 // by default we're going to simply unroll it. That is usually the
301 // best approach, except in the case where the resulting strict (scalar)
302 // operations would themselves use the fallback mutation to non-strict.
303 // In that specific case, just do the fallback on the vector op.
304 if (Action == TargetLowering::Expand && !TLI.isStrictFPEnabled() &&
305 TLI.getStrictFPOperationAction(Node->getOpcode(), ValVT) ==
306 TargetLowering::Legal) {
307 EVT EltVT = ValVT.getVectorElementType();
308 if (TLI.getOperationAction(Node->getOpcode(), EltVT)
309 == TargetLowering::Expand &&
310 TLI.getStrictFPOperationAction(Node->getOpcode(), EltVT)
311 == TargetLowering::Legal)
312 Action = TargetLowering::Legal;
343 case ISD::BITREVERSE:
346 case ISD::CTLZ_ZERO_UNDEF:
347 case ISD::CTTZ_ZERO_UNDEF:
352 case ISD::ZERO_EXTEND:
353 case ISD::ANY_EXTEND:
355 case ISD::SIGN_EXTEND:
356 case ISD::FP_TO_SINT:
357 case ISD::FP_TO_UINT:
362 case ISD::FMINNUM_IEEE:
363 case ISD::FMAXNUM_IEEE:
380 case ISD::FNEARBYINT:
382 case ISD::FROUNDEVEN:
387 case ISD::SIGN_EXTEND_INREG:
388 case ISD::ANY_EXTEND_VECTOR_INREG:
389 case ISD::SIGN_EXTEND_VECTOR_INREG:
390 case ISD::ZERO_EXTEND_VECTOR_INREG:
403 case ISD::FCANONICALIZE:
410 case ISD::FP_TO_SINT_SAT:
411 case ISD::FP_TO_UINT_SAT:
413 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
416 case ISD::SMULFIXSAT:
418 case ISD::UMULFIXSAT:
420 case ISD::SDIVFIXSAT:
422 case ISD::UDIVFIXSAT: {
423 unsigned Scale = Node->getConstantOperandVal(2);
424 Action = TLI.getFixedPointOperationAction(Node->getOpcode(),
425 Node->getValueType(0), Scale);
428 case ISD::SINT_TO_FP:
429 case ISD::UINT_TO_FP:
430 case ISD::VECREDUCE_ADD:
431 case ISD::VECREDUCE_MUL:
432 case ISD::VECREDUCE_AND:
433 case ISD::VECREDUCE_OR:
434 case ISD::VECREDUCE_XOR:
435 case ISD::VECREDUCE_SMAX:
436 case ISD::VECREDUCE_SMIN:
437 case ISD::VECREDUCE_UMAX:
438 case ISD::VECREDUCE_UMIN:
439 case ISD::VECREDUCE_FADD:
440 case ISD::VECREDUCE_FMUL:
441 case ISD::VECREDUCE_FMAX:
442 case ISD::VECREDUCE_FMIN:
443 Action = TLI.getOperationAction(Node->getOpcode(),
444 Node->getOperand(0).getValueType());
446 case ISD::VECREDUCE_SEQ_FADD:
447 case ISD::VECREDUCE_SEQ_FMUL:
448 Action = TLI.getOperationAction(Node->getOpcode(),
449 Node->getOperand(1).getValueType());
452 MVT OpVT = Node->getOperand(0).getSimpleValueType();
453 ISD::CondCode CCCode = cast<CondCodeSDNode>(Node->getOperand(2))->get();
454 Action = TLI.getCondCodeAction(CCCode, OpVT);
455 if (Action == TargetLowering::Legal)
456 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
460 #define BEGIN_REGISTER_VP_SDNODE(VPID, LEGALPOS, ...) \
462 EVT LegalizeVT = LEGALPOS < 0 ? Node->getValueType(-(1 + LEGALPOS)) \
463 : Node->getOperand(LEGALPOS).getValueType(); \
464 if (ISD::VPID == ISD::VP_SETCC) { \
465 ISD::CondCode CCCode = cast<CondCodeSDNode>(Node->getOperand(2))->get(); \
466 Action = TLI.getCondCodeAction(CCCode, LegalizeVT.getSimpleVT()); \
467 if (Action != TargetLowering::Legal) \
470 Action = TLI.getOperationAction(Node->getOpcode(), LegalizeVT); \
472 #include "llvm/IR/VPIntrinsics.def"
475 LLVM_DEBUG(dbgs() << "\nLegalizing vector op: "; Node->dump(&DAG));
477 SmallVector<SDValue, 8> ResultVals;
479 default: llvm_unreachable("This action is not supported yet!");
480 case TargetLowering::Promote:
481 assert((Op.getOpcode() != ISD::LOAD && Op.getOpcode() != ISD::STORE) &&
482 "This action is not supported yet!");
483 LLVM_DEBUG(dbgs() << "Promoting\n");
484 Promote(Node, ResultVals);
485 assert(!ResultVals.empty() && "No results for promotion?");
487 case TargetLowering::Legal:
488 LLVM_DEBUG(dbgs() << "Legal node: nothing to do\n");
490 case TargetLowering::Custom:
491 LLVM_DEBUG(dbgs() << "Trying custom legalization\n");
492 if (LowerOperationWrapper(Node, ResultVals))
494 LLVM_DEBUG(dbgs() << "Could not custom legalize node\n");
496 case TargetLowering::Expand:
497 LLVM_DEBUG(dbgs() << "Expanding\n");
498 Expand(Node, ResultVals);
502 if (ResultVals.empty())
503 return TranslateLegalizeResults(Op, Node);
506 return RecursivelyLegalizeResults(Op, ResultVals);
509 // FIXME: This is very similar to TargetLowering::LowerOperationWrapper. Can we
510 // merge them somehow?
511 bool VectorLegalizer::LowerOperationWrapper(SDNode *Node,
512 SmallVectorImpl<SDValue> &Results) {
513 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
518 if (Res == SDValue(Node, 0))
521 // If the original node has one result, take the return value from
522 // LowerOperation as is. It might not be result number 0.
523 if (Node->getNumValues() == 1) {
524 Results.push_back(Res);
528 // If the original node has multiple results, then the return node should
529 // have the same number of results.
530 assert((Node->getNumValues() == Res->getNumValues()) &&
531 "Lowering returned the wrong number of results!");
533 // Places new result values base on N result number.
534 for (unsigned I = 0, E = Node->getNumValues(); I != E; ++I)
535 Results.push_back(Res.getValue(I));
540 void VectorLegalizer::Promote(SDNode *Node, SmallVectorImpl<SDValue> &Results) {
541 // For a few operations there is a specific concept for promotion based on
542 // the operand's type.
543 switch (Node->getOpcode()) {
544 case ISD::SINT_TO_FP:
545 case ISD::UINT_TO_FP:
546 case ISD::STRICT_SINT_TO_FP:
547 case ISD::STRICT_UINT_TO_FP:
548 // "Promote" the operation by extending the operand.
549 PromoteINT_TO_FP(Node, Results);
551 case ISD::FP_TO_UINT:
552 case ISD::FP_TO_SINT:
553 case ISD::STRICT_FP_TO_UINT:
554 case ISD::STRICT_FP_TO_SINT:
555 // Promote the operation by extending the operand.
556 PromoteFP_TO_INT(Node, Results);
560 // These operations are used to do promotion so they can't be promoted
562 llvm_unreachable("Don't know how to promote this operation!");
565 // There are currently two cases of vector promotion:
566 // 1) Bitcasting a vector of integers to a different type to a vector of the
567 // same overall length. For example, x86 promotes ISD::AND v2i32 to v1i64.
568 // 2) Extending a vector of floats to a vector of the same number of larger
569 // floats. For example, AArch64 promotes ISD::FADD on v4f16 to v4f32.
570 assert(Node->getNumValues() == 1 &&
571 "Can't promote a vector with multiple results!");
572 MVT VT = Node->getSimpleValueType(0);
573 MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
575 SmallVector<SDValue, 4> Operands(Node->getNumOperands());
577 for (unsigned j = 0; j != Node->getNumOperands(); ++j) {
578 if (Node->getOperand(j).getValueType().isVector())
579 if (Node->getOperand(j)
581 .getVectorElementType()
582 .isFloatingPoint() &&
583 NVT.isVector() && NVT.getVectorElementType().isFloatingPoint())
584 Operands[j] = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(j));
586 Operands[j] = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(j));
588 Operands[j] = Node->getOperand(j);
592 DAG.getNode(Node->getOpcode(), dl, NVT, Operands, Node->getFlags());
594 if ((VT.isFloatingPoint() && NVT.isFloatingPoint()) ||
595 (VT.isVector() && VT.getVectorElementType().isFloatingPoint() &&
596 NVT.isVector() && NVT.getVectorElementType().isFloatingPoint()))
597 Res = DAG.getNode(ISD::FP_ROUND, dl, VT, Res,
598 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
600 Res = DAG.getNode(ISD::BITCAST, dl, VT, Res);
602 Results.push_back(Res);
605 void VectorLegalizer::PromoteINT_TO_FP(SDNode *Node,
606 SmallVectorImpl<SDValue> &Results) {
607 // INT_TO_FP operations may require the input operand be promoted even
608 // when the type is otherwise legal.
609 bool IsStrict = Node->isStrictFPOpcode();
610 MVT VT = Node->getOperand(IsStrict ? 1 : 0).getSimpleValueType();
611 MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
612 assert(NVT.getVectorNumElements() == VT.getVectorNumElements() &&
613 "Vectors have different number of elements!");
616 SmallVector<SDValue, 4> Operands(Node->getNumOperands());
618 unsigned Opc = (Node->getOpcode() == ISD::UINT_TO_FP ||
619 Node->getOpcode() == ISD::STRICT_UINT_TO_FP)
622 for (unsigned j = 0; j != Node->getNumOperands(); ++j) {
623 if (Node->getOperand(j).getValueType().isVector())
624 Operands[j] = DAG.getNode(Opc, dl, NVT, Node->getOperand(j));
626 Operands[j] = Node->getOperand(j);
630 SDValue Res = DAG.getNode(Node->getOpcode(), dl,
631 {Node->getValueType(0), MVT::Other}, Operands);
632 Results.push_back(Res);
633 Results.push_back(Res.getValue(1));
638 DAG.getNode(Node->getOpcode(), dl, Node->getValueType(0), Operands);
639 Results.push_back(Res);
642 // For FP_TO_INT we promote the result type to a vector type with wider
643 // elements and then truncate the result. This is different from the default
644 // PromoteVector which uses bitcast to promote thus assumning that the
645 // promoted vector type has the same overall size.
646 void VectorLegalizer::PromoteFP_TO_INT(SDNode *Node,
647 SmallVectorImpl<SDValue> &Results) {
648 MVT VT = Node->getSimpleValueType(0);
649 MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
650 bool IsStrict = Node->isStrictFPOpcode();
651 assert(NVT.getVectorNumElements() == VT.getVectorNumElements() &&
652 "Vectors have different number of elements!");
654 unsigned NewOpc = Node->getOpcode();
655 // Change FP_TO_UINT to FP_TO_SINT if possible.
656 // TODO: Should we only do this if FP_TO_UINT itself isn't legal?
657 if (NewOpc == ISD::FP_TO_UINT &&
658 TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NVT))
659 NewOpc = ISD::FP_TO_SINT;
661 if (NewOpc == ISD::STRICT_FP_TO_UINT &&
662 TLI.isOperationLegalOrCustom(ISD::STRICT_FP_TO_SINT, NVT))
663 NewOpc = ISD::STRICT_FP_TO_SINT;
666 SDValue Promoted, Chain;
668 Promoted = DAG.getNode(NewOpc, dl, {NVT, MVT::Other},
669 {Node->getOperand(0), Node->getOperand(1)});
670 Chain = Promoted.getValue(1);
672 Promoted = DAG.getNode(NewOpc, dl, NVT, Node->getOperand(0));
674 // Assert that the converted value fits in the original type. If it doesn't
675 // (eg: because the value being converted is too big), then the result of the
676 // original operation was undefined anyway, so the assert is still correct.
677 if (Node->getOpcode() == ISD::FP_TO_UINT ||
678 Node->getOpcode() == ISD::STRICT_FP_TO_UINT)
679 NewOpc = ISD::AssertZext;
681 NewOpc = ISD::AssertSext;
683 Promoted = DAG.getNode(NewOpc, dl, NVT, Promoted,
684 DAG.getValueType(VT.getScalarType()));
685 Promoted = DAG.getNode(ISD::TRUNCATE, dl, VT, Promoted);
686 Results.push_back(Promoted);
688 Results.push_back(Chain);
691 std::pair<SDValue, SDValue> VectorLegalizer::ExpandLoad(SDNode *N) {
692 LoadSDNode *LD = cast<LoadSDNode>(N);
693 return TLI.scalarizeVectorLoad(LD, DAG);
696 SDValue VectorLegalizer::ExpandStore(SDNode *N) {
697 StoreSDNode *ST = cast<StoreSDNode>(N);
698 SDValue TF = TLI.scalarizeVectorStore(ST, DAG);
702 void VectorLegalizer::Expand(SDNode *Node, SmallVectorImpl<SDValue> &Results) {
703 switch (Node->getOpcode()) {
705 std::pair<SDValue, SDValue> Tmp = ExpandLoad(Node);
706 Results.push_back(Tmp.first);
707 Results.push_back(Tmp.second);
711 Results.push_back(ExpandStore(Node));
713 case ISD::MERGE_VALUES:
714 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
715 Results.push_back(Node->getOperand(i));
717 case ISD::SIGN_EXTEND_INREG:
718 Results.push_back(ExpandSEXTINREG(Node));
720 case ISD::ANY_EXTEND_VECTOR_INREG:
721 Results.push_back(ExpandANY_EXTEND_VECTOR_INREG(Node));
723 case ISD::SIGN_EXTEND_VECTOR_INREG:
724 Results.push_back(ExpandSIGN_EXTEND_VECTOR_INREG(Node));
726 case ISD::ZERO_EXTEND_VECTOR_INREG:
727 Results.push_back(ExpandZERO_EXTEND_VECTOR_INREG(Node));
730 Results.push_back(ExpandBSWAP(Node));
733 Results.push_back(ExpandVSELECT(Node));
736 Results.push_back(ExpandVP_SELECT(Node));
739 Results.push_back(ExpandSELECT(Node));
741 case ISD::SELECT_CC: {
742 if (Node->getValueType(0).isScalableVector()) {
743 EVT CondVT = TLI.getSetCCResultType(
744 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
746 DAG.getNode(ISD::SETCC, SDLoc(Node), CondVT, Node->getOperand(0),
747 Node->getOperand(1), Node->getOperand(4));
748 Results.push_back(DAG.getSelect(SDLoc(Node), Node->getValueType(0), SetCC,
750 Node->getOperand(3)));
755 case ISD::FP_TO_UINT:
756 ExpandFP_TO_UINT(Node, Results);
758 case ISD::UINT_TO_FP:
759 ExpandUINT_TO_FLOAT(Node, Results);
762 Results.push_back(ExpandFNEG(Node));
765 ExpandFSUB(Node, Results);
769 ExpandSETCC(Node, Results);
772 if (SDValue Expanded = TLI.expandABS(Node, DAG)) {
773 Results.push_back(Expanded);
777 case ISD::BITREVERSE:
778 ExpandBITREVERSE(Node, Results);
781 if (SDValue Expanded = TLI.expandCTPOP(Node, DAG)) {
782 Results.push_back(Expanded);
787 case ISD::CTLZ_ZERO_UNDEF:
788 if (SDValue Expanded = TLI.expandCTLZ(Node, DAG)) {
789 Results.push_back(Expanded);
794 case ISD::CTTZ_ZERO_UNDEF:
795 if (SDValue Expanded = TLI.expandCTTZ(Node, DAG)) {
796 Results.push_back(Expanded);
802 if (SDValue Expanded = TLI.expandFunnelShift(Node, DAG)) {
803 Results.push_back(Expanded);
809 if (SDValue Expanded = TLI.expandROT(Node, false /*AllowVectorOps*/, DAG)) {
810 Results.push_back(Expanded);
816 if (SDValue Expanded = TLI.expandFMINNUM_FMAXNUM(Node, DAG)) {
817 Results.push_back(Expanded);
825 if (SDValue Expanded = TLI.expandIntMINMAX(Node, DAG)) {
826 Results.push_back(Expanded);
832 ExpandUADDSUBO(Node, Results);
836 ExpandSADDSUBO(Node, Results);
840 ExpandMULO(Node, Results);
846 if (SDValue Expanded = TLI.expandAddSubSat(Node, DAG)) {
847 Results.push_back(Expanded);
851 case ISD::FP_TO_SINT_SAT:
852 case ISD::FP_TO_UINT_SAT:
853 // Expand the fpsosisat if it is scalable to prevent it from unrolling below.
854 if (Node->getValueType(0).isScalableVector()) {
855 if (SDValue Expanded = TLI.expandFP_TO_INT_SAT(Node, DAG)) {
856 Results.push_back(Expanded);
863 if (SDValue Expanded = TLI.expandFixedPointMul(Node, DAG)) {
864 Results.push_back(Expanded);
868 case ISD::SMULFIXSAT:
869 case ISD::UMULFIXSAT:
870 // FIXME: We do not expand SMULFIXSAT/UMULFIXSAT here yet, not sure exactly
871 // why. Maybe it results in worse codegen compared to the unroll for some
872 // targets? This should probably be investigated. And if we still prefer to
873 // unroll an explanation could be helpful.
877 ExpandFixedPointDiv(Node, Results);
879 case ISD::SDIVFIXSAT:
880 case ISD::UDIVFIXSAT:
882 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
883 case ISD::STRICT_##DAGN:
884 #include "llvm/IR/ConstrainedOps.def"
885 ExpandStrictFPOp(Node, Results);
887 case ISD::VECREDUCE_ADD:
888 case ISD::VECREDUCE_MUL:
889 case ISD::VECREDUCE_AND:
890 case ISD::VECREDUCE_OR:
891 case ISD::VECREDUCE_XOR:
892 case ISD::VECREDUCE_SMAX:
893 case ISD::VECREDUCE_SMIN:
894 case ISD::VECREDUCE_UMAX:
895 case ISD::VECREDUCE_UMIN:
896 case ISD::VECREDUCE_FADD:
897 case ISD::VECREDUCE_FMUL:
898 case ISD::VECREDUCE_FMAX:
899 case ISD::VECREDUCE_FMIN:
900 Results.push_back(TLI.expandVecReduce(Node, DAG));
902 case ISD::VECREDUCE_SEQ_FADD:
903 case ISD::VECREDUCE_SEQ_FMUL:
904 Results.push_back(TLI.expandVecReduceSeq(Node, DAG));
908 ExpandREM(Node, Results);
911 Results.push_back(ExpandVP_MERGE(Node));
915 Results.push_back(DAG.UnrollVectorOp(Node));
918 SDValue VectorLegalizer::ExpandSELECT(SDNode *Node) {
919 // Lower a select instruction where the condition is a scalar and the
920 // operands are vectors. Lower this select to VSELECT and implement it
921 // using XOR AND OR. The selector bit is broadcasted.
922 EVT VT = Node->getValueType(0);
925 SDValue Mask = Node->getOperand(0);
926 SDValue Op1 = Node->getOperand(1);
927 SDValue Op2 = Node->getOperand(2);
929 assert(VT.isVector() && !Mask.getValueType().isVector()
930 && Op1.getValueType() == Op2.getValueType() && "Invalid type");
932 // If we can't even use the basic vector operations of
933 // AND,OR,XOR, we will have to scalarize the op.
934 // Notice that the operation may be 'promoted' which means that it is
935 // 'bitcasted' to another type which is handled.
936 // Also, we need to be able to construct a splat vector using either
937 // BUILD_VECTOR or SPLAT_VECTOR.
938 // FIXME: Should we also permit fixed-length SPLAT_VECTOR as a fallback to
940 if (TLI.getOperationAction(ISD::AND, VT) == TargetLowering::Expand ||
941 TLI.getOperationAction(ISD::XOR, VT) == TargetLowering::Expand ||
942 TLI.getOperationAction(ISD::OR, VT) == TargetLowering::Expand ||
943 TLI.getOperationAction(VT.isFixedLengthVector() ? ISD::BUILD_VECTOR
945 VT) == TargetLowering::Expand)
946 return DAG.UnrollVectorOp(Node);
948 // Generate a mask operand.
949 EVT MaskTy = VT.changeVectorElementTypeToInteger();
951 // What is the size of each element in the vector mask.
952 EVT BitTy = MaskTy.getScalarType();
954 Mask = DAG.getSelect(DL, BitTy, Mask, DAG.getAllOnesConstant(DL, BitTy),
955 DAG.getConstant(0, DL, BitTy));
957 // Broadcast the mask so that the entire vector is all one or all zero.
958 if (VT.isFixedLengthVector())
959 Mask = DAG.getSplatBuildVector(MaskTy, DL, Mask);
961 Mask = DAG.getSplatVector(MaskTy, DL, Mask);
963 // Bitcast the operands to be the same type as the mask.
964 // This is needed when we select between FP types because
965 // the mask is a vector of integers.
966 Op1 = DAG.getNode(ISD::BITCAST, DL, MaskTy, Op1);
967 Op2 = DAG.getNode(ISD::BITCAST, DL, MaskTy, Op2);
969 SDValue NotMask = DAG.getNOT(DL, Mask, MaskTy);
971 Op1 = DAG.getNode(ISD::AND, DL, MaskTy, Op1, Mask);
972 Op2 = DAG.getNode(ISD::AND, DL, MaskTy, Op2, NotMask);
973 SDValue Val = DAG.getNode(ISD::OR, DL, MaskTy, Op1, Op2);
974 return DAG.getNode(ISD::BITCAST, DL, Node->getValueType(0), Val);
977 SDValue VectorLegalizer::ExpandSEXTINREG(SDNode *Node) {
978 EVT VT = Node->getValueType(0);
980 // Make sure that the SRA and SHL instructions are available.
981 if (TLI.getOperationAction(ISD::SRA, VT) == TargetLowering::Expand ||
982 TLI.getOperationAction(ISD::SHL, VT) == TargetLowering::Expand)
983 return DAG.UnrollVectorOp(Node);
986 EVT OrigTy = cast<VTSDNode>(Node->getOperand(1))->getVT();
988 unsigned BW = VT.getScalarSizeInBits();
989 unsigned OrigBW = OrigTy.getScalarSizeInBits();
990 SDValue ShiftSz = DAG.getConstant(BW - OrigBW, DL, VT);
992 SDValue Op = DAG.getNode(ISD::SHL, DL, VT, Node->getOperand(0), ShiftSz);
993 return DAG.getNode(ISD::SRA, DL, VT, Op, ShiftSz);
996 // Generically expand a vector anyext in register to a shuffle of the relevant
997 // lanes into the appropriate locations, with other lanes left undef.
998 SDValue VectorLegalizer::ExpandANY_EXTEND_VECTOR_INREG(SDNode *Node) {
1000 EVT VT = Node->getValueType(0);
1001 int NumElements = VT.getVectorNumElements();
1002 SDValue Src = Node->getOperand(0);
1003 EVT SrcVT = Src.getValueType();
1004 int NumSrcElements = SrcVT.getVectorNumElements();
1006 // *_EXTEND_VECTOR_INREG SrcVT can be smaller than VT - so insert the vector
1007 // into a larger vector type.
1008 if (SrcVT.bitsLE(VT)) {
1009 assert((VT.getSizeInBits() % SrcVT.getScalarSizeInBits()) == 0 &&
1010 "ANY_EXTEND_VECTOR_INREG vector size mismatch");
1011 NumSrcElements = VT.getSizeInBits() / SrcVT.getScalarSizeInBits();
1012 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getScalarType(),
1014 Src = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SrcVT, DAG.getUNDEF(SrcVT),
1015 Src, DAG.getVectorIdxConstant(0, DL));
1018 // Build a base mask of undef shuffles.
1019 SmallVector<int, 16> ShuffleMask;
1020 ShuffleMask.resize(NumSrcElements, -1);
1022 // Place the extended lanes into the correct locations.
1023 int ExtLaneScale = NumSrcElements / NumElements;
1024 int EndianOffset = DAG.getDataLayout().isBigEndian() ? ExtLaneScale - 1 : 0;
1025 for (int i = 0; i < NumElements; ++i)
1026 ShuffleMask[i * ExtLaneScale + EndianOffset] = i;
1029 ISD::BITCAST, DL, VT,
1030 DAG.getVectorShuffle(SrcVT, DL, Src, DAG.getUNDEF(SrcVT), ShuffleMask));
1033 SDValue VectorLegalizer::ExpandSIGN_EXTEND_VECTOR_INREG(SDNode *Node) {
1035 EVT VT = Node->getValueType(0);
1036 SDValue Src = Node->getOperand(0);
1037 EVT SrcVT = Src.getValueType();
1039 // First build an any-extend node which can be legalized above when we
1040 // recurse through it.
1041 SDValue Op = DAG.getNode(ISD::ANY_EXTEND_VECTOR_INREG, DL, VT, Src);
1043 // Now we need sign extend. Do this by shifting the elements. Even if these
1044 // aren't legal operations, they have a better chance of being legalized
1045 // without full scalarization than the sign extension does.
1046 unsigned EltWidth = VT.getScalarSizeInBits();
1047 unsigned SrcEltWidth = SrcVT.getScalarSizeInBits();
1048 SDValue ShiftAmount = DAG.getConstant(EltWidth - SrcEltWidth, DL, VT);
1049 return DAG.getNode(ISD::SRA, DL, VT,
1050 DAG.getNode(ISD::SHL, DL, VT, Op, ShiftAmount),
1054 // Generically expand a vector zext in register to a shuffle of the relevant
1055 // lanes into the appropriate locations, a blend of zero into the high bits,
1056 // and a bitcast to the wider element type.
1057 SDValue VectorLegalizer::ExpandZERO_EXTEND_VECTOR_INREG(SDNode *Node) {
1059 EVT VT = Node->getValueType(0);
1060 int NumElements = VT.getVectorNumElements();
1061 SDValue Src = Node->getOperand(0);
1062 EVT SrcVT = Src.getValueType();
1063 int NumSrcElements = SrcVT.getVectorNumElements();
1065 // *_EXTEND_VECTOR_INREG SrcVT can be smaller than VT - so insert the vector
1066 // into a larger vector type.
1067 if (SrcVT.bitsLE(VT)) {
1068 assert((VT.getSizeInBits() % SrcVT.getScalarSizeInBits()) == 0 &&
1069 "ZERO_EXTEND_VECTOR_INREG vector size mismatch");
1070 NumSrcElements = VT.getSizeInBits() / SrcVT.getScalarSizeInBits();
1071 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getScalarType(),
1073 Src = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SrcVT, DAG.getUNDEF(SrcVT),
1074 Src, DAG.getVectorIdxConstant(0, DL));
1077 // Build up a zero vector to blend into this one.
1078 SDValue Zero = DAG.getConstant(0, DL, SrcVT);
1080 // Shuffle the incoming lanes into the correct position, and pull all other
1081 // lanes from the zero vector.
1082 auto ShuffleMask = llvm::to_vector<16>(llvm::seq<int>(0, NumSrcElements));
1084 int ExtLaneScale = NumSrcElements / NumElements;
1085 int EndianOffset = DAG.getDataLayout().isBigEndian() ? ExtLaneScale - 1 : 0;
1086 for (int i = 0; i < NumElements; ++i)
1087 ShuffleMask[i * ExtLaneScale + EndianOffset] = NumSrcElements + i;
1089 return DAG.getNode(ISD::BITCAST, DL, VT,
1090 DAG.getVectorShuffle(SrcVT, DL, Zero, Src, ShuffleMask));
1093 static void createBSWAPShuffleMask(EVT VT, SmallVectorImpl<int> &ShuffleMask) {
1094 int ScalarSizeInBytes = VT.getScalarSizeInBits() / 8;
1095 for (int I = 0, E = VT.getVectorNumElements(); I != E; ++I)
1096 for (int J = ScalarSizeInBytes - 1; J >= 0; --J)
1097 ShuffleMask.push_back((I * ScalarSizeInBytes) + J);
1100 SDValue VectorLegalizer::ExpandBSWAP(SDNode *Node) {
1101 EVT VT = Node->getValueType(0);
1103 // Scalable vectors can't use shuffle expansion.
1104 if (VT.isScalableVector())
1105 return TLI.expandBSWAP(Node, DAG);
1107 // Generate a byte wise shuffle mask for the BSWAP.
1108 SmallVector<int, 16> ShuffleMask;
1109 createBSWAPShuffleMask(VT, ShuffleMask);
1110 EVT ByteVT = EVT::getVectorVT(*DAG.getContext(), MVT::i8, ShuffleMask.size());
1112 // Only emit a shuffle if the mask is legal.
1113 if (TLI.isShuffleMaskLegal(ShuffleMask, ByteVT)) {
1115 SDValue Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Node->getOperand(0));
1116 Op = DAG.getVectorShuffle(ByteVT, DL, Op, DAG.getUNDEF(ByteVT), ShuffleMask);
1117 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
1120 // If we have the appropriate vector bit operations, it is better to use them
1121 // than unrolling and expanding each component.
1122 if (TLI.isOperationLegalOrCustom(ISD::SHL, VT) &&
1123 TLI.isOperationLegalOrCustom(ISD::SRL, VT) &&
1124 TLI.isOperationLegalOrCustomOrPromote(ISD::AND, VT) &&
1125 TLI.isOperationLegalOrCustomOrPromote(ISD::OR, VT))
1126 return TLI.expandBSWAP(Node, DAG);
1128 // Otherwise unroll.
1129 return DAG.UnrollVectorOp(Node);
1132 void VectorLegalizer::ExpandBITREVERSE(SDNode *Node,
1133 SmallVectorImpl<SDValue> &Results) {
1134 EVT VT = Node->getValueType(0);
1136 // We can't unroll or use shuffles for scalable vectors.
1137 if (VT.isScalableVector()) {
1138 Results.push_back(TLI.expandBITREVERSE(Node, DAG));
1142 // If we have the scalar operation, it's probably cheaper to unroll it.
1143 if (TLI.isOperationLegalOrCustom(ISD::BITREVERSE, VT.getScalarType())) {
1144 SDValue Tmp = DAG.UnrollVectorOp(Node);
1145 Results.push_back(Tmp);
1149 // If the vector element width is a whole number of bytes, test if its legal
1150 // to BSWAP shuffle the bytes and then perform the BITREVERSE on the byte
1151 // vector. This greatly reduces the number of bit shifts necessary.
1152 unsigned ScalarSizeInBits = VT.getScalarSizeInBits();
1153 if (ScalarSizeInBits > 8 && (ScalarSizeInBits % 8) == 0) {
1154 SmallVector<int, 16> BSWAPMask;
1155 createBSWAPShuffleMask(VT, BSWAPMask);
1157 EVT ByteVT = EVT::getVectorVT(*DAG.getContext(), MVT::i8, BSWAPMask.size());
1158 if (TLI.isShuffleMaskLegal(BSWAPMask, ByteVT) &&
1159 (TLI.isOperationLegalOrCustom(ISD::BITREVERSE, ByteVT) ||
1160 (TLI.isOperationLegalOrCustom(ISD::SHL, ByteVT) &&
1161 TLI.isOperationLegalOrCustom(ISD::SRL, ByteVT) &&
1162 TLI.isOperationLegalOrCustomOrPromote(ISD::AND, ByteVT) &&
1163 TLI.isOperationLegalOrCustomOrPromote(ISD::OR, ByteVT)))) {
1165 SDValue Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Node->getOperand(0));
1166 Op = DAG.getVectorShuffle(ByteVT, DL, Op, DAG.getUNDEF(ByteVT),
1168 Op = DAG.getNode(ISD::BITREVERSE, DL, ByteVT, Op);
1169 Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
1170 Results.push_back(Op);
1175 // If we have the appropriate vector bit operations, it is better to use them
1176 // than unrolling and expanding each component.
1177 if (TLI.isOperationLegalOrCustom(ISD::SHL, VT) &&
1178 TLI.isOperationLegalOrCustom(ISD::SRL, VT) &&
1179 TLI.isOperationLegalOrCustomOrPromote(ISD::AND, VT) &&
1180 TLI.isOperationLegalOrCustomOrPromote(ISD::OR, VT)) {
1181 Results.push_back(TLI.expandBITREVERSE(Node, DAG));
1185 // Otherwise unroll.
1186 SDValue Tmp = DAG.UnrollVectorOp(Node);
1187 Results.push_back(Tmp);
1190 SDValue VectorLegalizer::ExpandVSELECT(SDNode *Node) {
1191 // Implement VSELECT in terms of XOR, AND, OR
1192 // on platforms which do not support blend natively.
1195 SDValue Mask = Node->getOperand(0);
1196 SDValue Op1 = Node->getOperand(1);
1197 SDValue Op2 = Node->getOperand(2);
1199 EVT VT = Mask.getValueType();
1201 // If we can't even use the basic vector operations of
1202 // AND,OR,XOR, we will have to scalarize the op.
1203 // Notice that the operation may be 'promoted' which means that it is
1204 // 'bitcasted' to another type which is handled.
1205 if (TLI.getOperationAction(ISD::AND, VT) == TargetLowering::Expand ||
1206 TLI.getOperationAction(ISD::XOR, VT) == TargetLowering::Expand ||
1207 TLI.getOperationAction(ISD::OR, VT) == TargetLowering::Expand)
1208 return DAG.UnrollVectorOp(Node);
1210 // This operation also isn't safe with AND, OR, XOR when the boolean type is
1211 // 0/1 and the select operands aren't also booleans, as we need an all-ones
1212 // vector constant to mask with.
1213 // FIXME: Sign extend 1 to all ones if that's legal on the target.
1214 auto BoolContents = TLI.getBooleanContents(Op1.getValueType());
1215 if (BoolContents != TargetLowering::ZeroOrNegativeOneBooleanContent &&
1216 !(BoolContents == TargetLowering::ZeroOrOneBooleanContent &&
1217 Op1.getValueType().getVectorElementType() == MVT::i1))
1218 return DAG.UnrollVectorOp(Node);
1220 // If the mask and the type are different sizes, unroll the vector op. This
1221 // can occur when getSetCCResultType returns something that is different in
1222 // size from the operand types. For example, v4i8 = select v4i32, v4i8, v4i8.
1223 if (VT.getSizeInBits() != Op1.getValueSizeInBits())
1224 return DAG.UnrollVectorOp(Node);
1226 // Bitcast the operands to be the same type as the mask.
1227 // This is needed when we select between FP types because
1228 // the mask is a vector of integers.
1229 Op1 = DAG.getNode(ISD::BITCAST, DL, VT, Op1);
1230 Op2 = DAG.getNode(ISD::BITCAST, DL, VT, Op2);
1232 SDValue NotMask = DAG.getNOT(DL, Mask, VT);
1234 Op1 = DAG.getNode(ISD::AND, DL, VT, Op1, Mask);
1235 Op2 = DAG.getNode(ISD::AND, DL, VT, Op2, NotMask);
1236 SDValue Val = DAG.getNode(ISD::OR, DL, VT, Op1, Op2);
1237 return DAG.getNode(ISD::BITCAST, DL, Node->getValueType(0), Val);
1240 SDValue VectorLegalizer::ExpandVP_SELECT(SDNode *Node) {
1241 // Implement VP_SELECT in terms of VP_XOR, VP_AND and VP_OR on platforms which
1242 // do not support it natively.
1245 SDValue Mask = Node->getOperand(0);
1246 SDValue Op1 = Node->getOperand(1);
1247 SDValue Op2 = Node->getOperand(2);
1248 SDValue EVL = Node->getOperand(3);
1250 EVT VT = Mask.getValueType();
1252 // If we can't even use the basic vector operations of
1253 // VP_AND,VP_OR,VP_XOR, we will have to scalarize the op.
1254 if (TLI.getOperationAction(ISD::VP_AND, VT) == TargetLowering::Expand ||
1255 TLI.getOperationAction(ISD::VP_XOR, VT) == TargetLowering::Expand ||
1256 TLI.getOperationAction(ISD::VP_OR, VT) == TargetLowering::Expand)
1257 return DAG.UnrollVectorOp(Node);
1259 // This operation also isn't safe when the operands aren't also booleans.
1260 if (Op1.getValueType().getVectorElementType() != MVT::i1)
1261 return DAG.UnrollVectorOp(Node);
1263 SDValue Ones = DAG.getAllOnesConstant(DL, VT);
1264 SDValue NotMask = DAG.getNode(ISD::VP_XOR, DL, VT, Mask, Ones, Mask, EVL);
1266 Op1 = DAG.getNode(ISD::VP_AND, DL, VT, Op1, Mask, Mask, EVL);
1267 Op2 = DAG.getNode(ISD::VP_AND, DL, VT, Op2, NotMask, Mask, EVL);
1268 return DAG.getNode(ISD::VP_OR, DL, VT, Op1, Op2, Mask, EVL);
1271 SDValue VectorLegalizer::ExpandVP_MERGE(SDNode *Node) {
1272 // Implement VP_MERGE in terms of VSELECT. Construct a mask where vector
1273 // indices less than the EVL/pivot are true. Combine that with the original
1274 // mask for a full-length mask. Use a full-length VSELECT to select between
1275 // the true and false values.
1278 SDValue Mask = Node->getOperand(0);
1279 SDValue Op1 = Node->getOperand(1);
1280 SDValue Op2 = Node->getOperand(2);
1281 SDValue EVL = Node->getOperand(3);
1283 EVT MaskVT = Mask.getValueType();
1284 bool IsFixedLen = MaskVT.isFixedLengthVector();
1286 EVT EVLVecVT = EVT::getVectorVT(*DAG.getContext(), EVL.getValueType(),
1287 MaskVT.getVectorElementCount());
1289 // If we can't construct the EVL mask efficiently, it's better to unroll.
1291 !TLI.isOperationLegalOrCustom(ISD::BUILD_VECTOR, EVLVecVT)) ||
1293 (!TLI.isOperationLegalOrCustom(ISD::STEP_VECTOR, EVLVecVT) ||
1294 !TLI.isOperationLegalOrCustom(ISD::SPLAT_VECTOR, EVLVecVT))))
1295 return DAG.UnrollVectorOp(Node);
1297 // If using a SETCC would result in a different type than the mask type,
1299 if (TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
1300 EVLVecVT) != MaskVT)
1301 return DAG.UnrollVectorOp(Node);
1303 SDValue StepVec = DAG.getStepVector(DL, EVLVecVT);
1304 SDValue SplatEVL = IsFixedLen ? DAG.getSplatBuildVector(EVLVecVT, DL, EVL)
1305 : DAG.getSplatVector(EVLVecVT, DL, EVL);
1307 DAG.getSetCC(DL, MaskVT, StepVec, SplatEVL, ISD::CondCode::SETULT);
1309 SDValue FullMask = DAG.getNode(ISD::AND, DL, MaskVT, Mask, EVLMask);
1310 return DAG.getSelect(DL, Node->getValueType(0), FullMask, Op1, Op2);
1313 void VectorLegalizer::ExpandFP_TO_UINT(SDNode *Node,
1314 SmallVectorImpl<SDValue> &Results) {
1315 // Attempt to expand using TargetLowering.
1316 SDValue Result, Chain;
1317 if (TLI.expandFP_TO_UINT(Node, Result, Chain, DAG)) {
1318 Results.push_back(Result);
1319 if (Node->isStrictFPOpcode())
1320 Results.push_back(Chain);
1324 // Otherwise go ahead and unroll.
1325 if (Node->isStrictFPOpcode()) {
1326 UnrollStrictFPOp(Node, Results);
1330 Results.push_back(DAG.UnrollVectorOp(Node));
1333 void VectorLegalizer::ExpandUINT_TO_FLOAT(SDNode *Node,
1334 SmallVectorImpl<SDValue> &Results) {
1335 bool IsStrict = Node->isStrictFPOpcode();
1336 unsigned OpNo = IsStrict ? 1 : 0;
1337 SDValue Src = Node->getOperand(OpNo);
1338 EVT VT = Src.getValueType();
1341 // Attempt to expand using TargetLowering.
1344 if (TLI.expandUINT_TO_FP(Node, Result, Chain, DAG)) {
1345 Results.push_back(Result);
1347 Results.push_back(Chain);
1351 // Make sure that the SINT_TO_FP and SRL instructions are available.
1352 if (((!IsStrict && TLI.getOperationAction(ISD::SINT_TO_FP, VT) ==
1353 TargetLowering::Expand) ||
1354 (IsStrict && TLI.getOperationAction(ISD::STRICT_SINT_TO_FP, VT) ==
1355 TargetLowering::Expand)) ||
1356 TLI.getOperationAction(ISD::SRL, VT) == TargetLowering::Expand) {
1358 UnrollStrictFPOp(Node, Results);
1362 Results.push_back(DAG.UnrollVectorOp(Node));
1366 unsigned BW = VT.getScalarSizeInBits();
1367 assert((BW == 64 || BW == 32) &&
1368 "Elements in vector-UINT_TO_FP must be 32 or 64 bits wide");
1370 SDValue HalfWord = DAG.getConstant(BW / 2, DL, VT);
1372 // Constants to clear the upper part of the word.
1373 // Notice that we can also use SHL+SHR, but using a constant is slightly
1375 uint64_t HWMask = (BW == 64) ? 0x00000000FFFFFFFF : 0x0000FFFF;
1376 SDValue HalfWordMask = DAG.getConstant(HWMask, DL, VT);
1378 // Two to the power of half-word-size.
1380 DAG.getConstantFP(1ULL << (BW / 2), DL, Node->getValueType(0));
1382 // Clear upper part of LO, lower HI
1383 SDValue HI = DAG.getNode(ISD::SRL, DL, VT, Src, HalfWord);
1384 SDValue LO = DAG.getNode(ISD::AND, DL, VT, Src, HalfWordMask);
1387 // Convert hi and lo to floats
1388 // Convert the hi part back to the upper values
1389 // TODO: Can any fast-math-flags be set on these nodes?
1390 SDValue fHI = DAG.getNode(ISD::STRICT_SINT_TO_FP, DL,
1391 {Node->getValueType(0), MVT::Other},
1392 {Node->getOperand(0), HI});
1393 fHI = DAG.getNode(ISD::STRICT_FMUL, DL, {Node->getValueType(0), MVT::Other},
1394 {fHI.getValue(1), fHI, TWOHW});
1395 SDValue fLO = DAG.getNode(ISD::STRICT_SINT_TO_FP, DL,
1396 {Node->getValueType(0), MVT::Other},
1397 {Node->getOperand(0), LO});
1399 SDValue TF = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, fHI.getValue(1),
1402 // Add the two halves
1404 DAG.getNode(ISD::STRICT_FADD, DL, {Node->getValueType(0), MVT::Other},
1407 Results.push_back(Result);
1408 Results.push_back(Result.getValue(1));
1412 // Convert hi and lo to floats
1413 // Convert the hi part back to the upper values
1414 // TODO: Can any fast-math-flags be set on these nodes?
1415 SDValue fHI = DAG.getNode(ISD::SINT_TO_FP, DL, Node->getValueType(0), HI);
1416 fHI = DAG.getNode(ISD::FMUL, DL, Node->getValueType(0), fHI, TWOHW);
1417 SDValue fLO = DAG.getNode(ISD::SINT_TO_FP, DL, Node->getValueType(0), LO);
1419 // Add the two halves
1421 DAG.getNode(ISD::FADD, DL, Node->getValueType(0), fHI, fLO));
1424 SDValue VectorLegalizer::ExpandFNEG(SDNode *Node) {
1425 if (TLI.isOperationLegalOrCustom(ISD::FSUB, Node->getValueType(0))) {
1427 SDValue Zero = DAG.getConstantFP(-0.0, DL, Node->getValueType(0));
1428 // TODO: If FNEG had fast-math-flags, they'd get propagated to this FSUB.
1429 return DAG.getNode(ISD::FSUB, DL, Node->getValueType(0), Zero,
1430 Node->getOperand(0));
1432 return DAG.UnrollVectorOp(Node);
1435 void VectorLegalizer::ExpandFSUB(SDNode *Node,
1436 SmallVectorImpl<SDValue> &Results) {
1437 // For floating-point values, (a-b) is the same as a+(-b). If FNEG is legal,
1438 // we can defer this to operation legalization where it will be lowered as
1440 EVT VT = Node->getValueType(0);
1441 if (TLI.isOperationLegalOrCustom(ISD::FNEG, VT) &&
1442 TLI.isOperationLegalOrCustom(ISD::FADD, VT))
1443 return; // Defer to LegalizeDAG
1445 SDValue Tmp = DAG.UnrollVectorOp(Node);
1446 Results.push_back(Tmp);
1449 void VectorLegalizer::ExpandSETCC(SDNode *Node,
1450 SmallVectorImpl<SDValue> &Results) {
1451 bool NeedInvert = false;
1452 bool IsVP = Node->getOpcode() == ISD::VP_SETCC;
1454 MVT OpVT = Node->getOperand(0).getSimpleValueType();
1455 ISD::CondCode CCCode = cast<CondCodeSDNode>(Node->getOperand(2))->get();
1457 if (TLI.getCondCodeAction(CCCode, OpVT) != TargetLowering::Expand) {
1458 Results.push_back(UnrollVSETCC(Node));
1463 SDValue LHS = Node->getOperand(0);
1464 SDValue RHS = Node->getOperand(1);
1465 SDValue CC = Node->getOperand(2);
1468 Mask = Node->getOperand(3);
1469 EVL = Node->getOperand(4);
1473 TLI.LegalizeSetCCCondCode(DAG, Node->getValueType(0), LHS, RHS, CC, Mask,
1474 EVL, NeedInvert, dl, Chain);
1477 // If we expanded the SETCC by swapping LHS and RHS, or by inverting the
1478 // condition code, create a new SETCC node.
1481 LHS = DAG.getNode(ISD::SETCC, dl, Node->getValueType(0), LHS, RHS, CC,
1484 LHS = DAG.getNode(ISD::VP_SETCC, dl, Node->getValueType(0),
1485 {LHS, RHS, CC, Mask, EVL}, Node->getFlags());
1488 // If we expanded the SETCC by inverting the condition code, then wrap
1489 // the existing SETCC in a NOT to restore the intended condition.
1492 LHS = DAG.getLogicalNOT(dl, LHS, LHS->getValueType(0));
1494 LHS = DAG.getVPLogicalNOT(dl, LHS, Mask, EVL, LHS->getValueType(0));
1497 // Otherwise, SETCC for the given comparison type must be completely
1498 // illegal; expand it into a SELECT_CC.
1499 EVT VT = Node->getValueType(0);
1501 DAG.getNode(ISD::SELECT_CC, dl, VT, LHS, RHS,
1502 DAG.getBoolConstant(true, dl, VT, LHS.getValueType()),
1503 DAG.getBoolConstant(false, dl, VT, LHS.getValueType()), CC);
1504 LHS->setFlags(Node->getFlags());
1507 Results.push_back(LHS);
1510 void VectorLegalizer::ExpandUADDSUBO(SDNode *Node,
1511 SmallVectorImpl<SDValue> &Results) {
1512 SDValue Result, Overflow;
1513 TLI.expandUADDSUBO(Node, Result, Overflow, DAG);
1514 Results.push_back(Result);
1515 Results.push_back(Overflow);
1518 void VectorLegalizer::ExpandSADDSUBO(SDNode *Node,
1519 SmallVectorImpl<SDValue> &Results) {
1520 SDValue Result, Overflow;
1521 TLI.expandSADDSUBO(Node, Result, Overflow, DAG);
1522 Results.push_back(Result);
1523 Results.push_back(Overflow);
1526 void VectorLegalizer::ExpandMULO(SDNode *Node,
1527 SmallVectorImpl<SDValue> &Results) {
1528 SDValue Result, Overflow;
1529 if (!TLI.expandMULO(Node, Result, Overflow, DAG))
1530 std::tie(Result, Overflow) = DAG.UnrollVectorOverflowOp(Node);
1532 Results.push_back(Result);
1533 Results.push_back(Overflow);
1536 void VectorLegalizer::ExpandFixedPointDiv(SDNode *Node,
1537 SmallVectorImpl<SDValue> &Results) {
1539 if (SDValue Expanded = TLI.expandFixedPointDiv(N->getOpcode(), SDLoc(N),
1540 N->getOperand(0), N->getOperand(1), N->getConstantOperandVal(2), DAG))
1541 Results.push_back(Expanded);
1544 void VectorLegalizer::ExpandStrictFPOp(SDNode *Node,
1545 SmallVectorImpl<SDValue> &Results) {
1546 if (Node->getOpcode() == ISD::STRICT_UINT_TO_FP) {
1547 ExpandUINT_TO_FLOAT(Node, Results);
1550 if (Node->getOpcode() == ISD::STRICT_FP_TO_UINT) {
1551 ExpandFP_TO_UINT(Node, Results);
1555 UnrollStrictFPOp(Node, Results);
1558 void VectorLegalizer::ExpandREM(SDNode *Node,
1559 SmallVectorImpl<SDValue> &Results) {
1560 assert((Node->getOpcode() == ISD::SREM || Node->getOpcode() == ISD::UREM) &&
1561 "Expected REM node");
1564 if (!TLI.expandREM(Node, Result, DAG))
1565 Result = DAG.UnrollVectorOp(Node);
1566 Results.push_back(Result);
1569 void VectorLegalizer::UnrollStrictFPOp(SDNode *Node,
1570 SmallVectorImpl<SDValue> &Results) {
1571 EVT VT = Node->getValueType(0);
1572 EVT EltVT = VT.getVectorElementType();
1573 unsigned NumElems = VT.getVectorNumElements();
1574 unsigned NumOpers = Node->getNumOperands();
1575 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1577 EVT TmpEltVT = EltVT;
1578 if (Node->getOpcode() == ISD::STRICT_FSETCC ||
1579 Node->getOpcode() == ISD::STRICT_FSETCCS)
1580 TmpEltVT = TLI.getSetCCResultType(DAG.getDataLayout(),
1581 *DAG.getContext(), TmpEltVT);
1583 EVT ValueVTs[] = {TmpEltVT, MVT::Other};
1584 SDValue Chain = Node->getOperand(0);
1587 SmallVector<SDValue, 32> OpValues;
1588 SmallVector<SDValue, 32> OpChains;
1589 for (unsigned i = 0; i < NumElems; ++i) {
1590 SmallVector<SDValue, 4> Opers;
1591 SDValue Idx = DAG.getVectorIdxConstant(i, dl);
1593 // The Chain is the first operand.
1594 Opers.push_back(Chain);
1596 // Now process the remaining operands.
1597 for (unsigned j = 1; j < NumOpers; ++j) {
1598 SDValue Oper = Node->getOperand(j);
1599 EVT OperVT = Oper.getValueType();
1601 if (OperVT.isVector())
1602 Oper = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
1603 OperVT.getVectorElementType(), Oper, Idx);
1605 Opers.push_back(Oper);
1608 SDValue ScalarOp = DAG.getNode(Node->getOpcode(), dl, ValueVTs, Opers);
1609 SDValue ScalarResult = ScalarOp.getValue(0);
1610 SDValue ScalarChain = ScalarOp.getValue(1);
1612 if (Node->getOpcode() == ISD::STRICT_FSETCC ||
1613 Node->getOpcode() == ISD::STRICT_FSETCCS)
1614 ScalarResult = DAG.getSelect(dl, EltVT, ScalarResult,
1615 DAG.getAllOnesConstant(dl, EltVT),
1616 DAG.getConstant(0, dl, EltVT));
1618 OpValues.push_back(ScalarResult);
1619 OpChains.push_back(ScalarChain);
1622 SDValue Result = DAG.getBuildVector(VT, dl, OpValues);
1623 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OpChains);
1625 Results.push_back(Result);
1626 Results.push_back(NewChain);
1629 SDValue VectorLegalizer::UnrollVSETCC(SDNode *Node) {
1630 EVT VT = Node->getValueType(0);
1631 unsigned NumElems = VT.getVectorNumElements();
1632 EVT EltVT = VT.getVectorElementType();
1633 SDValue LHS = Node->getOperand(0);
1634 SDValue RHS = Node->getOperand(1);
1635 SDValue CC = Node->getOperand(2);
1636 EVT TmpEltVT = LHS.getValueType().getVectorElementType();
1638 SmallVector<SDValue, 8> Ops(NumElems);
1639 for (unsigned i = 0; i < NumElems; ++i) {
1640 SDValue LHSElem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, TmpEltVT, LHS,
1641 DAG.getVectorIdxConstant(i, dl));
1642 SDValue RHSElem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, TmpEltVT, RHS,
1643 DAG.getVectorIdxConstant(i, dl));
1644 Ops[i] = DAG.getNode(ISD::SETCC, dl,
1645 TLI.getSetCCResultType(DAG.getDataLayout(),
1646 *DAG.getContext(), TmpEltVT),
1647 LHSElem, RHSElem, CC);
1648 Ops[i] = DAG.getSelect(dl, EltVT, Ops[i], DAG.getAllOnesConstant(dl, EltVT),
1649 DAG.getConstant(0, dl, EltVT));
1651 return DAG.getBuildVector(VT, dl, Ops);
1654 bool SelectionDAG::LegalizeVectors() {
1655 return VectorLegalizer(*this).Run();