LLVM 24.0.0git
RISCVLegalizerInfo.cpp
Go to the documentation of this file.
1//===-- RISCVLegalizerInfo.cpp ----------------------------------*- C++ -*-===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8/// \file
9/// This file implements the targeting of the Machinelegalizer class for RISC-V.
10/// \todo This should be generated by TableGen.
11//===----------------------------------------------------------------------===//
12
13#include "RISCVLegalizerInfo.h"
16#include "RISCVSubtarget.h"
17#include "llvm/ADT/APFloat.h"
32#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/IntrinsicsRISCV.h"
34#include "llvm/IR/Type.h"
35
36using namespace llvm;
37using namespace LegalityPredicates;
38using namespace LegalizeMutations;
39using namespace MIPatternMatch;
40
42typeIsLegalIntOrFPVec(unsigned TypeIdx,
43 std::initializer_list<LLT> IntOrFPVecTys,
44 const RISCVSubtarget &ST) {
45 LegalityPredicate P = [=, &ST](const LegalityQuery &Query) {
46 return ST.hasVInstructions() &&
47 (Query.Types[TypeIdx].getScalarSizeInBits() != 64 ||
48 ST.hasVInstructionsI64()) &&
49 (Query.Types[TypeIdx].getElementCount().getKnownMinValue() != 1 ||
50 ST.getELen() == 64);
51 };
52
53 return all(typeInSet(TypeIdx, IntOrFPVecTys), P);
54}
55
57typeIsLegalBoolVec(unsigned TypeIdx, std::initializer_list<LLT> BoolVecTys,
58 const RISCVSubtarget &ST) {
59 LegalityPredicate P = [=, &ST](const LegalityQuery &Query) {
60 return ST.hasVInstructions() &&
61 (Query.Types[TypeIdx].getElementCount().getKnownMinValue() != 1 ||
62 ST.getELen() == 64);
63 };
64 return all(typeInSet(TypeIdx, BoolVecTys), P);
65}
66
67static LegalityPredicate typeIsLegalPtrVec(unsigned TypeIdx,
68 std::initializer_list<LLT> PtrVecTys,
69 const RISCVSubtarget &ST) {
70 LegalityPredicate P = [=, &ST](const LegalityQuery &Query) {
71 return ST.hasVInstructions() &&
72 (Query.Types[TypeIdx].getElementCount().getKnownMinValue() != 1 ||
73 ST.getELen() == 64) &&
74 (Query.Types[TypeIdx].getElementCount().getKnownMinValue() != 16 ||
75 Query.Types[TypeIdx].getScalarSizeInBits() == 32);
76 };
77 return all(typeInSet(TypeIdx, PtrVecTys), P);
78}
79
81 : STI(ST), XLen(STI.getXLen()), sXLen(LLT::scalar(XLen)),
82 iXLen(LLT::integer(XLen)) {
83 const LLT sDoubleXLen = LLT::scalar(2 * XLen);
84 const LLT p0 = LLT::pointer(0, XLen);
85 const LLT s1 = LLT::scalar(1);
86 const LLT s8 = LLT::scalar(8);
87 const LLT s16 = LLT::scalar(16);
88 const LLT f16 = LLT::float16();
89 const LLT f32 = LLT::float32();
90 const LLT f64 = LLT::float64();
91 const LLT f128 = LLT::float128();
92 const LLT s32 = LLT::scalar(32);
93 const LLT s64 = LLT::scalar(64);
94 const LLT s128 = LLT::scalar(128);
95
96 const LLT nxv1s1 = LLT::scalable_vector(1, s1);
97 const LLT nxv2s1 = LLT::scalable_vector(2, s1);
98 const LLT nxv4s1 = LLT::scalable_vector(4, s1);
99 const LLT nxv8s1 = LLT::scalable_vector(8, s1);
100 const LLT nxv16s1 = LLT::scalable_vector(16, s1);
101 const LLT nxv32s1 = LLT::scalable_vector(32, s1);
102 const LLT nxv64s1 = LLT::scalable_vector(64, s1);
103
104 const LLT nxv1s8 = LLT::scalable_vector(1, s8);
105 const LLT nxv2s8 = LLT::scalable_vector(2, s8);
106 const LLT nxv4s8 = LLT::scalable_vector(4, s8);
107 const LLT nxv8s8 = LLT::scalable_vector(8, s8);
108 const LLT nxv16s8 = LLT::scalable_vector(16, s8);
109 const LLT nxv32s8 = LLT::scalable_vector(32, s8);
110 const LLT nxv64s8 = LLT::scalable_vector(64, s8);
111
112 const LLT nxv1s16 = LLT::scalable_vector(1, s16);
113 const LLT nxv2s16 = LLT::scalable_vector(2, s16);
114 const LLT nxv4s16 = LLT::scalable_vector(4, s16);
115 const LLT nxv8s16 = LLT::scalable_vector(8, s16);
116 const LLT nxv16s16 = LLT::scalable_vector(16, s16);
117 const LLT nxv32s16 = LLT::scalable_vector(32, s16);
118
119 const LLT nxv1s32 = LLT::scalable_vector(1, s32);
120 const LLT nxv2s32 = LLT::scalable_vector(2, s32);
121 const LLT nxv4s32 = LLT::scalable_vector(4, s32);
122 const LLT nxv8s32 = LLT::scalable_vector(8, s32);
123 const LLT nxv16s32 = LLT::scalable_vector(16, s32);
124
125 const LLT nxv1s64 = LLT::scalable_vector(1, s64);
126 const LLT nxv2s64 = LLT::scalable_vector(2, s64);
127 const LLT nxv4s64 = LLT::scalable_vector(4, s64);
128 const LLT nxv8s64 = LLT::scalable_vector(8, s64);
129
130 const LLT nxv1p0 = LLT::scalable_vector(1, p0);
131 const LLT nxv2p0 = LLT::scalable_vector(2, p0);
132 const LLT nxv4p0 = LLT::scalable_vector(4, p0);
133 const LLT nxv8p0 = LLT::scalable_vector(8, p0);
134 const LLT nxv16p0 = LLT::scalable_vector(16, p0);
135
136 using namespace TargetOpcode;
137
138 auto BoolVecTys = {nxv1s1, nxv2s1, nxv4s1, nxv8s1, nxv16s1, nxv32s1, nxv64s1};
139
140 auto IntOrFPVecTys = {nxv1s8, nxv2s8, nxv4s8, nxv8s8, nxv16s8, nxv32s8,
141 nxv64s8, nxv1s16, nxv2s16, nxv4s16, nxv8s16, nxv16s16,
142 nxv32s16, nxv1s32, nxv2s32, nxv4s32, nxv8s32, nxv16s32,
143 nxv1s64, nxv2s64, nxv4s64, nxv8s64};
144
145 auto PtrVecTys = {nxv1p0, nxv2p0, nxv4p0, nxv8p0, nxv16p0};
146
147 getActionDefinitionsBuilder({G_ADD, G_SUB})
148 .legalFor({sXLen})
149 .legalIf(typeIsLegalIntOrFPVec(0, IntOrFPVecTys, ST))
150 .customFor(ST.is64Bit(), {s32})
152 .clampScalar(0, sXLen, sXLen);
153
154 getActionDefinitionsBuilder({G_AND, G_OR, G_XOR})
155 .legalFor({sXLen})
156 .legalIf(typeIsLegalIntOrFPVec(0, IntOrFPVecTys, ST))
158 .clampScalar(0, sXLen, sXLen);
159
161 {G_UADDE, G_UADDO, G_USUBE, G_USUBO, G_READ_REGISTER, G_WRITE_REGISTER})
162 .lower();
163
164 getActionDefinitionsBuilder({G_SADDE, G_SADDO, G_SSUBE, G_SSUBO})
165 .minScalar(0, sXLen)
166 .lower();
167
168 // TODO: Use Vector Single-Width Saturating Instructions for vector types.
170 {G_UADDSAT, G_SADDSAT, G_USUBSAT, G_SSUBSAT, G_SSHLSAT, G_USHLSAT})
171 .lower();
172
173 LegalityPredicate ShiftAmtSameTypePred = [](const LegalityQuery &Query) {
174 return Query.Types[0] == Query.Types[1];
175 };
176 getActionDefinitionsBuilder({G_SHL, G_ASHR, G_LSHR})
177 .legalFor({{sXLen, sXLen}})
178 .legalIf(all(typeIsLegalIntOrFPVec(0, IntOrFPVecTys, ST),
179 ShiftAmtSameTypePred))
180 .customFor(ST.is64Bit(), {{s32, s32}})
181 .widenScalarToNextPow2(0)
182 .clampScalar(1, sXLen, sXLen)
183 .clampScalar(0, sXLen, sXLen);
184
185 getActionDefinitionsBuilder({G_ZEXT, G_SEXT, G_ANYEXT})
186 .legalFor({{s32, s16}})
187 .legalFor(ST.is64Bit(), {{s64, s16}, {s64, s32}})
188 .legalIf(all(typeIsLegalIntOrFPVec(0, IntOrFPVecTys, ST),
189 typeIsLegalIntOrFPVec(1, IntOrFPVecTys, ST)))
190 .customIf(typeIsLegalBoolVec(1, BoolVecTys, ST))
191 .maxScalar(0, sXLen);
192
193 getActionDefinitionsBuilder(G_TRUNC).alwaysLegal();
194
195 {
196 LegalityPredicate ValidSextInRegWidth = all(sizeIs(0, 64), immIs(0, 32));
197
198 if (STI.hasStdExtZbb())
199 ValidSextInRegWidth =
200 LegalityPredicates::any(ValidSextInRegWidth, immInSet(0, {8, 16}));
201
202 getActionDefinitionsBuilder(G_SEXT_INREG)
203 .legalIf(all(typeIs(0, sXLen), ValidSextInRegWidth))
204 .clampScalar(0, sXLen, sXLen)
205 .lower();
206 }
207
208 // Merge/Unmerge
209 for (unsigned Op : {G_MERGE_VALUES, G_UNMERGE_VALUES}) {
210 auto &MergeUnmergeActions = getActionDefinitionsBuilder(Op);
211 unsigned BigTyIdx = Op == G_MERGE_VALUES ? 0 : 1;
212 unsigned LitTyIdx = Op == G_MERGE_VALUES ? 1 : 0;
213 if (XLen == 32 && (ST.hasStdExtD() || ST.hasStdExtZilsd())) {
214 MergeUnmergeActions.legalIf(
215 all(typeIs(BigTyIdx, s64), typeIs(LitTyIdx, s32)));
216 }
217 MergeUnmergeActions.widenScalarToNextPow2(LitTyIdx, XLen)
218 .widenScalarToNextPow2(BigTyIdx, XLen)
219 .clampScalar(LitTyIdx, sXLen, sXLen)
220 .clampScalar(BigTyIdx, sXLen, sXLen);
221 }
222
223 getActionDefinitionsBuilder({G_FSHL, G_FSHR}).lower();
224
225 getActionDefinitionsBuilder({G_ROTR, G_ROTL})
226 .legalFor(ST.hasStdExtZbb() || ST.hasStdExtZbkb(), {{sXLen, sXLen}})
227 .customFor(ST.is64Bit() && (ST.hasStdExtZbb() || ST.hasStdExtZbkb()),
228 {{s32, s32}})
229 .lower();
230
231 getActionDefinitionsBuilder(G_BITREVERSE)
232 .customFor(ST.hasStdExtZbkb(), {s8})
233 .lowerIf(scalarNarrowerThan(0, 8))
234 .widenScalarToNextPow2(0)
235 .maxScalar(0, sXLen)
236 .lower();
237
238 getActionDefinitionsBuilder(G_BITCAST)
239 .legalIf(all(
241 typeIsLegalBoolVec(0, BoolVecTys, ST)),
243 typeIsLegalBoolVec(1, BoolVecTys, ST))))
244 // Scalar int <-> fp bitcasts that fit in a GPR are register moves.
245 .legalIf(all(isScalar(0), isScalar(1), scalarNarrowerThan(0, XLen + 1)))
246 // Wider ones (i128/f128, or f64/i64 on RV32) are split into XLen pieces.
247 .narrowScalarIf(all(isScalar(0), isScalar(1), scalarWiderThan(0, XLen)),
249
250 auto &BSWAPActions = getActionDefinitionsBuilder(G_BSWAP);
251 if (ST.hasStdExtZbb() || ST.hasStdExtZbkb())
252 BSWAPActions.legalFor({sXLen}).clampScalar(0, sXLen, sXLen);
253 else
254 BSWAPActions.maxScalar(0, sXLen).lower();
255
256 getActionDefinitionsBuilder(G_CLMUL)
257 .legalFor(ST.hasStdExtZbkc(), {sXLen})
258 .unsupported();
259
260 getActionDefinitionsBuilder(G_CLMULH)
261 .legalFor(ST.hasStdExtZbkc(), {sXLen})
262 .customFor(ST.is64Bit() && ST.hasStdExtZbkc(), {s32})
263 .unsupported();
264
265 // CLMULR is Zbc-only; Zbkc is a subset that has CLMUL/CLMULH but not CLMULR.
266 getActionDefinitionsBuilder(G_CLMULR)
267 .legalFor(ST.hasStdExtZbc(), {sXLen})
268 .customFor(ST.is64Bit() && ST.hasStdExtZbc(), {s32})
269 .unsupported();
270
271 auto &CTLZPoisonActions = getActionDefinitionsBuilder(G_CTLZ_ZERO_POISON);
272 auto &CTTZPoisonActions = getActionDefinitionsBuilder(G_CTTZ_ZERO_POISON);
273 if (ST.hasStdExtZbb()) {
274 getActionDefinitionsBuilder({G_CTLZ, G_CTTZ})
275 .legalFor({{sXLen, sXLen}})
276 .customFor({{s32, s32}})
277 .clampScalar(0, s32, sXLen)
278 .widenScalarToNextPow2(0)
279 .scalarSameSizeAs(1, 0);
280 } else {
281 auto &CTLZActions = getActionDefinitionsBuilder(G_CTLZ);
282 if (ST.hasVendorXTHeadBb())
283 CTLZActions.legalFor({{sXLen, sXLen}})
284 .clampScalar(0, sXLen, sXLen)
285 .scalarSameSizeAs(1, 0);
286 else
287 CTLZActions.maxScalar(0, sXLen).scalarSameSizeAs(1, 0).lower();
288
289 auto &CTTZActions = getActionDefinitionsBuilder(G_CTTZ);
290 if (ST.hasVendorXTHeadBb()) {
291 CTTZActions.clampScalar(0, sXLen, sXLen).scalarSameSizeAs(1, 0).lower();
292 CTLZPoisonActions.clampScalar(0, sXLen, sXLen).scalarSameSizeAs(1, 0);
293 CTTZPoisonActions.clampScalar(0, sXLen, sXLen).scalarSameSizeAs(1, 0);
294 } else {
295 CTTZActions.maxScalar(0, sXLen).scalarSameSizeAs(1, 0).lower();
296 CTLZPoisonActions.maxScalar(0, sXLen).scalarSameSizeAs(1, 0);
297 CTTZPoisonActions.maxScalar(0, sXLen).scalarSameSizeAs(1, 0);
298 }
299 }
300 CTLZPoisonActions.lower();
301 CTTZPoisonActions.lower();
302
303 auto &CountSignActions = getActionDefinitionsBuilder(G_CTLS);
304 if (ST.hasStdExtP()) {
305 CountSignActions.legalFor({{sXLen, sXLen}})
306 .customFor({{s32, s32}})
307 .clampScalar(0, s32, sXLen)
308 .widenScalarToNextPow2(0)
309 .scalarSameSizeAs(1, 0);
310 } else {
311 CountSignActions.maxScalar(0, sXLen).scalarSameSizeAs(1, 0).lower();
312 }
313
314 auto &CTPOPActions = getActionDefinitionsBuilder(G_CTPOP);
315 if (ST.hasStdExtZbb()) {
316 CTPOPActions.legalFor({{sXLen, sXLen}})
317 .clampScalar(0, sXLen, sXLen)
318 .scalarSameSizeAs(1, 0);
319 } else {
320 CTPOPActions.widenScalarToNextPow2(0, /*Min*/ 8)
321 .clampScalar(0, s8, sXLen)
322 .scalarSameSizeAs(1, 0)
323 .lower();
324 }
325
326 getActionDefinitionsBuilder(G_CONSTANT)
327 .legalFor({p0})
328 .legalFor(!ST.is64Bit(), {s32})
329 .customFor(ST.is64Bit(), {s64})
330 .widenScalarToNextPow2(0)
331 .clampScalar(0, sXLen, sXLen);
332
333 // TODO: transform illegal vector types into legal vector type
334 getActionDefinitionsBuilder(G_FREEZE)
335 .legalFor({s16, s32, p0})
336 .legalFor(ST.is64Bit(), {s64})
337 .legalIf(typeIsLegalBoolVec(0, BoolVecTys, ST))
338 .legalIf(typeIsLegalIntOrFPVec(0, IntOrFPVecTys, ST))
339 .widenScalarToNextPow2(0)
340 .clampScalar(0, s16, sXLen);
341
342 // TODO: transform illegal vector types into legal vector type
343 // TODO: Merge with G_FREEZE?
344 getActionDefinitionsBuilder(
345 {G_IMPLICIT_DEF, G_CONSTANT_FOLD_BARRIER})
346 .legalFor({s32, sXLen, p0})
347 .legalIf(typeIsLegalBoolVec(0, BoolVecTys, ST))
348 .legalIf(typeIsLegalIntOrFPVec(0, IntOrFPVecTys, ST))
349 .widenScalarToNextPow2(0)
350 .clampScalar(0, s32, sXLen);
351
352 getActionDefinitionsBuilder(G_ICMP)
353 .legalFor({{sXLen, sXLen}, {sXLen, p0}})
354 .legalIf(all(typeIsLegalBoolVec(0, BoolVecTys, ST),
355 typeIsLegalIntOrFPVec(1, IntOrFPVecTys, ST)))
356 .widenScalarOrEltToNextPow2OrMinSize(1, 8)
357 .clampScalar(1, sXLen, sXLen)
358 .clampScalar(0, sXLen, sXLen);
359
360 getActionDefinitionsBuilder(G_SELECT)
361 .legalFor({{s32, sXLen}, {p0, sXLen}})
362 .legalIf(all(typeIsLegalIntOrFPVec(0, IntOrFPVecTys, ST),
363 typeIsLegalBoolVec(1, BoolVecTys, ST)))
364 .legalFor(XLen == 64 || ST.hasStdExtD(), {{s64, sXLen}})
365 .widenScalarToNextPow2(0)
366 .clampScalar(0, s32, (XLen == 64 || ST.hasStdExtD()) ? s64 : s32)
367 .clampScalar(1, sXLen, sXLen);
368
369 auto &LoadActions = getActionDefinitionsBuilder(G_LOAD);
370 auto &StoreActions = getActionDefinitionsBuilder(G_STORE);
371 auto &ExtLoadActions = getActionDefinitionsBuilder({G_SEXTLOAD, G_ZEXTLOAD});
372
373 // Return the alignment needed for scalar memory ops. If unaligned scalar mem
374 // is supported, we only require byte alignment. Otherwise, we need the memory
375 // op to be natively aligned.
376 auto getScalarMemAlign = [&ST](unsigned Size) {
377 return ST.enableUnalignedScalarMem() ? 8 : Size;
378 };
379
380 LoadActions.legalForTypesWithMemDesc(
381 {{s16, p0, s8, getScalarMemAlign(8)},
382 {s32, p0, s8, getScalarMemAlign(8)},
383 {s16, p0, s16, getScalarMemAlign(16)},
384 {s32, p0, s16, getScalarMemAlign(16)},
385 {s32, p0, s32, getScalarMemAlign(32)},
386 {p0, p0, sXLen, getScalarMemAlign(XLen)}});
387 StoreActions.legalForTypesWithMemDesc(
388 {{s16, p0, s8, getScalarMemAlign(8)},
389 {s32, p0, s8, getScalarMemAlign(8)},
390 {s16, p0, s16, getScalarMemAlign(16)},
391 {s32, p0, s16, getScalarMemAlign(16)},
392 {s32, p0, s32, getScalarMemAlign(32)},
393 {p0, p0, sXLen, getScalarMemAlign(XLen)}});
394 ExtLoadActions.legalForTypesWithMemDesc(
395 {{sXLen, p0, s8, getScalarMemAlign(8)},
396 {sXLen, p0, s16, getScalarMemAlign(16)}});
397 if (XLen == 64) {
398 LoadActions.legalForTypesWithMemDesc(
399 {{s64, p0, s8, getScalarMemAlign(8)},
400 {s64, p0, s16, getScalarMemAlign(16)},
401 {s64, p0, s32, getScalarMemAlign(32)},
402 {s64, p0, s64, getScalarMemAlign(64)}});
403 StoreActions.legalForTypesWithMemDesc(
404 {{s64, p0, s8, getScalarMemAlign(8)},
405 {s64, p0, s16, getScalarMemAlign(16)},
406 {s64, p0, s32, getScalarMemAlign(32)},
407 {s64, p0, s64, getScalarMemAlign(64)}});
408 ExtLoadActions.legalForTypesWithMemDesc(
409 {{s64, p0, s32, getScalarMemAlign(32)}});
410 } else if (ST.hasStdExtD() || ST.hasStdExtZilsd()) {
411 // RV32: s64 is legal for f64 (D/Zdinx) or i64 (Zilsd); LLT cannot tell the
412 // two apart, so one rule covers both.
413 // FIXME: We require natural alignment, so under -mzilsd-word-align an
414 // align-4 i64 access is split into two s32 ones. riscv-prera-zilsd-opt
415 // merges them back into LD_RV32/SD_RV32, but it is skipped at -O0.
416 LoadActions.legalForTypesWithMemDesc(
417 {{s64, p0, s64, getScalarMemAlign(64)}});
418 StoreActions.legalForTypesWithMemDesc(
419 {{s64, p0, s64, getScalarMemAlign(64)}});
420 }
421
422 // Vector loads/stores.
423 if (ST.hasVInstructions()) {
424 LoadActions.legalForTypesWithMemDesc({{nxv2s8, p0, nxv2s8, 8},
425 {nxv4s8, p0, nxv4s8, 8},
426 {nxv8s8, p0, nxv8s8, 8},
427 {nxv16s8, p0, nxv16s8, 8},
428 {nxv32s8, p0, nxv32s8, 8},
429 {nxv64s8, p0, nxv64s8, 8},
430 {nxv2s16, p0, nxv2s16, 16},
431 {nxv4s16, p0, nxv4s16, 16},
432 {nxv8s16, p0, nxv8s16, 16},
433 {nxv16s16, p0, nxv16s16, 16},
434 {nxv32s16, p0, nxv32s16, 16},
435 {nxv2s32, p0, nxv2s32, 32},
436 {nxv4s32, p0, nxv4s32, 32},
437 {nxv8s32, p0, nxv8s32, 32},
438 {nxv16s32, p0, nxv16s32, 32}});
439 StoreActions.legalForTypesWithMemDesc({{nxv2s8, p0, nxv2s8, 8},
440 {nxv4s8, p0, nxv4s8, 8},
441 {nxv8s8, p0, nxv8s8, 8},
442 {nxv16s8, p0, nxv16s8, 8},
443 {nxv32s8, p0, nxv32s8, 8},
444 {nxv64s8, p0, nxv64s8, 8},
445 {nxv2s16, p0, nxv2s16, 16},
446 {nxv4s16, p0, nxv4s16, 16},
447 {nxv8s16, p0, nxv8s16, 16},
448 {nxv16s16, p0, nxv16s16, 16},
449 {nxv32s16, p0, nxv32s16, 16},
450 {nxv2s32, p0, nxv2s32, 32},
451 {nxv4s32, p0, nxv4s32, 32},
452 {nxv8s32, p0, nxv8s32, 32},
453 {nxv16s32, p0, nxv16s32, 32}});
454
455 if (ST.getELen() == 64) {
456 LoadActions.legalForTypesWithMemDesc({{nxv1s8, p0, nxv1s8, 8},
457 {nxv1s16, p0, nxv1s16, 16},
458 {nxv1s32, p0, nxv1s32, 32}});
459 StoreActions.legalForTypesWithMemDesc({{nxv1s8, p0, nxv1s8, 8},
460 {nxv1s16, p0, nxv1s16, 16},
461 {nxv1s32, p0, nxv1s32, 32}});
462 }
463
464 if (ST.hasVInstructionsI64()) {
465 LoadActions.legalForTypesWithMemDesc({{nxv1s64, p0, nxv1s64, 64},
466 {nxv2s64, p0, nxv2s64, 64},
467 {nxv4s64, p0, nxv4s64, 64},
468 {nxv8s64, p0, nxv8s64, 64}});
469 StoreActions.legalForTypesWithMemDesc({{nxv1s64, p0, nxv1s64, 64},
470 {nxv2s64, p0, nxv2s64, 64},
471 {nxv4s64, p0, nxv4s64, 64},
472 {nxv8s64, p0, nxv8s64, 64}});
473 }
474
475 // we will take the custom lowering logic if we have scalable vector types
476 // with non-standard alignments
477 LoadActions.customIf(typeIsLegalIntOrFPVec(0, IntOrFPVecTys, ST));
478 StoreActions.customIf(typeIsLegalIntOrFPVec(0, IntOrFPVecTys, ST));
479
480 // Pointers require that XLen sized elements are legal.
481 if (XLen <= ST.getELen()) {
482 LoadActions.customIf(typeIsLegalPtrVec(0, PtrVecTys, ST));
483 StoreActions.customIf(typeIsLegalPtrVec(0, PtrVecTys, ST));
484 }
485 }
486
487 LoadActions.widenScalarToNextPow2(0, /* MinSize = */ 8)
488 .lowerIfMemSizeNotByteSizePow2()
489 .clampScalar(0, s16, sXLen)
490 .lower();
491 StoreActions
492 .clampScalar(0, s16, sXLen)
493 .lowerIfMemSizeNotByteSizePow2()
494 .lower();
495
496 ExtLoadActions.widenScalarToNextPow2(0).clampScalar(0, sXLen, sXLen).lower();
497
498 getActionDefinitionsBuilder({G_PTR_ADD, G_PTRMASK}).legalFor({{p0, sXLen}});
499
500 getActionDefinitionsBuilder(G_PTRTOINT)
501 .legalFor({{sXLen, p0}})
502 .clampScalar(0, sXLen, sXLen);
503
504 getActionDefinitionsBuilder(G_INTTOPTR)
505 .legalFor({{p0, sXLen}})
506 .clampScalar(1, sXLen, sXLen);
507
508 getActionDefinitionsBuilder(G_BR).alwaysLegal();
509
510 getActionDefinitionsBuilder(G_BRCOND).legalFor({sXLen}).minScalar(0, sXLen);
511
512 getActionDefinitionsBuilder(G_BRJT).customFor({{p0, sXLen}});
513
514 getActionDefinitionsBuilder(G_BRINDIRECT).legalFor({p0});
515
516 getActionDefinitionsBuilder(G_PHI)
517 .legalFor({p0, s32, sXLen})
518 .widenScalarToNextPow2(0)
519 .clampScalar(0, s32, sXLen);
520
521 getActionDefinitionsBuilder({G_GLOBAL_VALUE, G_JUMP_TABLE, G_CONSTANT_POOL})
522 .legalFor({p0});
523
524 if (ST.hasStdExtZmmul()) {
525 getActionDefinitionsBuilder(G_MUL)
526 .legalFor({sXLen})
527 .legalIf(typeIsLegalIntOrFPVec(0, IntOrFPVecTys, ST))
528 .widenScalarToNextPow2(0)
529 .clampScalar(0, sXLen, sXLen);
530
531 // clang-format off
532 getActionDefinitionsBuilder({G_SMULH, G_UMULH})
533 .legalFor({sXLen})
534 .lower();
535 // clang-format on
536
537 getActionDefinitionsBuilder({G_SMULO, G_UMULO}).minScalar(0, sXLen).lower();
538 } else {
539 getActionDefinitionsBuilder(G_MUL)
540 .libcallFor({sXLen, sDoubleXLen})
541 .legalIf(typeIsLegalIntOrFPVec(0, IntOrFPVecTys, ST))
542 .widenScalarToNextPow2(0)
543 .clampScalar(0, sXLen, sDoubleXLen);
544
545 getActionDefinitionsBuilder({G_SMULH, G_UMULH}).lowerFor({sXLen});
546
547 getActionDefinitionsBuilder({G_SMULO, G_UMULO})
548 .minScalar(0, sXLen)
549 // Widen sXLen to sDoubleXLen so we can use a single libcall to get
550 // the low bits for the mul result and high bits to do the overflow
551 // check.
552 .widenScalarIf(typeIs(0, sXLen),
554 .lower();
555 }
556
557 if (ST.hasStdExtM()) {
558 getActionDefinitionsBuilder({G_SDIV, G_UDIV, G_UREM})
559 .legalFor({sXLen})
560 .legalIf(typeIsLegalIntOrFPVec(0, IntOrFPVecTys, ST))
561 .customFor({s32})
562 .libcallFor({sDoubleXLen})
563 .clampScalar(0, s32, sDoubleXLen)
564 .widenScalarToNextPow2(0);
565 getActionDefinitionsBuilder(G_SREM)
566 .legalFor({sXLen})
567 .legalIf(typeIsLegalIntOrFPVec(0, IntOrFPVecTys, ST))
568 .libcallFor({sDoubleXLen})
569 .clampScalar(0, sXLen, sDoubleXLen)
570 .widenScalarToNextPow2(0);
571 } else {
572 getActionDefinitionsBuilder({G_UDIV, G_SDIV, G_UREM, G_SREM})
573 .libcallFor({sXLen, sDoubleXLen})
574 .legalIf(typeIsLegalIntOrFPVec(0, IntOrFPVecTys, ST))
575 .clampScalar(0, sXLen, sDoubleXLen)
576 .widenScalarToNextPow2(0);
577 }
578
579 // TODO: Use libcall for sDoubleXLen.
580 getActionDefinitionsBuilder({G_SDIVREM, G_UDIVREM}).lower();
581
582 getActionDefinitionsBuilder(G_ABS)
583 .customFor(ST.hasStdExtZbb(), {sXLen})
584 .minScalar(ST.hasStdExtZbb(), 0, sXLen)
585 .lower();
586
587 getActionDefinitionsBuilder({G_ABDS, G_ABDU})
588 .minScalar(ST.hasStdExtZbb(), 0, sXLen)
589 .lower();
590
591 getActionDefinitionsBuilder({G_UMAX, G_UMIN, G_SMAX, G_SMIN})
592 .legalFor(ST.hasStdExtZbb(), {sXLen})
593 .minScalar(ST.hasStdExtZbb(), 0, sXLen)
594 .lower();
595
596 getActionDefinitionsBuilder({G_SCMP, G_UCMP}).lower();
597
598 getActionDefinitionsBuilder(G_FRAME_INDEX).legalFor({p0});
599
600 getActionDefinitionsBuilder({G_MEMCPY, G_MEMMOVE, G_MEMSET}).libcall();
601
602 getActionDefinitionsBuilder({G_MEMCPY_INLINE, G_MEMSET_INLINE}).lower();
603
604 getActionDefinitionsBuilder({G_DYN_STACKALLOC, G_STACKSAVE, G_STACKRESTORE})
605 .lower();
606
607 // On RV64 the 64-bit counter CSRs (cycle/time) are read directly. On RV32
608 // they are custom-legally lowered to a re-read-the-high-half loop (see
609 // legalizeReadCounter).
610 getActionDefinitionsBuilder({G_READCYCLECOUNTER, G_READSTEADYCOUNTER})
611 .legalFor(ST.is64Bit(), {s64})
612 .customFor(!ST.is64Bit(), {s64});
613
614 // FP Operations
615
616 // FIXME: Support f128 for rv32 when libcall handling is able to use sret.
617 getActionDefinitionsBuilder({G_FADD, G_FSUB, G_FMUL, G_FDIV, G_FMA, G_FSQRT,
618 G_FMAXNUM, G_FMINNUM, G_FMAXIMUMNUM,
619 G_FMINIMUMNUM})
620 .legalFor(ST.hasStdExtF(), {f32})
621 .legalFor(ST.hasStdExtD(), {f64})
622 .legalFor(ST.hasStdExtZfh(), {f16})
623 .libcallFor({f32, f64})
624 .libcallFor(ST.is64Bit(), {f128});
625
626 getActionDefinitionsBuilder({G_FNEG, G_FABS})
627 .legalFor(ST.hasStdExtF(), {f32})
628 .legalFor(ST.hasStdExtD(), {f64})
629 .legalFor(ST.hasStdExtZfh(), {f16})
630 .lowerFor({f32, f64, f128});
631
632 getActionDefinitionsBuilder(G_FREM)
633 .libcallFor({f32, f64})
634 .libcallFor(ST.is64Bit(), {f128})
635 .minScalar(0, f32)
636 .scalarize(0);
637
638 getActionDefinitionsBuilder(G_FCOPYSIGN)
639 .legalFor(ST.hasStdExtF(), {{f32, f32}})
640 .legalFor(ST.hasStdExtD(), {{f64, f64}, {f32, f64}, {f64, f32}})
641 .legalFor(ST.hasStdExtZfh(), {{f16, f16}, {f16, f32}, {f32, f16}})
642 .legalFor(ST.hasStdExtZfh() && ST.hasStdExtD(), {{f16, f64}, {f64, f16}})
643 .lower();
644
645 getActionDefinitionsBuilder(G_FPTRUNC)
646 .legalFor(ST.hasStdExtD(), {{f32, f64}})
647 .legalFor(ST.hasStdExtZfhmin(), {{f16, f32}})
648 .legalFor(ST.hasStdExtZfhmin() && ST.hasStdExtD(), {{f16, f64}})
649 .libcallFor({{f16, f32}, {f16, f64}, {f32, f64}})
650 .libcallFor(ST.is64Bit(), {{f32, f128}, {f64, f128}});
651 getActionDefinitionsBuilder(G_FPEXT)
652 .legalFor(ST.hasStdExtD(), {{f64, f32}})
653 .legalFor(ST.hasStdExtZfhmin(), {{f32, f16}})
654 .legalFor(ST.hasStdExtZfhmin() && ST.hasStdExtD(), {{f64, f16}})
655 .libcallFor(!ST.hasStdExtZfhmin(), {{f32, f16}})
656 .libcallFor(!(ST.hasStdExtZfhmin() && ST.hasStdExtD()), {{f64, f16}})
657 .libcallFor({{f64, f32}})
658 .libcallFor(ST.is64Bit(), {{f128, f32}, {f128, f64}});
659
660 getActionDefinitionsBuilder(G_FCMP)
661 .legalFor(ST.hasStdExtF(), {{sXLen, f32}})
662 .legalFor(ST.hasStdExtD(), {{sXLen, f64}})
663 .legalFor(ST.hasStdExtZfh(), {{sXLen, f16}})
664 .clampScalar(0, sXLen, sXLen)
665 .minScalar(1, f32)
666 .libcallFor({{sXLen, f32}, {sXLen, f64}})
667 .libcallFor(ST.is64Bit(), {{sXLen, f128}});
668
669 // TODO: Support vector version of G_IS_FPCLASS.
670 getActionDefinitionsBuilder(G_IS_FPCLASS)
671 .customFor(ST.hasStdExtF(), {{s1, f32}})
672 .customFor(ST.hasStdExtD(), {{s1, f64}})
673 .customFor(ST.hasStdExtZfh(), {{s1, f16}})
674 .lower();
675
676 getActionDefinitionsBuilder(G_FCONSTANT)
677 .legalFor(ST.hasStdExtF(), {f32})
678 .legalFor(ST.hasStdExtD(), {f64})
679 .legalFor(ST.hasStdExtZfhmin(), {f16})
680 .lowerFor({f32, f64, f128, LLT::bfloat16()});
681
682 getActionDefinitionsBuilder({G_FPTOSI, G_FPTOUI})
683 .legalFor(ST.hasStdExtF(), {{sXLen, f32}})
684 .legalFor(ST.hasStdExtD(), {{sXLen, f64}})
685 .legalFor(ST.hasStdExtZfh(), {{sXLen, f16}})
686 .customFor(ST.is64Bit() && ST.hasStdExtF(), {{s32, f32}})
687 .customFor(ST.is64Bit() && ST.hasStdExtD(), {{s32, f64}})
688 .customFor(ST.is64Bit() && ST.hasStdExtZfh(), {{s32, f16}})
689 .widenScalarToNextPow2(0)
690 .minScalar(0, s32)
691 // The magnitude of a half is at most 65504, so with Zfh use fcvt.w[u].h
692 // and extend the i32 result. Otherwise promote the half source to float
693 // (via fcvt.s.h with Zfhmin, __extendhfsf2 without) and use the float
694 // conversion. On RV32, exclude i64 results here so that they get
695 // narrowed to i32 first.
696 .widenScalarIf(
697 [=, &ST](const LegalityQuery &Query) {
698 return Query.Types[1] == f16 && !ST.hasStdExtZfh() &&
699 (ST.is64Bit() || Query.Types[0].isScalar(32));
700 },
701 changeTo(1, f32))
702 .libcallFor(!ST.hasStdExtZfhmin(), {{s64, f16}})
703 .narrowScalarFor({{s64, f16}}, changeTo(0, s32))
704 .libcallFor({{s32, f32}, {s64, f32}, {s32, f64}, {s64, f64}})
705 .libcallFor(ST.is64Bit(), {{s32, f128}, {s64, f128}}) // FIXME RV32.
706 .libcallFor(ST.is64Bit(), {{s128, f32}, {s128, f64}, {s128, f128}});
707
708 // Unlike G_FPTOSI/G_FPTOUI these need no libcalls for out-of-range values:
709 // the RISC-V conversions already saturate. There is no legalFor() because
710 // they do not produce 0 for NaN, which legalizeCustom fixes up with a
711 // compare and a select. The remaining cases fall back to the generic
712 // lowering, which clamps before converting and only handles scalars.
713 getActionDefinitionsBuilder({G_FPTOSI_SAT, G_FPTOUI_SAT})
714 .customFor(ST.hasStdExtF(), {{sXLen, f32}})
715 .customFor(ST.hasStdExtD(), {{sXLen, f64}})
716 .customFor(ST.hasStdExtZfh(), {{sXLen, f16}})
717 .customFor(ST.is64Bit() && ST.hasStdExtF(), {{s32, f32}})
718 .customFor(ST.is64Bit() && ST.hasStdExtD(), {{s32, f64}})
719 .customFor(ST.is64Bit() && ST.hasStdExtZfh(), {{s32, f16}})
720 // f16 extends exactly to f32; converting via f32 avoids needing rules
721 // for every {sXX, f16} combination.
722 .widenScalarIf(typeIs(1, f16), changeTo(1, f32))
723 .lowerIf(all(isScalar(0), isScalar(1)));
724
725 getActionDefinitionsBuilder({G_LROUND, G_LLROUND})
726 .legalFor(ST.hasStdExtF(), {{sXLen, f32}})
727 .legalFor(ST.hasStdExtD(), {{sXLen, f64}})
728 .legalFor(ST.hasStdExtZfh(), {{sXLen, f16}})
729 .customFor(ST.is64Bit() && ST.hasStdExtF(), {{s32, f32}})
730 .customFor(ST.is64Bit() && ST.hasStdExtD(), {{s32, f64}})
731 .customFor(ST.is64Bit() && ST.hasStdExtZfh(), {{s32, f16}})
732 .minScalar(1, f32)
733 .libcallFor({{s32, f32},
734 {s64, f32},
735 {s32, f64},
736 {s64, f64},
737 {s32, f128},
738 {s64, f128}});
739
740 getActionDefinitionsBuilder({G_INTRINSIC_LRINT, G_INTRINSIC_LLRINT})
741 .legalFor(ST.hasStdExtF(), {{sXLen, f32}})
742 .legalFor(ST.hasStdExtD(), {{sXLen, f64}})
743 .legalFor(ST.hasStdExtZfh(), {{sXLen, f16}})
744 .minScalar(0, sXLen)
745 .minScalar(1, f32)
746 .libcallFor({{s32, f32},
747 {s64, f32},
748 {s32, f64},
749 {s64, f64},
750 {s32, f128},
751 {s64, f128}});
752
753 getActionDefinitionsBuilder({G_SITOFP, G_UITOFP})
754 .legalFor(ST.hasStdExtF(), {{f32, sXLen}})
755 .legalFor(ST.hasStdExtD(), {{f64, sXLen}})
756 .legalFor(ST.hasStdExtZfh(), {{f16, sXLen}})
757 .widenScalarToNextPow2(1)
758 // Promote to XLen if the operation is legal.
759 .widenScalarIf(
760 [=, &ST](const LegalityQuery &Query) {
761 return Query.Types[0].isScalar() && Query.Types[1].isScalar() &&
762 (Query.Types[1].getSizeInBits() < ST.getXLen()) &&
763 ((ST.hasStdExtF() && Query.Types[0].getSizeInBits() == 32) ||
764 (ST.hasStdExtD() && Query.Types[0].getSizeInBits() == 64) ||
765 (ST.hasStdExtZfh() &&
766 Query.Types[0].getSizeInBits() == 16));
767 },
769 // Otherwise only promote to s32 since we have si libcalls.
770 .minScalar(1, s32)
771 .libcallFor({{f32, s32}, {f64, s32}, {f32, s64}, {f64, s64}})
772 .libcallFor(ST.is64Bit(), {{f128, s32}, {f128, s64}}) // FIXME RV32.
773 .libcallFor(ST.is64Bit(), {{f32, s128}, {f64, s128}, {f128, s128}});
774
775 // Without Zfa, round by converting to an integer and back, like
776 // SelectionDAG does.
777 getActionDefinitionsBuilder({G_FCEIL, G_FFLOOR, G_FRINT, G_INTRINSIC_TRUNC,
778 G_INTRINSIC_ROUND, G_INTRINSIC_ROUNDEVEN})
779 .legalFor(ST.hasStdExtZfa(), {f32})
780 .legalFor(ST.hasStdExtZfa() && ST.hasStdExtD(), {f64})
781 .legalFor(ST.hasStdExtZfa() && ST.hasStdExtZfh(), {f16})
782 .customFor(ST.hasStdExtZfh(), {f16})
783 // Without Zfh there is no fcvt.w.h, so round in f32, which f16 extends
784 // to exactly.
785 .widenScalarIf(typeIs(0, f16), changeTo(0, f32))
786 .customFor(ST.hasStdExtF(), {f32})
787 // Rounding an f64 needs an integer that can hold every value below 2^52.
788 .customFor(ST.is64Bit() && ST.hasStdExtD(), {f64})
789 .libcallFor({f32, f64})
790 .libcallFor(ST.is64Bit(), {f128});
791
792 // G_FNEARBYINT must not raise the inexact exception, which the integer round
793 // trip does, so without Zfa it has to stay a libcall.
794 getActionDefinitionsBuilder(G_FNEARBYINT)
795 .legalFor(ST.hasStdExtZfa(), {f32})
796 .legalFor(ST.hasStdExtZfa() && ST.hasStdExtD(), {f64})
797 .legalFor(ST.hasStdExtZfa() && ST.hasStdExtZfh(), {f16})
798 .widenScalarIf(typeIs(0, f16), changeTo(0, f32))
799 .libcallFor({f32, f64})
800 .libcallFor(ST.is64Bit(), {f128});
801
802 getActionDefinitionsBuilder({G_FMAXIMUM, G_FMINIMUM})
803 .legalFor(ST.hasStdExtZfa(), {f32})
804 .legalFor(ST.hasStdExtZfa() && ST.hasStdExtD(), {f64})
805 .legalFor(ST.hasStdExtZfa() && ST.hasStdExtZfh(), {f16});
806
807 getActionDefinitionsBuilder({G_FCOS, G_FSIN, G_FTAN, G_FPOW, G_FLOG, G_FLOG2,
808 G_FLOG10, G_FEXP, G_FEXP2, G_FEXP10, G_FACOS,
809 G_FASIN, G_FATAN, G_FATAN2, G_FCOSH, G_FSINH,
810 G_FTANH, G_FMODF, G_FSINCOS})
811 .libcallFor({f32, f64})
812 .libcallFor(ST.is64Bit(), {f128});
813 getActionDefinitionsBuilder({G_FPOWI, G_FLDEXP})
814 .libcallFor({{f32, s32}, {f64, s32}})
815 .libcallFor(ST.is64Bit(), {f128, s32});
816
817 getActionDefinitionsBuilder(G_FCANONICALIZE)
818 .legalFor(ST.hasStdExtF(), {f32})
819 .legalFor(ST.hasStdExtD(), {f64})
820 .legalFor(ST.hasStdExtZfh(), {f16});
821
822 getActionDefinitionsBuilder(G_VASTART).customFor({p0});
823
824 // va_list must be a pointer, but most sized types are pretty easy to handle
825 // as the destination.
826 getActionDefinitionsBuilder(G_VAARG)
827 // TODO: Implement narrowScalar and widenScalar for G_VAARG for types
828 // other than sXLen.
829 .clampScalar(0, sXLen, sXLen)
830 .lowerForCartesianProduct({sXLen, p0}, {p0});
831
832 getActionDefinitionsBuilder(G_VSCALE)
833 .clampScalar(0, sXLen, sXLen)
834 .customFor({sXLen});
835
836 auto &SplatActions =
837 getActionDefinitionsBuilder(G_SPLAT_VECTOR)
838 .legalIf(all(typeIsLegalIntOrFPVec(0, IntOrFPVecTys, ST),
839 typeIs(1, sXLen)));
840 // Handle case of s64 element vectors on RV32. If the subtarget does not have
841 // f64, then try to lower it to G_SPLAT_VECTOR_SPLIT_64_VL. If the subtarget
842 // does have f64, then we don't know whether the type is an f64 or an i64,
843 // so mark the G_SPLAT_VECTOR as legal and decide later what to do with it,
844 // depending on how the instructions it consumes are legalized. They are not
845 // legalized yet since legalization is in reverse postorder, so we cannot
846 // make the decision at this moment.
847 if (XLen == 32) {
848 if (ST.hasVInstructionsF64() && ST.hasStdExtD())
849 SplatActions.legalIf(all(
850 typeInSet(0, {nxv1s64, nxv2s64, nxv4s64, nxv8s64}), typeIs(1, s64)));
851 else if (ST.hasVInstructionsI64())
852 SplatActions.customIf(all(
853 typeInSet(0, {nxv1s64, nxv2s64, nxv4s64, nxv8s64}), typeIs(1, s64)));
854 }
855 SplatActions.customIf(
856 all(typeIsLegalBoolVec(0, BoolVecTys, ST), typeIs(1, s1)));
857
858 SplatActions.clampScalar(1, sXLen, sXLen);
859
860 LegalityPredicate ExtractSubvecBitcastPred = [=](const LegalityQuery &Query) {
861 LLT DstTy = Query.Types[0];
862 LLT SrcTy = Query.Types[1];
863 return DstTy.getElementType() == LLT::scalar(1) &&
864 DstTy.getElementCount().getKnownMinValue() >= 8 &&
865 SrcTy.getElementCount().getKnownMinValue() >= 8;
866 };
867 getActionDefinitionsBuilder(G_EXTRACT_SUBVECTOR)
868 // We don't have the ability to slide mask vectors down indexed by their
869 // i1 elements; the smallest we can do is i8. Often we are able to bitcast
870 // to equivalent i8 vectors.
871 .bitcastIf(all(typeIsLegalBoolVec(0, BoolVecTys, ST),
872 typeIsLegalBoolVec(1, BoolVecTys, ST),
873 ExtractSubvecBitcastPred),
874 [=](const LegalityQuery &Query) {
875 LLT CastTy = LLT::vector(
876 Query.Types[0].getElementCount().divideCoefficientBy(8),
877 LLT::integer(8));
878 return std::pair(0, CastTy);
879 })
880 .customIf(LegalityPredicates::any(
881 all(typeIsLegalBoolVec(0, BoolVecTys, ST),
882 typeIsLegalBoolVec(1, BoolVecTys, ST)),
883 all(typeIsLegalIntOrFPVec(0, IntOrFPVecTys, ST),
884 typeIsLegalIntOrFPVec(1, IntOrFPVecTys, ST))));
885
886 getActionDefinitionsBuilder(G_INSERT_SUBVECTOR)
887 .customIf(all(typeIsLegalBoolVec(0, BoolVecTys, ST),
888 typeIsLegalBoolVec(1, BoolVecTys, ST)))
889 .customIf(all(typeIsLegalIntOrFPVec(0, IntOrFPVecTys, ST),
890 typeIsLegalIntOrFPVec(1, IntOrFPVecTys, ST)));
891
892 getActionDefinitionsBuilder(G_ATOMIC_CMPXCHG_WITH_SUCCESS)
893 .lowerIf(all(typeInSet(0, {s8, s16, s32, s64}), typeIs(2, p0)));
894
895 getActionDefinitionsBuilder({G_ATOMIC_CMPXCHG, G_ATOMICRMW_ADD,
896 G_ATOMICRMW_XCHG, G_ATOMICRMW_AND,
897 G_ATOMICRMW_OR, G_ATOMICRMW_XOR})
898 .legalFor(ST.hasStdExtZalrsc(), {{sXLen, p0}})
899 .libcallFor(!ST.hasStdExtZalrsc(),
900 {{s8, p0}, {s16, p0}, {s32, p0}, {s64, p0}})
901 .clampScalar(0, sXLen, sXLen);
902
903 getActionDefinitionsBuilder(G_ATOMICRMW_SUB)
904 .libcallFor(!ST.hasStdExtZalrsc(),
905 {{s8, p0}, {s16, p0}, {s32, p0}, {s64, p0}})
906 .clampScalar(0, sXLen, sXLen)
907 .lower();
908
909 getActionDefinitionsBuilder(
910 {G_ATOMICRMW_MAX, G_ATOMICRMW_MIN, G_ATOMICRMW_UMAX, G_ATOMICRMW_UMIN})
911 .legalFor(ST.hasStdExtZalrsc(), {{sXLen, p0}})
912 .clampScalar(0, sXLen, sXLen)
913 .unsupported();
914
915 getActionDefinitionsBuilder(G_PREFETCH).legalIf(typeIs(0, p0));
916
917 LegalityPredicate InsertVectorEltPred = [=](const LegalityQuery &Query) {
918 LLT VecTy = Query.Types[0];
919 LLT EltTy = Query.Types[1];
920 return VecTy.getElementType() == EltTy;
921 };
922
923 getActionDefinitionsBuilder(G_INSERT_VECTOR_ELT)
924 .legalIf(all(typeIsLegalIntOrFPVec(0, IntOrFPVecTys, ST),
925 InsertVectorEltPred, typeIs(2, sXLen)))
926 .legalIf(all(typeIsLegalBoolVec(0, BoolVecTys, ST), InsertVectorEltPred,
927 typeIs(2, sXLen)));
928
929 getActionDefinitionsBuilder({G_INTRINSIC, G_INTRINSIC_W_SIDE_EFFECTS})
930 .alwaysLegal();
931
932 getActionDefinitionsBuilder(G_FENCE).alwaysLegal();
933
934 getActionDefinitionsBuilder({G_TRAP, G_DEBUGTRAP, G_UBSANTRAP}).alwaysLegal();
935
936 verify(*ST.getInstrInfo());
937}
938
940 MachineInstr &MI) const {
941 Intrinsic::ID IntrinsicID = cast<GIntrinsic>(MI).getIntrinsicID();
942
944 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntrinsicID)) {
945 if (II->hasScalarOperand() && !II->IsFPIntrinsic) {
946 MachineIRBuilder &MIRBuilder = Helper.MIRBuilder;
947 MachineRegisterInfo &MRI = *MIRBuilder.getMRI();
948
949 auto OldScalar = MI.getOperand(II->ScalarOperand + 2).getReg();
950 // Legalize integer vx form intrinsic.
951 if (MRI.getType(OldScalar).isScalar()) {
952 if (MRI.getType(OldScalar).getSizeInBits() < iXLen.getSizeInBits()) {
953 Helper.Observer.changingInstr(MI);
954 Helper.widenScalarSrc(MI, iXLen, II->ScalarOperand + 2,
955 TargetOpcode::G_ANYEXT);
956 Helper.Observer.changedInstr(MI);
957 } else if (MRI.getType(OldScalar).getSizeInBits() >
958 iXLen.getSizeInBits()) {
959 // TODO: i64 in riscv32.
960 return false;
961 }
962 }
963 }
964 return true;
965 }
966
967 switch (IntrinsicID) {
968 default:
969 return false;
970 case Intrinsic::riscv_orc_b: {
971 if (!STI.hasStdExtZbb())
972 return false;
973
974 MachineIRBuilder &MIRBuilder = Helper.MIRBuilder;
975 MachineRegisterInfo &MRI = *MIRBuilder.getMRI();
976 LLT Ty = MRI.getType(MI.getOperand(0).getReg());
977 if (Ty != iXLen && (!STI.is64Bit() || Ty != LLT::scalar(32)))
978 return false;
979
980 // Each output byte depends only on the corresponding input byte, so any
981 // extension is fine for narrow types.
982 Register Src = MI.getOperand(2).getReg();
983 if (Ty != iXLen)
984 Src = MIRBuilder.buildAnyExt(iXLen, Src).getReg(0);
985 auto Result = MIRBuilder.buildInstr(RISCV::G_ORC_B, {iXLen}, {Src});
986 if (Ty != iXLen)
987 MIRBuilder.buildTrunc(MI.getOperand(0), Result);
988 else
989 MIRBuilder.buildCopy(MI.getOperand(0), Result);
990 MI.eraseFromParent();
991 return true;
992 }
993 case Intrinsic::riscv_clmulh:
994 Helper.MIRBuilder.buildInstr(TargetOpcode::G_CLMULH, {MI.getOperand(0)},
995 {MI.getOperand(2), MI.getOperand(3)});
996 MI.eraseFromParent();
997 return true;
998 case Intrinsic::riscv_clmulr:
999 Helper.MIRBuilder.buildInstr(TargetOpcode::G_CLMULR, {MI.getOperand(0)},
1000 {MI.getOperand(2), MI.getOperand(3)});
1001 MI.eraseFromParent();
1002 return true;
1003 case Intrinsic::vacopy: {
1004 // vacopy arguments must be legal because of the intrinsic signature.
1005 // No need to check here.
1006
1007 MachineIRBuilder &MIRBuilder = Helper.MIRBuilder;
1008 MachineRegisterInfo &MRI = *MIRBuilder.getMRI();
1009 MachineFunction &MF = *MI.getMF();
1010 const DataLayout &DL = MIRBuilder.getDataLayout();
1011 LLVMContext &Ctx = MF.getFunction().getContext();
1012
1013 Register DstLst = MI.getOperand(1).getReg();
1014 LLT PtrTy = MRI.getType(DstLst);
1015
1016 // Load the source va_list
1017 Align Alignment = DL.getABITypeAlign(getTypeForLLT(PtrTy, Ctx));
1019 MachinePointerInfo(), MachineMemOperand::MOLoad, PtrTy, Alignment);
1020 auto Tmp = MIRBuilder.buildLoad(PtrTy, MI.getOperand(2), *LoadMMO);
1021
1022 // Store the result in the destination va_list
1024 MachinePointerInfo(), MachineMemOperand::MOStore, PtrTy, Alignment);
1025 MIRBuilder.buildStore(Tmp, DstLst, *StoreMMO);
1026
1027 MI.eraseFromParent();
1028 return true;
1029 }
1030 case Intrinsic::riscv_vsetvli:
1031 case Intrinsic::riscv_vsetvlimax:
1032 case Intrinsic::riscv_masked_atomicrmw_add:
1033 case Intrinsic::riscv_masked_atomicrmw_sub:
1034 case Intrinsic::riscv_masked_atomicrmw_xchg:
1035 case Intrinsic::riscv_masked_atomicrmw_max:
1036 case Intrinsic::riscv_masked_atomicrmw_min:
1037 case Intrinsic::riscv_masked_atomicrmw_umax:
1038 case Intrinsic::riscv_masked_atomicrmw_umin:
1039 case Intrinsic::riscv_masked_cmpxchg:
1040 return true;
1041 }
1042}
1043
1044bool RISCVLegalizerInfo::legalizeVAStart(MachineInstr &MI,
1045 MachineIRBuilder &MIRBuilder) const {
1046 // Stores the address of the VarArgsFrameIndex slot into the memory location
1047 assert(MI.getOpcode() == TargetOpcode::G_VASTART);
1048 MachineFunction *MF = MI.getParent()->getParent();
1050 int FI = FuncInfo->getVarArgsFrameIndex();
1051 LLT AddrTy = MIRBuilder.getMRI()->getType(MI.getOperand(0).getReg());
1052 auto FINAddr = MIRBuilder.buildFrameIndex(AddrTy, FI);
1053 assert(MI.hasOneMemOperand());
1054 MIRBuilder.buildStore(FINAddr, MI.getOperand(0).getReg(),
1055 *MI.memoperands()[0]);
1056 MI.eraseFromParent();
1057 return true;
1058}
1059
1060bool RISCVLegalizerInfo::legalizeReadCounter(
1061 MachineInstr &MI, MachineIRBuilder &MIRBuilder,
1062 GISelChangeObserver &Observer) const {
1063 assert((MI.getOpcode() == TargetOpcode::G_READCYCLECOUNTER ||
1064 MI.getOpcode() == TargetOpcode::G_READSTEADYCOUNTER) &&
1065 "Unexpected opcode");
1066 assert(!STI.is64Bit() && "READCYCLECOUNTER/READSTEADYCOUNTER only "
1067 "has custom type legalization on riscv32");
1068
1069 // On RV32 a 64-bit counter CSR must be read as two 32-bit halves. Because
1070 // the count may wrap between the two reads, re-read the high half and loop
1071 // until the two high reads agree.
1072 int64_t LoCounter, HiCounter;
1073 if (MI.getOpcode() == TargetOpcode::G_READCYCLECOUNTER) {
1074 LoCounter = RISCVSysReg::cycle;
1075 HiCounter = RISCVSysReg::cycleh;
1076 } else {
1077 LoCounter = RISCVSysReg::time;
1078 HiCounter = RISCVSysReg::timeh;
1079 }
1080
1081 MachineBasicBlock *BB = MI.getParent();
1082 MachineFunction &MF = *BB->getParent();
1083 const BasicBlock *LLVMBB = BB->getBasicBlock();
1084 DebugLoc DL = MI.getDebugLoc();
1085 MachineRegisterInfo &MRI = *MIRBuilder.getMRI();
1086
1087 // Split BB into an entry that falls through into a loop block, and a done
1088 // block that receives the remainder of BB and its original successors.
1089 MachineFunction::iterator It = std::next(BB->getIterator());
1090 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVMBB);
1091 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVMBB);
1092 MF.insert(It, LoopMBB);
1093 MF.insert(It, DoneMBB);
1094
1095 // Splice the instructions after the readcyclecounter into DoneMBB, notifying
1096 // the observer about each moved instruction so CSEInfo stays consistent.
1097 for (MachineBasicBlock::iterator I = std::next(MI.getIterator()),
1098 E = BB->end();
1099 I != E; ++I)
1100 Observer.changingInstr(*I);
1101 DoneMBB->splice(DoneMBB->begin(), BB,
1102 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1103 for (MachineInstr &MovedMI : DoneMBB->instrs())
1104 Observer.changedInstr(MovedMI);
1106 BB->addSuccessor(LoopMBB);
1107
1108 LLT i32 = LLT::integer(32);
1109 // Generic vregs carry the s32 type for G_MERGE_VALUES below, but are also
1110 // constrained to GPR so the target CSRRS/BNE instructions satisfy the
1111 // verifier's register-class constraints.
1112 auto CreateGPR = [&]() {
1114 MRI.setRegClass(R, &RISCV::GPRRegClass);
1115 return R;
1116 };
1117 Register LoReg = CreateGPR();
1118 Register HiReg = CreateGPR();
1119 Register ReadAgainReg = CreateGPR();
1120
1121 // read:
1122 // csrrs HiReg, counterh # high word
1123 // csrrs LoReg, counter # low word
1124 // csrrs ReadAgainReg, counterh
1125 // bne HiReg, ReadAgainReg, read
1126 // Emit the target instructions directly with BuildMI.
1127 const RISCVInstrInfo *TII = STI.getInstrInfo();
1128 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
1129 .addImm(HiCounter)
1130 .addReg(RISCV::X0);
1131 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
1132 .addImm(LoCounter)
1133 .addReg(RISCV::X0);
1134 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
1135 .addImm(HiCounter)
1136 .addReg(RISCV::X0);
1137
1138 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
1139 .addReg(HiReg)
1140 .addReg(ReadAgainReg)
1141 .addMBB(LoopMBB);
1142
1143 LoopMBB->addSuccessor(LoopMBB);
1144 LoopMBB->addSuccessor(DoneMBB);
1145
1146 // Re-pair the two halves into the 64-bit result.
1147 Register DstReg = MI.getOperand(0).getReg();
1148 Observer.erasingInstr(MI);
1149 MI.eraseFromParent();
1150
1151 MIRBuilder.setInsertPt(*DoneMBB, DoneMBB->begin());
1152 MIRBuilder.setDebugLoc(DL);
1153 MIRBuilder.buildMergeValues(DstReg, {LoReg, HiReg});
1154 return true;
1155}
1156
1157bool RISCVLegalizerInfo::legalizeBRJT(MachineInstr &MI,
1158 MachineIRBuilder &MIRBuilder) const {
1159 MachineRegisterInfo &MRI = *MIRBuilder.getMRI();
1160 auto &MF = *MI.getParent()->getParent();
1161 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1162 unsigned EntrySize = MJTI->getEntrySize(MF.getDataLayout());
1163
1164 Register PtrReg = MI.getOperand(0).getReg();
1165 LLT PtrTy = MRI.getType(PtrReg);
1166 Register IndexReg = MI.getOperand(2).getReg();
1167 LLT IndexTy = MRI.getType(IndexReg);
1168
1169 if (!isPowerOf2_32(EntrySize))
1170 return false;
1171
1172 auto ShiftAmt = MIRBuilder.buildConstant(IndexTy, Log2_32(EntrySize));
1173 IndexReg = MIRBuilder.buildShl(IndexTy, IndexReg, ShiftAmt).getReg(0);
1174
1175 auto Addr = MIRBuilder.buildPtrAdd(PtrTy, PtrReg, IndexReg);
1176
1177 MachineMemOperand *MMO = MF.getMachineMemOperand(
1179 EntrySize, Align(MJTI->getEntryAlignment(MF.getDataLayout())));
1180
1181 Register TargetReg;
1182 switch (MJTI->getEntryKind()) {
1183 default:
1184 return false;
1186 // For PIC, the sequence is:
1187 // BRIND(load(Jumptable + index) + RelocBase)
1188 // RelocBase can be JumpTable, GOT or some sort of global base.
1189 unsigned LoadOpc =
1190 STI.is64Bit() ? TargetOpcode::G_SEXTLOAD : TargetOpcode::G_LOAD;
1191 auto Load = MIRBuilder.buildLoadInstr(LoadOpc, IndexTy, Addr, *MMO);
1192 TargetReg = MIRBuilder.buildPtrAdd(PtrTy, PtrReg, Load).getReg(0);
1193 break;
1194 }
1196 auto Load = MIRBuilder.buildLoadInstr(TargetOpcode::G_SEXTLOAD, IndexTy,
1197 Addr, *MMO);
1198 TargetReg = MIRBuilder.buildIntToPtr(PtrTy, Load).getReg(0);
1199 break;
1200 }
1202 TargetReg = MIRBuilder.buildLoad(PtrTy, Addr, *MMO).getReg(0);
1203 break;
1204 }
1205
1206 if (MF.getInfo<RISCVMachineFunctionInfo>()->hasCFProtectionBranch()) {
1207 // When cf-protection-branch is enabled, we need to use a software
1208 // guarded branch for jump table branch.
1209 MIRBuilder.buildInstr(RISCV::G_SW_GUARDED_BRIND, {}, {TargetReg});
1210 } else {
1211 MIRBuilder.buildBrIndirect(TargetReg);
1212 }
1213
1214 MI.eraseFromParent();
1215 return true;
1216}
1217
1218bool RISCVLegalizerInfo::shouldBeInConstantPool(const APInt &APImm,
1219 bool ShouldOptForSize) const {
1220 assert(APImm.getBitWidth() == 32 || APImm.getBitWidth() == 64);
1221 int64_t Imm = APImm.getSExtValue();
1222 // All simm32 constants should be handled by isel.
1223 // NOTE: The getMaxBuildIntsCost call below should return a value >= 2 making
1224 // this check redundant, but small immediates are common so this check
1225 // should have better compile time.
1226 if (isInt<32>(Imm))
1227 return false;
1228
1229 // We only need to cost the immediate, if constant pool lowering is enabled.
1230 if (!STI.useConstantPoolForLargeInts())
1231 return false;
1232
1234 if (Seq.size() <= STI.getMaxBuildIntsCost())
1235 return false;
1236
1237 // Optimizations below are disabled for opt size. If we're optimizing for
1238 // size, use a constant pool.
1239 if (ShouldOptForSize)
1240 return true;
1241 //
1242 // Special case. See if we can build the constant as (ADD (SLLI X, C), X) do
1243 // that if it will avoid a constant pool.
1244 // It will require an extra temporary register though.
1245 // If we have Zba we can use (ADD_UW X, (SLLI X, 32)) to handle cases where
1246 // low and high 32 bits are the same and bit 31 and 63 are set.
1247 unsigned ShiftAmt, AddOpc;
1248 RISCVMatInt::InstSeq SeqLo =
1249 RISCVMatInt::generateTwoRegInstSeq(Imm, STI, ShiftAmt, AddOpc);
1250 return !(!SeqLo.empty() && (SeqLo.size() + 2) <= STI.getMaxBuildIntsCost());
1251}
1252
1253bool RISCVLegalizerInfo::legalizeVScale(MachineInstr &MI,
1254 MachineIRBuilder &MIB) const {
1255 Register Dst = MI.getOperand(0).getReg();
1256
1257 // We define our scalable vector types for lmul=1 to use a 64 bit known
1258 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
1259 // vscale as VLENB / 8.
1260 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
1261 if (STI.getRealMinVLen() < RISCV::RVVBitsPerBlock)
1262 // Support for VLEN==32 is incomplete.
1263 return false;
1264
1265 // We assume VLENB is a multiple of 8. We manually choose the best shift
1266 // here because SimplifyDemandedBits isn't always able to simplify it.
1267 uint64_t Val = MI.getOperand(1).getCImm()->getZExtValue();
1268 if (isPowerOf2_64(Val)) {
1269 uint64_t Log2 = Log2_64(Val);
1270 if (Log2 < 3) {
1271 auto VLENB = MIB.buildInstr(RISCV::G_READ_VLENB, {iXLen}, {});
1272 MIB.buildLShr(Dst, VLENB, MIB.buildConstant(iXLen, 3 - Log2),
1274 } else if (Log2 > 3) {
1275 auto VLENB = MIB.buildInstr(RISCV::G_READ_VLENB, {iXLen}, {});
1276 MIB.buildShl(Dst, VLENB, MIB.buildConstant(iXLen, Log2 - 3));
1277 } else {
1278 MIB.buildInstr(RISCV::G_READ_VLENB, {Dst}, {});
1279 }
1280 } else if ((Val % 8) == 0) {
1281 // If the multiplier is a multiple of 8, scale it down to avoid needing
1282 // to shift the VLENB value.
1283 auto VLENB = MIB.buildInstr(RISCV::G_READ_VLENB, {iXLen}, {});
1284 MIB.buildMul(Dst, VLENB, MIB.buildConstant(iXLen, Val / 8));
1285 } else {
1286 auto VLENB = MIB.buildInstr(RISCV::G_READ_VLENB, {iXLen}, {});
1287 auto VScale = MIB.buildLShr(iXLen, VLENB, MIB.buildConstant(iXLen, 3),
1289 MIB.buildMul(Dst, VScale, MIB.buildConstant(iXLen, Val));
1290 }
1291 MI.eraseFromParent();
1292 return true;
1293}
1294
1295// Custom-lower extensions from mask vectors by using a vselect either with 1
1296// for zero/any-extension or -1 for sign-extension:
1297// (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
1298// Note that any-extension is lowered identically to zero-extension.
1299bool RISCVLegalizerInfo::legalizeExt(MachineInstr &MI,
1300 MachineIRBuilder &MIB) const {
1301
1302 unsigned Opc = MI.getOpcode();
1303 assert(Opc == TargetOpcode::G_ZEXT || Opc == TargetOpcode::G_SEXT ||
1304 Opc == TargetOpcode::G_ANYEXT);
1305
1306 MachineRegisterInfo &MRI = *MIB.getMRI();
1307 Register Dst = MI.getOperand(0).getReg();
1308 Register Src = MI.getOperand(1).getReg();
1309
1310 LLT DstTy = MRI.getType(Dst);
1311 int64_t ExtTrueVal = Opc == TargetOpcode::G_SEXT ? -1 : 1;
1312 LLT DstEltTy = DstTy.getElementType();
1313 auto SplatZero = MIB.buildSplatVector(DstTy, MIB.buildConstant(DstEltTy, 0));
1314 auto SplatTrue =
1315 MIB.buildSplatVector(DstTy, MIB.buildConstant(DstEltTy, ExtTrueVal));
1316 MIB.buildSelect(Dst, Src, SplatTrue, SplatZero);
1317
1318 MI.eraseFromParent();
1319 return true;
1320}
1321
1322bool RISCVLegalizerInfo::legalizeLoadStore(MachineInstr &MI,
1323 LegalizerHelper &Helper,
1324 MachineIRBuilder &MIB) const {
1326 "Machine instructions must be Load/Store.");
1327 MachineRegisterInfo &MRI = *MIB.getMRI();
1328 MachineFunction *MF = MI.getMF();
1329 const DataLayout &DL = MIB.getDataLayout();
1330 LLVMContext &Ctx = MF->getFunction().getContext();
1331
1332 Register DstReg = MI.getOperand(0).getReg();
1333 LLT DataTy = MRI.getType(DstReg);
1334 if (!DataTy.isVector())
1335 return false;
1336
1337 if (!MI.hasOneMemOperand())
1338 return false;
1339
1340 MachineMemOperand *MMO = *MI.memoperands_begin();
1341
1342 const auto *TLI = STI.getTargetLowering();
1343 EVT VT = EVT::getEVT(getTypeForLLT(DataTy, Ctx));
1344
1345 if (TLI->allowsMemoryAccessForAlignment(Ctx, DL, VT, *MMO))
1346 return true;
1347
1348 unsigned EltSizeBits = DataTy.getScalarSizeInBits();
1349 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
1350 "Unexpected unaligned RVV load type");
1351
1352 // Calculate the new vector type with i8 elements
1353 unsigned NumElements =
1354 DataTy.getElementCount().getKnownMinValue() * (EltSizeBits / 8);
1355 LLT NewDataTy = LLT::scalable_vector(NumElements, LLT::integer(8));
1356
1357 Helper.bitcast(MI, 0, NewDataTy);
1358
1359 return true;
1360}
1361
1362/// Return the type of the mask type suitable for masking the provided
1363/// vector type. This is simply an i1 element type vector of the same
1364/// (possibly scalable) length.
1365static LLT getMaskTypeFor(LLT VecTy) {
1366 assert(VecTy.isVector());
1367 ElementCount EC = VecTy.getElementCount();
1368 return LLT::vector(EC, LLT::integer(1));
1369}
1370
1371/// Creates an all ones mask suitable for masking a vector of type VecTy with
1372/// vector length VL.
1374 MachineIRBuilder &MIB,
1376 LLT MaskTy = getMaskTypeFor(VecTy);
1377 return MIB.buildInstr(RISCV::G_VMSET_VL, {MaskTy}, {VL});
1378}
1379
1380/// Gets the two common "VL" operands: an all-ones mask and the vector length.
1381/// VecTy is a scalable vector type.
1382static std::pair<MachineInstrBuilder, MachineInstrBuilder>
1384 assert(VecTy.isScalableVector() && "Expecting scalable container type");
1385 const RISCVSubtarget &STI = MIB.getMF().getSubtarget<RISCVSubtarget>();
1386 LLT XLenTy(STI.getXLenVT());
1387 auto VL = MIB.buildConstant(XLenTy, -1);
1388 auto Mask = buildAllOnesMask(VecTy, VL, MIB, MRI);
1389 return {Mask, VL};
1390}
1391
1393buildSplatPartsS64WithVL(const DstOp &Dst, const SrcOp &Passthru, Register Lo,
1394 Register Hi, const SrcOp &VL, MachineIRBuilder &MIB,
1396 // TODO: If the Hi bits of the splat are undefined, then it's fine to just
1397 // splat Lo even if it might be sign extended. I don't think we have
1398 // introduced a case where we're build a s64 where the upper bits are undef
1399 // yet.
1400
1401 // Fall back to a stack store and stride x0 vector load.
1402 // TODO: need to lower G_SPLAT_VECTOR_SPLIT_I64. This is done in
1403 // preprocessDAG in SDAG.
1404 return MIB.buildInstr(RISCV::G_SPLAT_VECTOR_SPLIT_I64_VL, {Dst},
1405 {Passthru, Lo, Hi, VL});
1406}
1407
1409buildSplatSplitS64WithVL(const DstOp &Dst, const SrcOp &Passthru,
1410 const SrcOp &Scalar, const SrcOp &VL,
1412 assert(Scalar.getLLTTy(MRI) == LLT::scalar(64) && "Unexpected VecTy!");
1413 auto Unmerge = MIB.buildUnmerge(LLT::integer(32), Scalar);
1414 return buildSplatPartsS64WithVL(Dst, Passthru, Unmerge.getReg(0),
1415 Unmerge.getReg(1), VL, MIB, MRI);
1416}
1417
1418// Lower splats of s1 types to G_ICMP. For each mask vector type, we have a
1419// legal equivalently-sized i8 type, so we can use that as a go-between.
1420// Splats of s1 types that have constant value can be legalized as VMSET_VL or
1421// VMCLR_VL.
1422bool RISCVLegalizerInfo::legalizeSplatVector(MachineInstr &MI,
1423 MachineIRBuilder &MIB) const {
1424 assert(MI.getOpcode() == TargetOpcode::G_SPLAT_VECTOR);
1425
1426 MachineRegisterInfo &MRI = *MIB.getMRI();
1427
1428 Register Dst = MI.getOperand(0).getReg();
1429 Register SplatVal = MI.getOperand(1).getReg();
1430
1431 LLT VecTy = MRI.getType(Dst);
1432 LLT XLenTy(STI.getXLenVT());
1433
1434 // Handle case of s64 element vectors on rv32
1435 if (XLenTy.getSizeInBits() == 32 &&
1436 VecTy.getElementType().getSizeInBits() == 64) {
1437 auto [_, VL] = buildDefaultVLOps(MRI.getType(Dst), MIB, MRI);
1438 buildSplatSplitS64WithVL(Dst, MIB.buildUndef(VecTy), SplatVal, VL, MIB,
1439 MRI);
1440 MI.eraseFromParent();
1441 return true;
1442 }
1443
1444 // All-zeros or all-ones splats are handled specially.
1445 MachineInstr &SplatValMI = *MRI.getVRegDef(SplatVal);
1446 if (isAllOnesOrAllOnesSplat(SplatValMI, MRI)) {
1447 auto VL = buildDefaultVLOps(VecTy, MIB, MRI).second;
1448 MIB.buildInstr(RISCV::G_VMSET_VL, {Dst}, {VL});
1449 MI.eraseFromParent();
1450 return true;
1451 }
1452 if (isNullOrNullSplat(SplatValMI, MRI)) {
1453 auto VL = buildDefaultVLOps(VecTy, MIB, MRI).second;
1454 MIB.buildInstr(RISCV::G_VMCLR_VL, {Dst}, {VL});
1455 MI.eraseFromParent();
1456 return true;
1457 }
1458
1459 // Handle non-constant mask splat (i.e. not sure if it's all zeros or all
1460 // ones) by promoting it to an s8 splat.
1461 LLT InterEltTy = LLT::integer(8);
1462 LLT InterTy = VecTy.changeElementType(InterEltTy);
1463 auto ZExtSplatVal = MIB.buildZExt(InterEltTy, SplatVal);
1464 auto And =
1465 MIB.buildAnd(InterEltTy, ZExtSplatVal, MIB.buildConstant(InterEltTy, 1));
1466 auto LHS = MIB.buildSplatVector(InterTy, And);
1467 auto ZeroSplat =
1468 MIB.buildSplatVector(InterTy, MIB.buildConstant(InterEltTy, 0));
1469 MIB.buildICmp(CmpInst::Predicate::ICMP_NE, Dst, LHS, ZeroSplat);
1470 MI.eraseFromParent();
1471 return true;
1472}
1473
1474static LLT getLMUL1Ty(LLT VecTy) {
1475 assert(VecTy.getElementType().getSizeInBits() <= 64 &&
1476 "Unexpected vector LLT");
1478 VecTy.getElementType().getSizeInBits(),
1479 VecTy.getElementType());
1480}
1481
1482bool RISCVLegalizerInfo::legalizeExtractSubvector(MachineInstr &MI,
1483 MachineIRBuilder &MIB) const {
1484 GExtractSubvector &ES = cast<GExtractSubvector>(MI);
1485
1486 MachineRegisterInfo &MRI = *MIB.getMRI();
1487
1488 Register Dst = ES.getReg(0);
1489 Register Src = ES.getSrcVec();
1490 uint64_t Idx = ES.getIndexImm();
1491
1492 // With an index of 0 this is a cast-like subvector, which can be performed
1493 // with subregister operations.
1494 if (Idx == 0)
1495 return true;
1496
1497 LLT LitTy = MRI.getType(Dst);
1498 LLT BigTy = MRI.getType(Src);
1499
1500 if (LitTy.getElementType() == LLT::scalar(1)) {
1501 // We can't slide this mask vector up indexed by its i1 elements.
1502 // This poses a problem when we wish to insert a scalable vector which
1503 // can't be re-expressed as a larger type. Just choose the slow path and
1504 // extend to a larger type, then truncate back down.
1505 LLT ExtBigTy = BigTy.changeElementType(LLT::integer(8));
1506 LLT ExtLitTy = LitTy.changeElementType(LLT::integer(8));
1507 auto BigZExt = MIB.buildZExt(ExtBigTy, Src);
1508 auto ExtractZExt = MIB.buildExtractSubvector(ExtLitTy, BigZExt, Idx);
1509 auto SplatZero = MIB.buildSplatVector(
1510 ExtLitTy, MIB.buildConstant(ExtLitTy.getElementType(), 0));
1511 MIB.buildICmp(CmpInst::Predicate::ICMP_NE, Dst, ExtractZExt, SplatZero);
1512 MI.eraseFromParent();
1513 return true;
1514 }
1515
1516 // extract_subvector scales the index by vscale if the subvector is scalable,
1517 // and decomposeSubvectorInsertExtractToSubRegs takes this into account.
1518 const RISCVRegisterInfo *TRI = STI.getRegisterInfo();
1519 MVT LitTyMVT = getMVTForLLT(LitTy);
1520 auto Decompose =
1522 getMVTForLLT(BigTy), LitTyMVT, Idx, TRI);
1523 unsigned RemIdx = Decompose.second;
1524
1525 // If the Idx has been completely eliminated then this is a subvector extract
1526 // which naturally aligns to a vector register. These can easily be handled
1527 // using subregister manipulation.
1528 if (RemIdx == 0)
1529 return true;
1530
1531 // Else LitTy is M1 or smaller and may need to be slid down: if LitTy
1532 // was > M1 then the index would need to be a multiple of VLMAX, and so would
1533 // divide exactly.
1534 assert(
1537
1538 // If the vector type is an LMUL-group type, extract a subvector equal to the
1539 // nearest full vector register type.
1540 LLT InterLitTy = BigTy;
1541 Register Vec = Src;
1543 getLMUL1Ty(BigTy).getSizeInBits())) {
1544 // If BigTy has an LMUL > 1, then LitTy should have a smaller LMUL, and
1545 // we should have successfully decomposed the extract into a subregister.
1546 assert(Decompose.first != RISCV::NoSubRegister);
1547 InterLitTy = getLMUL1Ty(BigTy);
1548 // SDAG builds a TargetExtractSubreg. We cannot create a a Copy with SubReg
1549 // specified on the source Register (the equivalent) since generic virtual
1550 // register does not allow subregister index.
1551 Vec = MIB.buildExtractSubvector(InterLitTy, Src, Idx - RemIdx).getReg(0);
1552 }
1553
1554 // Slide this vector register down by the desired number of elements in order
1555 // to place the desired subvector starting at element 0.
1556 const LLT XLenTy(STI.getXLenVT());
1557 auto SlidedownAmt = MIB.buildVScale(XLenTy, RemIdx);
1558 auto [Mask, VL] = buildDefaultVLOps(InterLitTy, MIB, MRI);
1560 auto Slidedown = MIB.buildInstr(
1561 RISCV::G_VSLIDEDOWN_VL, {InterLitTy},
1562 {MIB.buildUndef(InterLitTy), Vec, SlidedownAmt, Mask, VL, Policy});
1563
1564 // Now the vector is in the right position, extract our final subvector. This
1565 // should resolve to a COPY.
1566 MIB.buildExtractSubvector(Dst, Slidedown, 0);
1567
1568 MI.eraseFromParent();
1569 return true;
1570}
1571
1572bool RISCVLegalizerInfo::legalizeInsertSubvector(MachineInstr &MI,
1573 LegalizerHelper &Helper,
1574 MachineIRBuilder &MIB) const {
1575 GInsertSubvector &IS = cast<GInsertSubvector>(MI);
1576
1577 MachineRegisterInfo &MRI = *MIB.getMRI();
1578
1579 Register Dst = IS.getReg(0);
1580 Register BigVec = IS.getBigVec();
1581 Register LitVec = IS.getSubVec();
1582 uint64_t Idx = IS.getIndexImm();
1583
1584 LLT BigTy = MRI.getType(BigVec);
1585 LLT LitTy = MRI.getType(LitVec);
1586
1587 if (Idx == 0 && mi_match(BigVec, MRI, m_GImplicitDef()))
1588 return true;
1589
1590 // We don't have the ability to slide mask vectors up indexed by their i1
1591 // elements; the smallest we can do is i8. Often we are able to bitcast to
1592 // equivalent i8 vectors. Otherwise, we can must zeroextend to equivalent i8
1593 // vectors and truncate down after the insert.
1594 if (LitTy.getElementType() == LLT::scalar(1)) {
1595 auto BigTyMinElts = BigTy.getElementCount().getKnownMinValue();
1596 auto LitTyMinElts = LitTy.getElementCount().getKnownMinValue();
1597 if (BigTyMinElts >= 8 && LitTyMinElts >= 8)
1598 return Helper.bitcast(
1599 IS, 0,
1601 LLT::integer(8)));
1602
1603 // We can't slide this mask vector up indexed by its i1 elements.
1604 // This poses a problem when we wish to insert a scalable vector which
1605 // can't be re-expressed as a larger type. Just choose the slow path and
1606 // extend to a larger type, then truncate back down.
1607 LLT ExtBigTy = BigTy.changeElementType(LLT::integer(8));
1608 return Helper.widenScalar(IS, 0, ExtBigTy);
1609 }
1610
1611 const RISCVRegisterInfo *TRI = STI.getRegisterInfo();
1612 unsigned SubRegIdx, RemIdx;
1613 std::tie(SubRegIdx, RemIdx) =
1615 getMVTForLLT(BigTy), getMVTForLLT(LitTy), Idx, TRI);
1616
1617 TypeSize VecRegSize = TypeSize::getScalable(RISCV::RVVBitsPerBlock);
1619 STI.expandVScale(LitTy.getSizeInBits()).getKnownMinValue()));
1620 bool ExactlyVecRegSized =
1621 STI.expandVScale(LitTy.getSizeInBits())
1622 .isKnownMultipleOf(STI.expandVScale(VecRegSize));
1623
1624 // If the Idx has been completely eliminated and this subvector's size is a
1625 // vector register or a multiple thereof, or the surrounding elements are
1626 // undef, then this is a subvector insert which naturally aligns to a vector
1627 // register. These can easily be handled using subregister manipulation.
1628 if (RemIdx == 0 && ExactlyVecRegSized)
1629 return true;
1630
1631 // If the subvector is smaller than a vector register, then the insertion
1632 // must preserve the undisturbed elements of the register. We do this by
1633 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
1634 // (which resolves to a subregister copy), performing a VSLIDEUP to place the
1635 // subvector within the vector register, and an INSERT_SUBVECTOR of that
1636 // LMUL=1 type back into the larger vector (resolving to another subregister
1637 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
1638 // to avoid allocating a large register group to hold our subvector.
1639
1640 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
1641 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
1642 // (in our case undisturbed). This means we can set up a subvector insertion
1643 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
1644 // size of the subvector.
1645 const LLT XLenTy(STI.getXLenVT());
1646 LLT InterLitTy = BigTy;
1647 Register AlignedExtract = BigVec;
1648 unsigned AlignedIdx = Idx - RemIdx;
1650 getLMUL1Ty(BigTy).getSizeInBits())) {
1651 InterLitTy = getLMUL1Ty(BigTy);
1652 // Extract a subvector equal to the nearest full vector register type. This
1653 // should resolve to a G_EXTRACT on a subreg.
1654 AlignedExtract =
1655 MIB.buildExtractSubvector(InterLitTy, BigVec, AlignedIdx).getReg(0);
1656 }
1657
1658 auto Insert = MIB.buildInsertSubvector(InterLitTy, MIB.buildUndef(InterLitTy),
1659 LitVec, 0);
1660
1661 auto [Mask, _] = buildDefaultVLOps(InterLitTy, MIB, MRI);
1662 auto VL = MIB.buildVScale(XLenTy, LitTy.getElementCount().getKnownMinValue());
1663
1664 // If we're inserting into the lowest elements, use a tail undisturbed
1665 // vmv.v.v.
1666 MachineInstrBuilder Inserted;
1667 bool NeedInsertSubvec =
1668 TypeSize::isKnownGT(BigTy.getSizeInBits(), InterLitTy.getSizeInBits());
1669 Register InsertedDst =
1670 NeedInsertSubvec ? MRI.createGenericVirtualRegister(InterLitTy) : Dst;
1671 if (RemIdx == 0) {
1672 Inserted = MIB.buildInstr(RISCV::G_VMV_V_V_VL, {InsertedDst},
1673 {AlignedExtract, Insert, VL});
1674 } else {
1675 auto SlideupAmt = MIB.buildVScale(XLenTy, RemIdx);
1676 // Construct the vector length corresponding to RemIdx + length(LitTy).
1677 VL = MIB.buildAdd(XLenTy, SlideupAmt, VL);
1678 // Use tail agnostic policy if we're inserting over InterLitTy's tail.
1679 ElementCount EndIndex =
1682 if (STI.expandVScale(EndIndex) ==
1683 STI.expandVScale(InterLitTy.getElementCount()))
1685
1686 Inserted =
1687 MIB.buildInstr(RISCV::G_VSLIDEUP_VL, {InsertedDst},
1688 {AlignedExtract, Insert, SlideupAmt, Mask, VL, Policy});
1689 }
1690
1691 // If required, insert this subvector back into the correct vector register.
1692 // This should resolve to an INSERT_SUBREG instruction.
1693 if (NeedInsertSubvec)
1694 MIB.buildInsertSubvector(Dst, BigVec, Inserted, AlignedIdx);
1695
1696 MI.eraseFromParent();
1697 return true;
1698}
1699
1700bool RISCVLegalizerInfo::legalizeBitreverse(MachineInstr &MI,
1701 MachineIRBuilder &MIB) const {
1702 assert(MI.getOpcode() == TargetOpcode::G_BITREVERSE && "Unexpected opcode");
1703
1704 if (!STI.hasStdExtZbkb())
1705 return false;
1706
1707 MachineRegisterInfo &MRI = *MIB.getMRI();
1708
1709 Register Dst = MI.getOperand(0).getReg();
1710 Register Src = MI.getOperand(1).getReg();
1711
1712 if (!MRI.getType(Dst).isScalar(8))
1713 return false;
1714
1715 auto WideSrc = MIB.buildAnyExt(iXLen, Src);
1716 auto Brev = MIB.buildInstr(RISCV::G_BREV8, {iXLen}, {WideSrc.getReg(0)});
1717 MIB.buildTrunc(Dst, Brev.getReg(0));
1718
1719 MI.eraseFromParent();
1720 return true;
1721}
1722
1723static unsigned getRISCVWOpcode(unsigned Opcode) {
1724 switch (Opcode) {
1725 default:
1726 llvm_unreachable("Unexpected opcode");
1727 case TargetOpcode::G_ASHR:
1728 return RISCV::G_SRAW;
1729 case TargetOpcode::G_LSHR:
1730 return RISCV::G_SRLW;
1731 case TargetOpcode::G_SHL:
1732 return RISCV::G_SLLW;
1733 case TargetOpcode::G_SDIV:
1734 return RISCV::G_DIVW;
1735 case TargetOpcode::G_UDIV:
1736 return RISCV::G_DIVUW;
1737 case TargetOpcode::G_UREM:
1738 return RISCV::G_REMUW;
1739 case TargetOpcode::G_ROTL:
1740 return RISCV::G_ROLW;
1741 case TargetOpcode::G_ROTR:
1742 return RISCV::G_RORW;
1743 case TargetOpcode::G_CTLZ:
1744 return RISCV::G_CLZW;
1745 case TargetOpcode::G_CTTZ:
1746 return RISCV::G_CTZW;
1747 case TargetOpcode::G_CTLS:
1748 return RISCV::G_CLSW;
1749 case TargetOpcode::G_FPTOSI:
1750 return RISCV::G_FCVT_W_RV64;
1751 case TargetOpcode::G_FPTOUI:
1752 return RISCV::G_FCVT_WU_RV64;
1753 }
1754}
1755
1756bool RISCVLegalizerInfo::legalizeFpRound(
1757 MachineInstr &MI, LegalizerHelper &Helper, MachineIRBuilder &MIRBuilder,
1758 LostDebugLocObserver &LocObserver) const {
1759 Register Dst = MI.getOperand(0).getReg();
1760 Register Src = MI.getOperand(1).getReg();
1761 MachineRegisterInfo &MRI = *MIRBuilder.getMRI();
1762 LLT Ty = MRI.getType(Src);
1763
1764 // SelectionDAG keeps the libcall when optimizing for size, but there is no
1765 // f16 libcall, so f16 always uses the inline expansion.
1766 if (Ty != LLT::float16() && MIRBuilder.getMF().getFunction().hasOptSize())
1767 return Helper.libcall(MI, LocObserver) == LegalizerHelper::Legalized;
1768
1770 switch (MI.getOpcode()) {
1771 case TargetOpcode::G_FCEIL:
1772 FRM = RISCVFPRndMode::RUP;
1773 break;
1774 case TargetOpcode::G_FFLOOR:
1775 FRM = RISCVFPRndMode::RDN;
1776 break;
1777 case TargetOpcode::G_FRINT:
1778 FRM = RISCVFPRndMode::DYN;
1779 break;
1780 case TargetOpcode::G_INTRINSIC_TRUNC:
1781 FRM = RISCVFPRndMode::RTZ;
1782 break;
1783 case TargetOpcode::G_INTRINSIC_ROUND:
1784 FRM = RISCVFPRndMode::RMM;
1785 break;
1786 case TargetOpcode::G_INTRINSIC_ROUNDEVEN:
1787 FRM = RISCVFPRndMode::RNE;
1788 break;
1789 default:
1790 llvm_unreachable("Unexpected rounding opcode");
1791 }
1792
1793 // Create an integer the size of the mantissa with the MSB set. This and all
1794 // values larger than it have no fractional bits, so emitFROUND passes them
1795 // through instead of converting. NaN is passed through as well.
1796 const fltSemantics &Sem = getFltSemanticForLLT(Ty);
1797 unsigned Precision = APFloat::semanticsPrecision(Sem);
1798 APFloat MaxVal(Sem);
1799 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1800 /*IsSigned=*/false, APFloat::rmNearestTiesToEven);
1801 auto Max = MIRBuilder.buildFConstant(Ty, MaxVal);
1802
1803 // Leave the guarded round trip through the integer domain to emitFROUND, so
1804 // the expansion stays shared with SelectionDAG.
1805 MIRBuilder
1806 .buildInstr(RISCV::G_FROUND, {Dst}, {Src, Max},
1807 MI.getFlags() & MachineInstr::NoFPExcept)
1808 .addImm(FRM);
1809
1810 MI.eraseFromParent();
1811 return true;
1812}
1813
1816 LostDebugLocObserver &LocObserver) const {
1817 MachineIRBuilder &MIRBuilder = Helper.MIRBuilder;
1818 MachineRegisterInfo &MRI = *MIRBuilder.getMRI();
1819 MachineFunction &MF = *MI.getParent()->getParent();
1820 switch (MI.getOpcode()) {
1821 default:
1822 // No idea what to do.
1823 return false;
1824 case TargetOpcode::G_ABS:
1825 return Helper.lowerAbsToMaxNeg(MI);
1826 case TargetOpcode::G_CLMULH:
1827 case TargetOpcode::G_CLMULR: {
1828 assert(STI.is64Bit() &&
1829 MRI.getType(MI.getOperand(0).getReg()) == LLT::scalar(32) &&
1830 "Unexpected custom legalization");
1831 // Shift both inputs by 32 so the full product has 64 trailing zeros.
1832 // Perform CLMULH or CLMULR on the shifted inputs, then extract the upper
1833 // 32 bits of the result.
1834 auto Shift = MIRBuilder.buildConstant(iXLen, 32);
1835 auto LHS = MIRBuilder.buildAnyExt(iXLen, MI.getOperand(1));
1836 auto RHS = MIRBuilder.buildAnyExt(iXLen, MI.getOperand(2));
1837 auto ShiftedLHS = MIRBuilder.buildShl(iXLen, LHS, Shift);
1838 auto ShiftedRHS = MIRBuilder.buildShl(iXLen, RHS, Shift);
1839 auto Product = MIRBuilder.buildInstr(MI.getOpcode(), {iXLen},
1840 {ShiftedLHS, ShiftedRHS});
1841 auto High = MIRBuilder.buildLShr(iXLen, Product, Shift);
1842 MIRBuilder.buildTrunc(MI.getOperand(0), High);
1843 MI.eraseFromParent();
1844 return true;
1845 }
1846 case TargetOpcode::G_CONSTANT: {
1847 const Function &F = MF.getFunction();
1848 // TODO: if PSI and BFI are present, add " ||
1849 // llvm::shouldOptForSize(*CurMBB, PSI, BFI)".
1850 bool ShouldOptForSize = F.hasOptSize();
1851 const ConstantInt *ConstVal = MI.getOperand(1).getCImm();
1852 if (!shouldBeInConstantPool(ConstVal->getValue(), ShouldOptForSize))
1853 return true;
1854 return Helper.lowerConstant(MI);
1855 }
1856 case TargetOpcode::G_SUB:
1857 case TargetOpcode::G_ADD: {
1858 Helper.Observer.changingInstr(MI);
1859 // The G_ANYEXTs below leave the new high bits unconstrained, so no-wrap
1860 // claims proved at the narrow width no longer hold.
1862 Helper.widenScalarSrc(MI, iXLen, 1, TargetOpcode::G_ANYEXT);
1863 Helper.widenScalarSrc(MI, iXLen, 2, TargetOpcode::G_ANYEXT);
1864
1865 Register DstALU = MRI.createGenericVirtualRegister(iXLen);
1866
1867 MachineOperand &MO = MI.getOperand(0);
1868 MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
1869 auto DstSext = MIRBuilder.buildSExtInReg(iXLen, DstALU, 32);
1870
1871 MIRBuilder.buildInstr(TargetOpcode::G_TRUNC, {MO}, {DstSext});
1872 MO.setReg(DstALU);
1873
1874 Helper.Observer.changedInstr(MI);
1875 return true;
1876 }
1877 case TargetOpcode::G_ASHR:
1878 case TargetOpcode::G_LSHR:
1879 case TargetOpcode::G_SHL: {
1880 if (getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI)) {
1881 // We don't need a custom node for shift by constant. Just widen the
1882 // source and the shift amount.
1883 unsigned ExtOpc = TargetOpcode::G_ANYEXT;
1884 if (MI.getOpcode() == TargetOpcode::G_ASHR)
1885 ExtOpc = TargetOpcode::G_SEXT;
1886 else if (MI.getOpcode() == TargetOpcode::G_LSHR)
1887 ExtOpc = TargetOpcode::G_ZEXT;
1888
1889 Helper.Observer.changingInstr(MI);
1890 // The G_ANYEXT leave the new high bits unconstrained, so no-wrap
1891 // claims proved at the narrow width no longer hold.
1892 if (ExtOpc == TargetOpcode::G_ANYEXT)
1894 Helper.widenScalarSrc(MI, iXLen, 1, ExtOpc);
1895 Helper.widenScalarSrc(MI, iXLen, 2, TargetOpcode::G_ZEXT);
1896 Helper.widenScalarDst(MI, iXLen);
1897 Helper.Observer.changedInstr(MI);
1898 return true;
1899 }
1900
1901 Helper.Observer.changingInstr(MI);
1902 Helper.widenScalarSrc(MI, iXLen, 1, TargetOpcode::G_ANYEXT);
1903 Helper.widenScalarSrc(MI, iXLen, 2, TargetOpcode::G_ANYEXT);
1904 Helper.widenScalarDst(MI, iXLen);
1905 MI.setDesc(MIRBuilder.getTII().get(getRISCVWOpcode(MI.getOpcode())));
1906 Helper.Observer.changedInstr(MI);
1907 return true;
1908 }
1909 case TargetOpcode::G_SDIV:
1910 case TargetOpcode::G_UDIV:
1911 case TargetOpcode::G_UREM:
1912 case TargetOpcode::G_ROTL:
1913 case TargetOpcode::G_ROTR: {
1914 Helper.Observer.changingInstr(MI);
1915 Helper.widenScalarSrc(MI, iXLen, 1, TargetOpcode::G_ANYEXT);
1916 Helper.widenScalarSrc(MI, iXLen, 2, TargetOpcode::G_ANYEXT);
1917 Helper.widenScalarDst(MI, iXLen);
1918 MI.setDesc(MIRBuilder.getTII().get(getRISCVWOpcode(MI.getOpcode())));
1919 Helper.Observer.changedInstr(MI);
1920 return true;
1921 }
1922 case TargetOpcode::G_CTLZ:
1923 case TargetOpcode::G_CTTZ:
1924 case TargetOpcode::G_CTLS: {
1925 Helper.Observer.changingInstr(MI);
1926 Helper.widenScalarSrc(MI, iXLen, 1, TargetOpcode::G_ANYEXT);
1927 Helper.widenScalarDst(MI, iXLen);
1928 MI.setDesc(MIRBuilder.getTII().get(getRISCVWOpcode(MI.getOpcode())));
1929 Helper.Observer.changedInstr(MI);
1930 return true;
1931 }
1932 case TargetOpcode::G_FPTOSI:
1933 case TargetOpcode::G_FPTOUI: {
1934 Helper.Observer.changingInstr(MI);
1935 Helper.widenScalarDst(MI, iXLen);
1936 MI.setDesc(MIRBuilder.getTII().get(getRISCVWOpcode(MI.getOpcode())));
1938 Helper.Observer.changedInstr(MI);
1939 return true;
1940 }
1941 case TargetOpcode::G_FPTOSI_SAT:
1942 case TargetOpcode::G_FPTOUI_SAT: {
1943 // Mirror lowerFP_TO_INT_SAT (RISCVISelLowering.cpp): the conversion
1944 // saturates out-of-range values, but we need to select 0 for NaN as
1945 // required by the intrinsics.
1946 Register Dst = MI.getOperand(0).getReg();
1947 Register Src = MI.getOperand(1).getReg();
1948 LLT DstTy = MRI.getType(Dst);
1949 unsigned DstBits = DstTy.getScalarSizeInBits();
1950 bool IsSigned = MI.getOpcode() == TargetOpcode::G_FPTOSI_SAT;
1951
1952 unsigned FCvtOp;
1953 if (DstBits == XLen) {
1954 FCvtOp = IsSigned ? RISCV::G_FCVT_X : RISCV::G_FCVT_XU;
1955 } else {
1956 assert(STI.is64Bit() && "Non-XLen results are only custom on RV64");
1957 FCvtOp = IsSigned ? RISCV::G_FCVT_W_RV64 : RISCV::G_FCVT_WU_RV64;
1958 }
1959
1960 auto FCvt = MIRBuilder.buildInstr(FCvtOp, {iXLen}, {Src})
1961 .addImm(RISCVFPRndMode::RTZ);
1962
1963 // RISC-V G_FCMP results are XLen wide, and so are G_SELECT conditions.
1964 auto IsNaN = MIRBuilder.buildFCmp(CmpInst::FCMP_UNO, iXLen, Src, Src);
1965
1966 Register FCvtReg = FCvt.getReg(0);
1967 if (DstBits != XLen)
1968 FCvtReg = MIRBuilder.buildTrunc(DstTy, FCvtReg).getReg(0);
1969
1970 MIRBuilder.buildSelect(Dst, IsNaN, MIRBuilder.buildConstant(DstTy, 0),
1971 FCvtReg);
1972
1973 MI.eraseFromParent();
1974 return true;
1975 }
1976 case TargetOpcode::G_LROUND: {
1977 // The (i32 any_lround) Pat is IsRV32-only; on RV64 lower to
1978 // riscv_fcvt_w_rv64 with FRM_RMM.
1979 Helper.Observer.changingInstr(MI);
1980 Helper.widenScalarDst(MI, iXLen);
1981 MI.setDesc(MIRBuilder.getTII().get(RISCV::G_FCVT_W_RV64));
1983 Helper.Observer.changedInstr(MI);
1984 return true;
1985 }
1986 case TargetOpcode::G_FCEIL:
1987 case TargetOpcode::G_FFLOOR:
1988 case TargetOpcode::G_FRINT:
1989 case TargetOpcode::G_INTRINSIC_TRUNC:
1990 case TargetOpcode::G_INTRINSIC_ROUND:
1991 case TargetOpcode::G_INTRINSIC_ROUNDEVEN:
1992 return legalizeFpRound(MI, Helper, MIRBuilder, LocObserver);
1993 case TargetOpcode::G_READCYCLECOUNTER:
1994 case TargetOpcode::G_READSTEADYCOUNTER:
1995 return legalizeReadCounter(MI, MIRBuilder, Helper.Observer);
1996 case TargetOpcode::G_IS_FPCLASS: {
1997 Register GISFPCLASS = MI.getOperand(0).getReg();
1998 Register Src = MI.getOperand(1).getReg();
1999 const MachineOperand &ImmOp = MI.getOperand(2);
2000 MachineIRBuilder MIB(MI);
2001
2002 // Turn LLVM IR's floating point classes to that in RISC-V,
2003 // by simply rotating the 10-bit immediate right by two bits.
2004 APInt GFpClassImm(10, static_cast<uint64_t>(ImmOp.getImm()));
2005 auto FClassMask = MIB.buildConstant(iXLen, GFpClassImm.rotr(2).zext(XLen));
2006 auto ConstZero = MIB.buildConstant(iXLen, 0);
2007
2008 auto GFClass = MIB.buildInstr(RISCV::G_FCLASS, {iXLen}, {Src});
2009 auto And = MIB.buildAnd(iXLen, GFClass, FClassMask);
2010 MIB.buildICmp(CmpInst::ICMP_NE, GISFPCLASS, And, ConstZero);
2011
2012 MI.eraseFromParent();
2013 return true;
2014 }
2015 case TargetOpcode::G_BRJT:
2016 return legalizeBRJT(MI, MIRBuilder);
2017 case TargetOpcode::G_VASTART:
2018 return legalizeVAStart(MI, MIRBuilder);
2019 case TargetOpcode::G_VSCALE:
2020 return legalizeVScale(MI, MIRBuilder);
2021 case TargetOpcode::G_ZEXT:
2022 case TargetOpcode::G_SEXT:
2023 case TargetOpcode::G_ANYEXT:
2024 return legalizeExt(MI, MIRBuilder);
2025 case TargetOpcode::G_SPLAT_VECTOR:
2026 return legalizeSplatVector(MI, MIRBuilder);
2027 case TargetOpcode::G_EXTRACT_SUBVECTOR:
2028 return legalizeExtractSubvector(MI, MIRBuilder);
2029 case TargetOpcode::G_INSERT_SUBVECTOR:
2030 return legalizeInsertSubvector(MI, Helper, MIRBuilder);
2031 case TargetOpcode::G_BITREVERSE:
2032 return legalizeBitreverse(MI, MIRBuilder);
2033 case TargetOpcode::G_LOAD:
2034 case TargetOpcode::G_STORE:
2035 return legalizeLoadStore(MI, Helper, MIRBuilder);
2036 }
2037
2038 llvm_unreachable("expected switch to return");
2039}
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
uint64_t Imm
This file declares a class to represent arbitrary precision floating point values and provide a varie...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
bpf unwind lower
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Declares convenience wrapper classes for interpreting MachineInstr instances as specific generic oper...
const HexagonInstrInfo * TII
#define _
IRTranslator LLVM IR MI
unsigned Opc
Implement a low-level type suitable for MachineInstr level instruction selection.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Contains matchers for matching SSA Machine Instructions.
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
This file declares the MachineIRBuilder class.
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
uint64_t High
uint64_t IntrinsicInst * II
#define P(N)
ppc ctr loops verify
MachineRegisterInfo & MRI
static LLT getLMUL1Ty(LLT VecTy)
static MachineInstrBuilder buildAllOnesMask(LLT VecTy, const SrcOp &VL, MachineIRBuilder &MIB, MachineRegisterInfo &MRI)
Creates an all ones mask suitable for masking a vector of type VecTy with vector length VL.
static std::pair< MachineInstrBuilder, MachineInstrBuilder > buildDefaultVLOps(LLT VecTy, MachineIRBuilder &MIB, MachineRegisterInfo &MRI)
Gets the two common "VL" operands: an all-ones mask and the vector length.
static LegalityPredicate typeIsLegalBoolVec(unsigned TypeIdx, std::initializer_list< LLT > BoolVecTys, const RISCVSubtarget &ST)
static MachineInstrBuilder buildSplatSplitS64WithVL(const DstOp &Dst, const SrcOp &Passthru, const SrcOp &Scalar, const SrcOp &VL, MachineIRBuilder &MIB, MachineRegisterInfo &MRI)
static LegalityPredicate typeIsLegalIntOrFPVec(unsigned TypeIdx, std::initializer_list< LLT > IntOrFPVecTys, const RISCVSubtarget &ST)
static MachineInstrBuilder buildSplatPartsS64WithVL(const DstOp &Dst, const SrcOp &Passthru, Register Lo, Register Hi, const SrcOp &VL, MachineIRBuilder &MIB, MachineRegisterInfo &MRI)
static LLT getMaskTypeFor(LLT VecTy)
Return the type of the mask type suitable for masking the provided vector type.
static LegalityPredicate typeIsLegalPtrVec(unsigned TypeIdx, std::initializer_list< LLT > PtrVecTys, const RISCVSubtarget &ST)
static unsigned getRISCVWOpcode(unsigned Opcode)
This file declares the targeting of the Machinelegalizer class for RISC-V.
MachineInstr *& Lo
Value * LHS
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:379
static LLVM_ABI unsigned int semanticsPrecision(const fltSemantics &)
Definition APFloat.cpp:609
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
LLVM_ABI APInt rotr(unsigned rotateAmt) const
Rotate right by rotateAmt.
Definition APInt.cpp:1199
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1582
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
This is the shared class of boolean and integer constants.
Definition Constants.h:87
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
static constexpr ElementCount getScalable(ScalarTy MinVal)
Definition TypeSize.h:309
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
Definition Function.h:708
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
Abstract class that contains various methods for clients to notify about changes.
virtual void changingInstr(MachineInstr &MI)=0
This instruction is about to be mutated in some way.
virtual void changedInstr(MachineInstr &MI)=0
This instruction was mutated in some way.
virtual void erasingInstr(MachineInstr &MI)=0
An instruction is about to be erased.
Register getReg(unsigned Idx) const
Access the Idx'th operand as a register and return it.
static constexpr LLT float64()
Get a 64-bit IEEE double value.
constexpr bool isScalableVector() const
Returns true if the LLT is a scalable vector.
constexpr unsigned getScalarSizeInBits() const
constexpr bool isScalar() const
static constexpr LLT scalable_vector(unsigned MinNumElements, unsigned ScalarSizeInBits)
Get a low-level scalable vector of some number of elements and element width.
constexpr LLT changeElementType(LLT NewEltTy) const
If this type is a vector, return a vector with the same number of elements but the new element type.
static constexpr LLT vector(ElementCount EC, unsigned ScalarSizeInBits)
Get a low-level vector of some number of elements and element width.
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
static constexpr LLT float128()
Get a 128-bit IEEE quad value.
constexpr bool isVector() const
static constexpr LLT pointer(unsigned AddressSpace, unsigned SizeInBits)
Get a low-level pointer in the given address space.
constexpr TypeSize getSizeInBits() const
Returns the total size of the type. Must only be called on sized types.
constexpr ElementCount getElementCount() const
static constexpr LLT float16()
Get a 16-bit IEEE half value.
static LLT integer(unsigned SizeInBits)
static constexpr LLT bfloat16()
LLT getElementType() const
Returns the vector's element type. Only valid for vector types.
static constexpr LLT float32()
Get a 32-bit IEEE float value.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
LegalizeRuleSet & maxScalar(unsigned TypeIdx, const LLT Ty)
Ensure the scalar is at most as wide as Ty.
LegalizeRuleSet & lower()
The instruction is lowered.
LegalizeRuleSet & clampScalar(unsigned TypeIdx, const LLT MinTy, const LLT MaxTy)
Limit the range of scalar sizes to MinTy and MaxTy.
LegalizeRuleSet & alwaysLegal()
LegalizeRuleSet & customIf(LegalityPredicate Predicate)
LegalizeRuleSet & widenScalarToNextPow2(unsigned TypeIdx, unsigned MinSize=0)
Widen the scalar to the next power of two that is at least MinSize.
LegalizeRuleSet & customFor(std::initializer_list< LLT > Types)
LLVM_ABI void widenScalarSrc(MachineInstr &MI, LLT WideTy, unsigned OpIdx, unsigned ExtOpcode)
Legalize a single operand OpIdx of the machine instruction MI as a Use by extending the operand's typ...
LLVM_ABI LegalizeResult lowerAbsToMaxNeg(MachineInstr &MI)
LLVM_ABI LegalizeResult bitcast(MachineInstr &MI, unsigned TypeIdx, LLT Ty)
Legalize an instruction by replacing the value type.
@ Legalized
Instruction has been legalized and the MachineFunction changed.
GISelChangeObserver & Observer
To keep track of changes made by the LegalizerHelper.
LLVM_ABI LegalizeResult widenScalar(MachineInstr &MI, unsigned TypeIdx, LLT WideTy)
Legalize an instruction by performing the operation on a wider scalar type (for example a 16-bit addi...
LLVM_ABI LegalizeResult libcall(MachineInstr &MI, LostDebugLocObserver &LocObserver)
Legalize an instruction by emiting a runtime library call instead.
MachineIRBuilder & MIRBuilder
Expose MIRBuilder so clients can set their own RecordInsertInstruction functions.
LLVM_ABI LegalizeResult lowerConstant(MachineInstr &MI)
LLVM_ABI void widenScalarDst(MachineInstr &MI, LLT WideTy, unsigned OpIdx=0, unsigned TruncOpcode=TargetOpcode::G_TRUNC)
Legalize a single operand OpIdx of the machine instruction MI as a Def by extending the operand's typ...
LegalizeRuleSet & getActionDefinitionsBuilder(unsigned Opcode)
Get the action definition builder for the given opcode.
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode.
Definition MCInstrInfo.h:89
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LLT MemTy, Align BaseAlignment, const MMOMetadata &Metadata=MMOMetadata(), SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
const MachineJumpTableInfo * getJumpTableInfo() const
getJumpTableInfo - Return the jump table info object for the current function.
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
Helper class to build MachineInstr.
void setInsertPt(MachineBasicBlock &MBB, MachineBasicBlock::iterator II)
Set the insertion point before the specified position.
MachineInstrBuilder buildAdd(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, std::optional< unsigned > Flags=std::nullopt)
Build and insert Res = G_ADD Op0, Op1.
MachineInstrBuilder buildUndef(const DstOp &Res)
Build and insert Res = IMPLICIT_DEF.
MachineInstrBuilder buildUnmerge(ArrayRef< LLT > Res, const SrcOp &Op)
Build and insert Res0, ... = G_UNMERGE_VALUES Op.
MachineInstrBuilder buildSelect(const DstOp &Res, const SrcOp &Tst, const SrcOp &Op0, const SrcOp &Op1, std::optional< unsigned > Flags=std::nullopt)
Build and insert a Res = G_SELECT Tst, Op0, Op1.
MachineInstrBuilder buildMul(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, std::optional< unsigned > Flags=std::nullopt)
Build and insert Res = G_MUL Op0, Op1.
MachineInstrBuilder buildInsertSubvector(const DstOp &Res, const SrcOp &Src0, const SrcOp &Src1, unsigned Index)
Build and insert Res = G_INSERT_SUBVECTOR Src0, Src1, Idx.
MachineInstrBuilder buildAnd(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1)
Build and insert Res = G_AND Op0, Op1.
const TargetInstrInfo & getTII()
MachineInstrBuilder buildICmp(CmpInst::Predicate Pred, const DstOp &Res, const SrcOp &Op0, const SrcOp &Op1, std::optional< unsigned > Flags=std::nullopt)
Build and insert a Res = G_ICMP Pred, Op0, Op1.
MachineInstrBuilder buildLShr(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, std::optional< unsigned > Flags=std::nullopt)
MachineBasicBlock::iterator getInsertPt()
Current insertion point for new instructions.
MachineInstrBuilder buildZExt(const DstOp &Res, const SrcOp &Op, std::optional< unsigned > Flags=std::nullopt)
Build and insert Res = G_ZEXT Op.
MachineInstrBuilder buildVScale(const DstOp &Res, unsigned MinElts)
Build and insert Res = G_VSCALE MinElts.
MachineInstrBuilder buildIntToPtr(const DstOp &Dst, const SrcOp &Src)
Build and insert a G_INTTOPTR instruction.
MachineInstrBuilder buildLoad(const DstOp &Res, const SrcOp &Addr, MachineMemOperand &MMO)
Build and insert Res = G_LOAD Addr, MMO.
MachineInstrBuilder buildPtrAdd(const DstOp &Res, const SrcOp &Op0, const SrcOp &Op1, std::optional< unsigned > Flags=std::nullopt)
Build and insert Res = G_PTR_ADD Op0, Op1.
virtual MachineInstrBuilder buildFConstant(const DstOp &Res, const ConstantFP &Val)
Build and insert Res = G_FCONSTANT Val.
MachineInstrBuilder buildShl(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, std::optional< unsigned > Flags=std::nullopt)
MachineInstrBuilder buildStore(const SrcOp &Val, const SrcOp &Addr, MachineMemOperand &MMO)
Build and insert G_STORE Val, Addr, MMO.
MachineInstrBuilder buildInstr(unsigned Opcode)
Build and insert <empty> = Opcode <empty>.
MachineInstrBuilder buildFrameIndex(const DstOp &Res, int Idx)
Build and insert Res = G_FRAME_INDEX Idx.
MachineFunction & getMF()
Getter for the function we currently build.
MachineInstrBuilder buildMergeValues(const DstOp &Res, ArrayRef< Register > Ops)
Build and insert Res = G_MERGE_VALUES Op0, ...
MachineInstrBuilder buildTrunc(const DstOp &Res, const SrcOp &Op, std::optional< unsigned > Flags=std::nullopt)
Build and insert Res = G_TRUNC Op.
void setDebugLoc(const DebugLoc &DL)
Set the debug location to DL for all the next build instructions.
const MachineBasicBlock & getMBB() const
Getter for the basic block we currently build.
MachineInstrBuilder buildAnyExt(const DstOp &Res, const SrcOp &Op)
Build and insert Res = G_ANYEXT Op0.
MachineRegisterInfo * getMRI()
Getter for MRI.
MachineInstrBuilder buildCopy(const DstOp &Res, const SrcOp &Op)
Build and insert Res = COPY Op.
MachineInstrBuilder buildExtractSubvector(const DstOp &Res, const SrcOp &Src, unsigned Index)
Build and insert Res = G_EXTRACT_SUBVECTOR Src, Idx0.
const DataLayout & getDataLayout() const
MachineInstrBuilder buildBrIndirect(Register Tgt)
Build and insert G_BRINDIRECT Tgt.
MachineInstrBuilder buildSplatVector(const DstOp &Res, const SrcOp &Val)
Build and insert Res = G_SPLAT_VECTOR Val.
MachineInstrBuilder buildLoadInstr(unsigned Opcode, const DstOp &Res, const SrcOp &Addr, MachineMemOperand &MMO)
Build and insert Res = <opcode> Addr, MMO.
virtual MachineInstrBuilder buildConstant(const DstOp &Res, const ConstantInt &Val)
Build and insert Res = G_CONSTANT Val.
MachineInstrBuilder buildFCmp(CmpInst::Predicate Pred, const DstOp &Res, const SrcOp &Op0, const SrcOp &Op1, std::optional< unsigned > Flags=std::nullopt)
Build and insert a Res = G_FCMP PredOp0, Op1.
MachineInstrBuilder buildSExtInReg(const DstOp &Res, const SrcOp &Op, int64_t ImmOp)
Build and insert Res = G_SEXT_INREG Op, ImmOp.
Register getReg(unsigned Idx) const
Get the register for the operand index.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
Representation of each machine instruction.
LLVM_ABI unsigned getEntrySize(const DataLayout &TD) const
getEntrySize - Return the size of each entry in the jump table.
@ EK_LabelDifference32
EK_LabelDifference32 - Each entry is the address of the block minus the address of the jump table.
@ EK_Custom32
EK_Custom32 - Each entry is a 32-bit value that is custom lowered by the TargetLowering::LowerCustomJ...
@ EK_BlockAddress
EK_BlockAddress - Each entry is a plain address of block, e.g.: .word LBB123.
LLVM_ABI unsigned getEntryAlignment(const DataLayout &TD) const
getEntryAlignment - Return the alignment of each entry in the jump table.
A description of a memory reference used in the backend.
@ MOLoad
The memory access reads data.
@ MOStore
The memory access writes data.
MachineOperand class - Representation of each machine instruction operand.
int64_t getImm() const
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
static MachineOperand CreateImm(int64_t Val)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
LLT getType(Register Reg) const
Get the low-level type of Reg or LLT{} if Reg is not a generic (target independent) virtual register.
LLVM_ABI void setRegClass(Register Reg, const TargetRegisterClass *RC)
setRegClass - Set the register class of the specified virtual register.
LLVM_ABI Register createGenericVirtualRegister(LLT Ty, StringRef Name="")
Create and return a new generic virtual register with low-level type Ty.
bool legalizeCustom(LegalizerHelper &Helper, MachineInstr &MI, LostDebugLocObserver &LocObserver) const override
Called for instructions with the Custom LegalizationAction.
bool legalizeIntrinsic(LegalizerHelper &Helper, MachineInstr &MI) const override
RISCVLegalizerInfo(const RISCVSubtarget &ST)
RISCVMachineFunctionInfo - This class is derived from MachineFunctionInfo and contains private RISCV-...
static std::pair< unsigned, unsigned > decomposeSubvectorInsertExtractToSubRegs(MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, const RISCVRegisterInfo *TRI)
static RISCVVType::VLMUL getLMUL(MVT VT)
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Register getReg() const
bool allowsMemoryAccessForAlignment(LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *Fast=nullptr) const
This function returns true if the memory access is aligned or if the target allows this specific unal...
static constexpr TypeSize getScalable(ScalarTy MinimumSize)
Definition TypeSize.h:355
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
static constexpr bool isKnownGT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:224
constexpr LeafTy divideCoefficientBy(ScalarTy RHS) const
We do not provide the '/' operator here because division for polynomial types does not work in the sa...
Definition TypeSize.h:253
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI LegalityPredicate isScalar(unsigned TypeIdx)
True iff the specified type index is a scalar.
LLVM_ABI LegalityPredicate typeInSet(unsigned TypeIdx, std::initializer_list< LLT > TypesInit)
True iff the given type index is one of the specified types.
LLVM_ABI LegalityPredicate immIs(unsigned ImmIdx, int64_t Imm)
True iff the immediate at the given index has the specified value.
Predicate any(Predicate P0, Predicate P1)
True iff P0 or P1 are true.
LLVM_ABI LegalityPredicate sizeIs(unsigned TypeIdx, unsigned Size)
True if the total bitwidth of the specified type index is Size bits.
Predicate all(Predicate P0, Predicate P1)
True iff P0 and P1 are true.
LLVM_ABI LegalityPredicate typeIs(unsigned TypeIdx, LLT TypesInit)
True iff the given type index is the specified type.
LLVM_ABI LegalityPredicate scalarWiderThan(unsigned TypeIdx, unsigned Size)
True iff the specified type index is a scalar that's wider than the given size.
LLVM_ABI LegalityPredicate immInSet(unsigned ImmIdx, std::initializer_list< int64_t > ImmsInit)
True iff the immediate at the given index has one of the specified values.
LLVM_ABI LegalityPredicate scalarNarrowerThan(unsigned TypeIdx, unsigned Size)
True iff the specified type index is a scalar that's narrower than the given size.
LLVM_ABI LegalizeMutation changeTo(unsigned TypeIdx, LLT Ty)
Select this specific type for the given type index.
ImplicitDefMatch m_GImplicitDef()
bool mi_match(Reg R, const MachineRegisterInfo &MRI, Pattern &&P)
InstSeq generateInstSeq(int64_t Val, const MCSubtargetInfo &STI)
InstSeq generateTwoRegInstSeq(int64_t Val, const MCSubtargetInfo &STI, unsigned &ShiftAmt, unsigned &AddOpc)
SmallVector< Inst, 8 > InstSeq
Definition RISCVMatInt.h:43
LLVM_ABI std::pair< unsigned, bool > decodeVLMUL(VLMUL VLMul)
static constexpr unsigned RVVBitsPerBlock
Invariant opcodes: All instruction sets have these as their low opcodes.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI Type * getTypeForLLT(LLT Ty, LLVMContext &C)
Get the type back from LLT.
Definition Utils.cpp:2138
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
LLVM_ABI bool isAllOnesOrAllOnesSplat(const MachineInstr &MI, const MachineRegisterInfo &MRI, bool AllowUndefs=false)
Return true if the value is a constant -1 integer or a splatted vector of a constant -1 integer (with...
Definition Utils.cpp:1716
LLVM_ABI const llvm::fltSemantics & getFltSemanticForLLT(LLT Ty)
Get the appropriate floating point arithmetic semantic based on the bit size of the given scalar LLT.
@ Load
The value being inserted comes from a load (InsertElement only).
LLVM_ABI MVT getMVTForLLT(LLT Ty)
Get a rough equivalent of an MVT for a given LLT.
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
LLVM_ABI bool isNullOrNullSplat(const MachineInstr &MI, const MachineRegisterInfo &MRI, bool AllowUndefs=false)
Return true if the value is a constant 0 integer or a splatted vector of a constant 0 integer (with n...
Definition Utils.cpp:1700
unsigned Log2_64(uint64_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:332
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
std::function< bool(const LegalityQuery &)> LegalityPredicate
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
@ And
Bitwise or logical AND of integers.
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI std::optional< ValueAndVReg > getIConstantVRegValWithLookThrough(Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs=true)
If VReg is defined by a statically evaluable chain of instructions rooted on a G_CONSTANT returns its...
Definition Utils.cpp:440
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:202
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
static LLVM_ABI EVT getEVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
The LegalityQuery object bundles together all the information that's needed to decide whether a given...
ArrayRef< LLT > Types
Matching combinators.
This class contains a discriminated union of information about pointers in memory operands,...
static LLVM_ABI MachinePointerInfo getJumpTable(MachineFunction &MF)
Return a MachinePointerInfo record that refers to a jump table entry.